Some docstrings.
9198
def signal(e):
    
    callback = find_handler(e)
    if callback is None:
        if _activate_debugger:
            print 'Handler for error {0} not found'.format(type(e))
            traceback.print_stack()
            set_trace()
        raise e
    else:
        return callback(e)
1046742
def documentation(self, add_to=None, version=None, prefix="", base_url="", url=""):
        """"""
        doc = OrderedDict() if add_to is None else add_to

        usage = self.interface.spec.__doc__
        if usage:
            doc['usage'] = usage

        for example in self.examples:
            example_text = "{0}{1}{2}{3}".format(prefix, base_url, '/v{0}'.format(version) if version else '', url)
            if isinstance(example, str):
                example_text += "?{0}".format(example)
            doc_examples = doc.setdefault('examples', [])
            if not example_text in doc_examples:
                doc_examples.append(example_text)

        doc = super().documentation(doc)

        if getattr(self, 'output_doc', ''):
            doc['outputs']['type'] = self.output_doc

        return doc
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
292464
def description(self):
        """"""
        lines = []
        for line in self.__doc__.split('\n')[2:]:
            line = line.strip()
            if line:
                lines.append(line)
        return ' '.join(lines)
820106
def docstr(self, prefix='', include_label=True):
        """"""
        return '\n'.join([x.docstr(prefix, include_label) for x in self])
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
1237468
def _split_docstring(self, docstring):
        """"""

        lines = docstring.strip().splitlines()

        synopsis = lines[0].strip()
        body = textwrap.dedent('\n'.join(lines[2:]))

        # Remove RST preformatted text markers.
        body = body.replace('\n::\n', '')
        body = body.replace('::\n', ':')

        return (synopsis, body)
1215794
def split_docstring(docstring):
    
    docstring_list = [line.strip() for line in docstring.splitlines()]
    description_list = list(
        takewhile(lambda line: not (line.startswith(':') or
                                    line.startswith('@inherit')), docstring_list))
    description = ' '.join(description_list).strip()
    first_field_line_number = len(description_list)

    fields = []
    if first_field_line_number >= len(docstring_list):
        return description, fields  # only description, without any field
    last_field_lines = [docstring_list[first_field_line_number]]

    for line in docstring_list[first_field_line_number + 1:]:
        if line.strip().startswith(':') or line.strip().startswith('@inherit'):
            fields.append(' '.join(last_field_lines))
            last_field_lines = [line]
        else:
            last_field_lines.append(line)

    fields.append(' '.join(last_field_lines))
    return description, fields
649697
def trim_docstring(docstring):
    
    if not docstring or not docstring.strip():
        return ""
    # Convert tabs to spaces and split into lines
    lines = docstring.expandtabs().splitlines()
    indent = min(len(line) - len(line.lstrip()) for line in lines if line.lstrip())
    trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]]
    return "\n".join(trimmed).strip()
903872
def get_docstr_list(red):
    """"""
    docstr_list = []
    for n in red.find_all("string"):
        if n.value.startswith('"""'):
            docstr_list.append(n)
    return docstr_list
1197866
def doc_to_help(doc):
  """"""

  # Get rid of starting and ending white space. Using lstrip() or even
  # strip() could drop more than maximum of first line and right space
  # of last line.
  doc = doc.strip()

  # Get rid of all empty lines.
  whitespace_only_line = re.compile('^[ \t]+$', re.M)
  doc = whitespace_only_line.sub('', doc)

  # Cut out common space at line beginnings.
  doc = trim_docstring(doc)

  # Just like this module's comment, comments tend to be aligned somehow.
  # In other words they all start with the same amount of white space.
  # 1) keep double new lines;
  # 2) keep ws after new lines if not empty line;
  # 3) all other new lines shall be changed to a space;
  # Solution: Match new lines between non white space and replace with space.
  doc = re.sub(r'(?<=\S)\n(?=\S)', ' ', doc, flags=re.M)

  return doc
63260
def render_docstring(self):
        """"""
        default = (' = ' + str(self.default)) if self.default else ''
        opt = 'optional' if self.is_optional else ''
        can_be = ' '.join(self.possible_values) if self.possible_values else ''
        can_be = 'one of [{}]'.format(can_be) if can_be else ''
        type_ = 'of type "' + str(self.type) + '"'
        res = ' '.join([opt, '"' + self.field + '"', default, type_, can_be, '\n'])
        return res.replace('  ', ' ').lstrip()
285032
def _print_formatted_docstring(self, docstring, f):
    """"""
    lines = self._remove_docstring_indent(docstring)

    # Output the lines, identifying "Args" and other section blocks.
    i = 0

    def _at_start_of_section():
      """Returns the header if lines[i] is at start of a docstring section."""
      l = lines[i]
      match = _section_re.match(l)
      if match and i + 1 < len(
          lines) and lines[i + 1].startswith(" "):
        return match.group(1)
      else:
        return None

    while i < len(lines):
      l = lines[i]

      section_header = _at_start_of_section()
      if section_header:
        if i == 0 or lines[i-1]:
          print("", file=f)
        # Use at least H4 to keep these out of the TOC.
        print("##### " + section_header + ":", file=f)
        print("", file=f)
        i += 1
        outputting_list = False
        while i < len(lines):
          l = lines[i]
          # A new section header terminates the section.
          if _at_start_of_section():
            break
          match = _arg_re.match(l)
          if match:
            if not outputting_list:
              # We need to start a list. In Markdown, a blank line needs to
              # precede a list.
              print("", file=f)
              outputting_list = True
            suffix = l[len(match.group()):].lstrip()
            print("*  <b>`" + match.group(1) + "`</b>: " + suffix, file=f)
          else:
            # For lines that don't start with _arg_re, continue the list if it
            # has enough indentation.
            outputting_list &= l.startswith("   ")
            print(l, file=f)
          i += 1
      else:
        print(l, file=f)
        i += 1
1065407
def parse_docstring(whatever_has_docstring):
    ''''''
    try:
        summary, notes = whatever_has_docstring.__doc__.split('\n', 1)
        notes = dedent(notes).replace('\n', ' ')
    except ValueError:
        summary = whatever_has_docstring.__doc__.strip()
        notes = ''
    return summary, notes
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)
1329480
def _handle_docstrings(self):
        
        #Docstrings have to be continuous sets of lines that start with !!
        #When they change in any way (i.e. any of the three modes), we 
        #have to reparse the entire block because it has XML dependencies
        #Because of that, the cached version of the docstrings is actually
        #pointless and we only need to focus on the buffered.
        blocks = self._docstring_getblocks()

        if len(blocks) == 0:
            return

        xmldict = self._docstring_parse(blocks)
        delta = 0

        if isinstance(self.docelement, Module):
            delta += self.docparser.rt_update_module(xmldict, self.docelement)
        else:
            #We just need to handle the type and executable internal defs.
            if self.docelement.name in xmldict:
                docs = self.docparser.to_doc(xmldict[self.docelement.name][0],
                                             self.docelement.name)
                self.docparser.process_memberdocs(docs, self.docelement, False)
            #Also update the docstrings for any embedded types or executables.
            if isinstance(self.docelement, Executable):
                delta += self.docparser.process_embedded(xmldict, 
                                                         self.docelement, False)

        #Finally, we need to handle the overall character length change
        #that this update caused to the element first and then for the
        #operation as a whole for updating the module and its children.
        buffertot = sum([len(self.context.bufferstr[i]) for i in self._doclines])
        cachedtot = 0
    
        for i in range(self.icached[0],self.icached[1]):
            if self.docparser.RE_DOCS.match(self.context.cachedstr[i]):
                cachedtot += len(self.context.cachedstr[i])

        self.length = buffertot - cachedtot

        if delta == 0:
            #The update must have been to members variables of the module or the
            #executables/types. The element who owns the members is going to get
            #missed when the module updates its children.
            self.docelement.end += self.length
        else:
            #All the individual elements have been updated already, so just
            #set the length change for this operation.
            self.docdelta = delta
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}}