Basic docstring formatted for Sphinx docs
761915
def sphinx(self):
        """"""
        if callable(self.default):
            default_val = self.default()
            default_str = 'new instance of {}'.format(
                default_val.__class__.__name__
            )
        else:
            default_val = self.default
            default_str = '{}'.format(self.default)
        try:
            if default_val is None or default_val is undefined:
                default_str = ''
            elif len(default_val) == 0:                                        #pylint: disable=len-as-condition
                default_str = ''
            else:
                default_str = ', Default: {}'.format(default_str)
        except TypeError:
            default_str = ', Default: {}'.format(default_str)

        prop_doc = super(Property, self).sphinx()
        return '{doc}{default}'.format(doc=prop_doc, default=default_str)
25184
def core_module_docstrings(
    include_core=True, include_user=False, config=None, format="md"
):
    
    paths = {}
    docstrings = {}
    if include_core:
        for file in os.listdir(modules_directory()):
            if file.endswith(".py"):
                name = file[:-3]
                if name != "__init__":
                    paths[name] = (os.path.join(modules_directory(), file), "core")

    if include_user:
        # include user modules
        for include_path in sorted(config["include_paths"]):
            for file in sorted(os.listdir(include_path)):
                if not file.endswith(".py"):
                    continue
                name = file[:-3]
                paths[name] = (os.path.join(include_path, file), "user")
    for name in paths:
        path, module_type = paths[name]
        with open(path) as f:
            try:
                module = ast.parse(f.read())
            except SyntaxError:
                # there is a syntax error so ignore module
                continue
            raw_docstring = ast.get_docstring(module)

            # prevent issue when no docstring exists
            if raw_docstring is None:
                continue

            # remove any sample outputs
            parts = re.split("^SAMPLE OUTPUT$", raw_docstring, flags=re.M)
            docstring = parts[0]

            if format == "md":
                docstring = [
                    d for d in _from_docstring_md(str(docstring).strip().split("\n"))
                ]
            elif format == "rst":
                docstring = [
                    d for d in _from_docstring_rst(str(docstring).strip().split("\n"))
                ]
            else:
                raise Exception("`md` and `rst` format supported only")

            docstrings[name] = docstring + ["\n"]
    return docstrings
120378
def check_docstring(self, method):
        ''''''
        mn = method.__name__
        if method.__doc__ is None:
            return ['Missing docstring for method "{}"'.format(mn)]
1352534
def trim_docstring(docstring):
    """"""
    if not docstring:
        return ''

    # Convert tabs to spaces (following the normal Python rules)
    # and split into a list of lines:
    lines = docstring.expandtabs().splitlines()

    # Determine minimum indentation (first line doesn't count):
    indent = maxsize
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))

    # Remove indentation (first line is special):
    lines[0] = lines[0].strip()
    if indent < maxsize:
        index = 1
        for line in lines[1:]:
            lines[index] = line[indent:].rstrip()
            index += 1

    # Strip off trailing and leading blank lines:
    while lines and not lines[-1]:
        del lines[-1]
    while lines and not lines[0]:
        del lines[0]

    # Return a single string:
    return '\n'.join(lines)
967428
def docstr(self, prefix='', include_label=True):
        
        outstr = "%s%s : {%s, %s}\n" %(prefix, self.name, str(self.default),
            str(self.dtype).replace("<type '", '').replace("'>", '')) + \
            "%s    %s" %(prefix, self.description)
        if include_label:
            outstr += " Label: %s" %(self.label)
        return outstr
464497
def is_docstring(self, node):
        """"""
        return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
                                             isinstance(node.value, ast.Str))
859097
def generate_type_docs(types):
    
    output = StringIO()

    indent = "  "  # 2

    # loop through the basic types and add them to the RAML formatted output
    for type_name in types:

        if types[type_name].get("type") != None:

            output.write(indent + type_name + ":\n")

            indent += "  "  # 4

            type_safe = types[type_name]["type"].replace(" ", "_")

            # if we are dealing with a list, set type to array and specify type of items
            if types[type_name].get("items") != None:
                items_safe = types[type_name]["items"].replace(" ", "_")
                # if items_safe == "base":
                #     items_safe = "object"
                output.write(indent + "type: " + type_safe + "\n")
                output.write(indent + "items: " + items_safe + "\n")

            # otherwise, use the type per normal
            else:
                output.write(indent + "type: " + type_safe + "\n")

            # add the description
            if types[type_name].get("description") != None:
                output.write(indent + "description: " + types[type_name]["description"] + "\n")

            indent = indent[:-2]    # 2

    type_docs = output.getvalue()
    output.close()
    return type_docs
1240379
def napoleon_to_sphinx(docstring, **config_params):
    
    if "napoleon_use_param" not in config_params:
        config_params["napoleon_use_param"] = False

    if "napoleon_use_rtype" not in config_params:
        config_params["napoleon_use_rtype"] = False

    config = Config(**config_params)

    return str(GoogleDocstring(docstring, config))
1311243
function formatSpecDescription(spec) {
    const egText = spec.example ? ` (eg. "${spec.example}")` : ''
    const docsText = spec.docs ? `. See ${spec.docs}` : ''
    return `${spec.desc}${egText}${docsText}` || ''
}
820106
def docstr(self, prefix='', include_label=True):
        """"""
        return '\n'.join([x.docstr(prefix, include_label) for x in self])
130549
def construct_docstring(options):
        """"""
        s = "\nParameters\n"
        s += "----------\n\n"
        for key, opt in options.items():
            s += "%s : %s\n      %s [%s]\n" % (key, str(opt[2]),
                                               str(opt[1]), str(opt[0]))
        return s
161380
def get_description(cls) -> str:
        
        if cls.__doc__ is None:
            raise ValueError('No docstring found for {}'.format(cls.__name__))
        return cls.__doc__.strip()
316755
def _format_docstring(self, text):
        
        #The only complication we have here is that we don't want to break words up.
        words = text.split()
        result = []
        line = []
        cumline = 0
        for word in words:
            if len(word) + 1 + cumline < 90:
                line.append(word)
                cumline += len(word) + 1
            else:
                result.append(' '.join(line))
                cumline = len(word) + 1
                line = [word]

        return result
349563
def parse_docstring(docstring, cls=None):
    
    def_arg_dict = lambda: {'description': None,
                            'type_name': None,
                            'required': False,
                            }
    description, fields_lines = split_docstring(docstring)
    arguments_dict = defaultdict(def_arg_dict)
    return_value_types = []
    #parse fields
    return_description = ''
    for docstring_line in fields_lines:
        if _ignored_field(docstring_line):
            continue
        #parse inherits
        if docstring_line.startswith('@inherits'):
            if not cls:
                raise MethodParsingException()
            inherit_tmp = docstring_line.split(None, 1)[1]
            inherit_str = inherit_tmp.split(':class:', 1)[1]
            result = _parse_inherit(cls, inherit_str)

            description = description or result['description']
            for arg_name, update_dict in result['arguments'].items():
                arguments_dict[arg_name].update(update_dict)
            return_value_types = result['return']['type_name']
            return_description = result['return']['description']
        #parse return value
        elif docstring_line.startswith(':rtype:'):
            class_name = __get_class_name(cls)
            types_str = docstring_line.split(None, 1)[1]
            return_value_types = types_str.replace('\n', '').strip(':').strip()
            if return_value_types.startswith('class:`.'):
                return_value_types = return_value_types.replace('class:`.', 'class:`'+class_name+'.')
        #parse return description
        elif docstring_line.startswith(':return:'):
            return_description = docstring_line.split(None, 1)[1].strip()
        #parse arguments
        else:
            arg_name, update_dict = _parse_docstring_field(cls, docstring_line)
            arguments_dict[arg_name].update(update_dict)
    #check fields
    _check_arguments_dict(arguments_dict)
    if not return_value_types:
        raise MethodParsingException('Can not get return types for method')
    return {'description': description,
            'arguments': arguments_dict,
            'return': {'description': return_description,
                       'type_name': return_value_types}}
467568
def process_docstring(app, what, name, obj, options, lines):
    """"""
    # pylint: disable=unused-argument
    # pylint: disable=too-many-arguments
    lines.extend(_format_contracts(what=what, obj=obj))
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
604197
def process_docstring(app, what, name, obj, options, lines):
    
    aliases = getattr(app, "_sigaliases", None)
    if aliases is None:
        if what == "module":
            aliases = get_aliases(inspect.getsource(obj).splitlines())
            app._sigaliases = aliases

    sig_marker = ":" + SIG_FIELD + ":"
    is_class = what in ("class", "exception")

    signature = extract_signature("\n".join(lines))
    if signature is None:
        if not is_class:
            return

        init_method = getattr(obj, "__init__")
        init_doc = init_method.__doc__
        init_lines = init_doc.splitlines()[1:]
        if len(init_lines) > 1:
            init_doc = textwrap.dedent("\n".join(init_lines[1:]))
            init_lines = init_doc.splitlines()
        if sig_marker not in init_doc:
            return

        sig_started = False
        for line in init_lines:
            if line.lstrip().startswith(sig_marker):
                sig_started = True
            if sig_started:
                lines.append(line)
        signature = extract_signature("\n".join(lines))

    if is_class:
        obj = init_method

    param_types, rtype, _ = parse_signature(signature)
    param_names = [p for p in inspect.signature(obj).parameters]

    if is_class and (param_names[0] == "self"):
        del param_names[0]

    # if something goes wrong, don't insert parameter types
    if len(param_names) == len(param_types):
        for name, type_ in zip(param_names, param_types):
            find = ":param %(name)s:" % {"name": name}
            alias = aliases.get(type_)
            if alias is not None:
                type_ = "*%(type)s* :sup:`%(alias)s`" % {"type": type_, "alias": alias}
            for i, line in enumerate(lines):
                if line.startswith(find):
                    lines.insert(i, ":type %(name)s: %(type)s" % {"name": name, "type": type_})
                    break

    if not is_class:
        for i, line in enumerate(lines):
            if line.startswith((":return:", ":returns:")):
                lines.insert(i, ":rtype: " + rtype)
                break

    # remove the signature field
    sig_start = 0
    while sig_start < len(lines):
        if lines[sig_start].startswith(sig_marker):
            break
        sig_start += 1
    sig_end = sig_start + 1
    while sig_end < len(lines):
        if (not lines[sig_end]) or (lines[sig_end][0] != " "):
            break
        sig_end += 1
    for i in reversed(range(sig_start, sig_end)):
        del lines[i]