Instruction:
Explain what the following Python 3 code does
def b32decode(s, casefold=False, map01=None):
    quanta, leftover = divmod(len(s), 8)
    if leftover:
        raise TypeError('Incorrect padding')
    # Handle section 2.4 zero and one mapping.  The flag map01 will be either
    # False, or the character to map the digit 1 (one) to.  It should be
    # either L (el) or I (eye).
    if map01:
        s = s.translate(string.maketrans(b'01', b'O' + map01))
    if casefold:
        s = s.upper()
    # Strip off pad characters from the right.  We need to count the pad
    # characters because this will tell us how many null bytes to remove from
    # the end of the decoded string.
    padchars = 0
    mo = re.search('(?P<pad>[=]*)$', s)
    if mo:
        padchars = len(mo.group('pad'))
        if padchars > 0:
            s = s[:-padchars]
    # Now decode the full quanta
    parts = []
    acc = 0
    shift = 35
    for c in s:
        val = _b32rev.get(c)
        if val is None:
            raise TypeError('Non-base32 digit found')
        acc += _b32rev[c] << shift
        shift -= 5
        if shift < 0:
            parts.append(binascii.unhexlify('%010x' % acc))
            acc = 0
            shift = 35
    # Process the last, partial quanta
    last = binascii.unhexlify('%010x' % acc)
    if padchars == 0:
        last = ''                       # No characters
    elif padchars == 1:
        last = last[:-1]
    elif padchars == 3:
        last = last[:-2]
    elif padchars == 4:
        last = last[:-3]
    elif padchars == 6:
        last = last[:-4]
    else:
        raise TypeError('Incorrect padding')
    parts.append(last)
    return EMPTYSTRING.join(parts)

Response: Decode a Base32 encoded string.


Instruction:
Can you implement a function in Python 3 that
decodes a Base16 encoded string.

Response:
def b16decode(s, casefold=False):
    """Decode a Base16 encoded string.

    s is the string to decode.  Optional casefold is a flag specifying whether
    a lowercase alphabet is acceptable as input.  For security purposes, the
    default is False.

    The decoded string is returned.  A TypeError is raised if s is
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if casefold:
        s = s.upper()
    if re.search('[^0-9A-F]', s):
        raise TypeError('Non-base16 digit found')
    return binascii.unhexlify(s)


Instruction:
How would you code a function in Python 3 to
encode a string into multiple lines of base - 64 data.

Response:
def encodestring(s):
    """Encode a string into multiple lines of base-64 data."""
    pieces = []
    for i in range(0, len(s), MAXBINSIZE):
        chunk = s[i : i + MAXBINSIZE]
        pieces.append(binascii.b2a_base64(chunk))
    return "".join(pieces)


Instruction:
Can you implement a function in Python 3 that
returns the source line from the source file at the given line number.

Response:
def source_line(self, lineno):
        """
        Returns line ``lineno`` from source, taking ``first_line`` into account,
        or raises :exc:`IndexError` if ``lineno`` is out of range.
        """
        line_begins = self._extract_line_begins()
        lineno = lineno - self.first_line
        if lineno >= 0 and lineno + 1 < len(line_begins):
            first, last = line_begins[lineno:lineno + 2]
            return self.source[first:last]
        elif lineno >= 0 and lineno < len(line_begins):
            return self.source[line_begins[-1]:]
        else:
            raise IndexError


Instruction:
Here you have a function in Python 3, explain what it does
def decompose_position(self, offset):
        line_begins = self._extract_line_begins()
        lineno = bisect.bisect_right(line_begins, offset) - 1
        if offset >= 0 and offset <= len(self.source):
            return lineno + self.first_line, offset - line_begins[lineno]
        else:
            raise IndexError

Response: Decomposes a character offset into a line column tuple.


Instruction:
Make a summary of the following Python 3 code
def chain(self, expanded_from):
        return Range(self.source_buffer, self.begin_pos, self.begin_pos,
                     expanded_from=expanded_from)

Response:
Returns a range identical to this one but indicating that that
        it was expanded from the range expanded_from.


Instruction:
Here you have a function in Python 3, explain what it does
def begin(self):
        return Range(self.source_buffer, self.begin_pos, self.begin_pos,
                     expanded_from=self.expanded_from)

Response: Returns a zero - length range located just before the beginning of this range.


Instruction:
Can you create a Python 3 function that
returns a zero - length range located just after the end of this range.

Response:
def end(self):
        """
        Returns a zero-length range located just after the end of this range.
        """
        return Range(self.source_buffer, self.end_pos, self.end_pos,
                     expanded_from=self.expanded_from)


Instruction:
Can you create a Python 3 function that
returns the column number of the beginning of this range.

Response:
def column(self):
        """
        Returns a zero-based column number of the beginning of this range.
        """
        line, column = self.source_buffer.decompose_position(self.begin_pos)
        return column


Instruction:
Write a Python 3 function that can
return a [ begin end ) tuple describing the range of columns spanned by this range.

Response:
def column_range(self):
        """
        Returns a [*begin*, *end*) tuple describing the range of columns spanned
        by this range. If range spans more than one line, returned *end* is
        the last column of the line.
        """
        if self.begin().line() == self.end().line():
            return self.begin().column(), self.end().column()
        else:
            return self.begin().column(), len(self.begin().source_line()) - 1


Instruction:
Can you generate a brief explanation for the following Python 3 code
def line(self):
        line, column = self.source_buffer.decompose_position(self.begin_pos)
        return line

Response: Returns the line number of the beginning of this range.


Instruction:
Can you create a Python 3 function that
returns the smallest possible range spanning both this range and other.

Response:
def join(self, other):
        """
        Returns the smallest possible range spanning both this range and other.
        Raises :exc:`ValueError` if the ranges do not belong to the same
        :class:`Buffer`.
        """
        if self.source_buffer != other.source_buffer:
            raise ValueError
        if self.expanded_from == other.expanded_from:
            expanded_from = self.expanded_from
        else:
            expanded_from = None
        return Range(self.source_buffer,
                     min(self.begin_pos, other.begin_pos),
                     max(self.end_pos, other.end_pos),
                     expanded_from=expanded_from)


Instruction:
Here you have a function in Python 3, explain what it does
def source_lines(self):
        return [self.source_buffer.source_line(line)
                for line in range(self.line(), self.end().line() + 1)]

Response: Returns the source lines of the entirety of this range.


Instruction:
Here you have a function in Python 3, explain what it does
def rewrite(self):
        self._sort()
        self._check()

        rewritten, pos = [], 0
        for range, replacement in self.ranges:
            rewritten.append(self.buffer.source[pos:range.begin_pos])
            rewritten.append(replacement)
            pos = range.end_pos
        rewritten.append(self.buffer.source[pos:])

        return Buffer("".join(rewritten), self.buffer.name, self.buffer.first_line)

Response: Return the rewritten source. May raise : class:`RewriterConflict`.


Instruction:
Make a summary of the following Python 3 code
def compare(left, right, compare_locs=False):
    if type(left) != type(right):
        return False

    if isinstance(left, ast.AST):
        for field in left._fields:
            if not compare(getattr(left, field), getattr(right, field)):
                return False

        if compare_locs:
            for loc in left._locs:
                if getattr(left, loc) != getattr(right, loc):
                    return False

        return True
    elif isinstance(left, list):
        if len(left) != len(right):
            return False

        for left_elt, right_elt in zip(left, right):
            if not compare(left_elt, right_elt):
                return False

        return True
    else:
        return left == right

Response: A comparison function that compares two objects.


Instruction:
Given the following Python 3 function, write the documentation
def visit(self, obj):
        if isinstance(obj, list):
            return [self.visit(elt) for elt in obj]
        elif isinstance(obj, ast.AST):
            return self._visit_one(obj)

Response: Visit a node or a list of nodes. Other values are ignored.


Instruction:
Make a summary of the following Python 3 code
def generic_visit(self, node):
        for field_name in node._fields:
            setattr(node, field_name, self.visit(getattr(node, field_name)))
        return node

Response: Called by the visitor function to visit the node.


Instruction:
Create a Python 3 function to
visit a node or a list of nodes. Other values are ignored.

Response:
def visit(self, obj):
        """Visit a node or a list of nodes. Other values are ignored"""
        if isinstance(obj, list):
            return list(filter(lambda x: x is not None, map(self.visit, obj)))
        elif isinstance(obj, ast.AST):
            return self._visit_one(obj)
        else:
            return obj


Instruction:
How would you explain what the following Python 3 function does
def acquire(self, waitflag=None):
        if waitflag is None or waitflag:
            self.locked_status = True
            return True
        else:
            if not self.locked_status:
                self.locked_status = True
                return True
            else:
                return False

Response: This method is used to acquire a key from the cache.


Instruction:
Given the following Python 3 function, write the documentation
def round_to_nearest(x):
  int_part = int(x)
  frac_part = x - int_part
  if frac_part > 0.5 or frac_part == 0.5 and int_part & 1 == 1:
    int_part += 1
  return int_part

Response: Python 3 style round a float x to the nearest int


Instruction:
Write a Python 3 script to
convert a 32 - bit integer created by float_pack into a Python float.

Response:
def float_unpack(Q, size, le):
  """Convert a 32-bit or 64-bit integer created
  by float_pack into a Python float."""

  if size == 8:
    MIN_EXP = -1021  # = sys.float_info.min_exp
    MAX_EXP = 1024   # = sys.float_info.max_exp
    MANT_DIG = 53    # = sys.float_info.mant_dig
    BITS = 64
  elif size == 4:
    MIN_EXP = -125   # C's FLT_MIN_EXP
    MAX_EXP = 128    # FLT_MAX_EXP
    MANT_DIG = 24    # FLT_MANT_DIG
    BITS = 32
  else:
    raise ValueError("invalid size value")

  if Q >> BITS:
    raise ValueError("input out of range")

  # extract pieces
  sign = Q >> BITS - 1
  exp = (Q & ((1 << BITS - 1) - (1 << MANT_DIG - 1))) >> MANT_DIG - 1
  mant = Q & ((1 << MANT_DIG - 1) - 1)

  if exp == MAX_EXP - MIN_EXP + 2:
    # nan or infinity
    result = float('nan') if mant else float('inf')
  elif exp == 0:
    # subnormal or zero
    result = math.ldexp(float(mant), MIN_EXP - MANT_DIG)
  else:
    # normal
    mant += 1 << MANT_DIG - 1
    result = math.ldexp(float(mant), exp + MIN_EXP - MANT_DIG - 1)
  return -result if sign else result


Instruction:
Here you have a function in Python 3, explain what it does
def float_pack(x, size):

  if size == 8:
    MIN_EXP = -1021  # = sys.float_info.min_exp
    MAX_EXP = 1024   # = sys.float_info.max_exp
    MANT_DIG = 53    # = sys.float_info.mant_dig
    BITS = 64
  elif size == 4:
    MIN_EXP = -125   # C's FLT_MIN_EXP
    MAX_EXP = 128    # FLT_MAX_EXP
    MANT_DIG = 24    # FLT_MANT_DIG
    BITS = 32
  else:
    raise ValueError("invalid size value")

  sign = math.copysign(1.0, x) < 0.0
  if math.isinf(x):
    mant = 0
    exp = MAX_EXP - MIN_EXP + 2
  elif math.isnan(x):
    mant = 1 << (MANT_DIG - 2)  # other values possible
    exp = MAX_EXP - MIN_EXP + 2
  elif x == 0.0:
    mant = 0
    exp = 0
  else:
    m, e = math.frexp(abs(x))  # abs(x) == m * 2**e
    exp = e - (MIN_EXP - 1)
    if exp > 0:
      # Normal case.
      mant = round_to_nearest(m * (1 << MANT_DIG))
      mant -= 1 << MANT_DIG - 1
    else:
      # Subnormal case.
      if exp + MANT_DIG - 1 >= 0:
        mant = round_to_nearest(m * (1 << exp + MANT_DIG - 1))
      else:
        mant = 0
      exp = 0

    # Special case: rounding produced a MANT_DIG-bit mantissa.
    assert 0 <= mant <= 1 << MANT_DIG - 1
    if mant == 1 << MANT_DIG - 1:
      mant = 0
      exp += 1

    # Raise on overflow (in some circumstances, may want to return
    # infinity instead).
    if exp >= MAX_EXP - MIN_EXP + 2:
      raise OverflowError("float too large to pack in this format")

  # check constraints
  assert 0 <= mant < 1 << MANT_DIG - 1
  assert 0 <= exp <= MAX_EXP - MIN_EXP + 2
  assert 0 <= sign <= 1
  return ((sign << BITS - 1) | (exp << MANT_DIG - 1)) | mant

Response:
Convert a Python float x into a 64 - bit unsigned integer
 with the same byte representation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calcsize(fmt):

  formatdef, endianness, i = getmode(fmt)
  num = 0
  result = 0
  while i < len(fmt):
    num, i = getNum(fmt, i)
    cur = fmt[i]
    try:
      format = formatdef[cur]
    except KeyError:
      raise StructError("%s is not a valid format" % cur)
    if num != None:
      result += num * format['size']
    else:
      result += format['size']
    num = 0
    i += 1
  return result

Response: Calculate size of a C struct described by format string fmt.


Instruction:
How would you explain what the following Python 3 function does
def pack(fmt, *args):
  formatdef, endianness, i = getmode(fmt)
  args = list(args)
  n_args = len(args)
  result = []
  while i < len(fmt):
    num, i = getNum(fmt, i)
    cur = fmt[i]
    try:
      format = formatdef[cur]
    except KeyError:
      raise StructError("%s is not a valid format" % cur)
    if num == None:
      num_s = 0
      num = 1
    else:
      num_s = num

    if cur == 'x':
      result += [b'\0' * num]
    elif cur == 's':
      if isinstance(args[0], bytes):
        padding = num - len(args[0])
        result += [args[0][:num] + b'\0' * padding]
        args.pop(0)
      else:
        raise StructError("arg for string format not a string")
    elif cur == 'p':
      if isinstance(args[0], bytes):
        padding = num - len(args[0]) - 1

        if padding > 0:
          result += [bytes([len(args[0])]) + args[0]
                     [:num - 1] + b'\0' * padding]
        else:
          if num < 255:
            result += [bytes([num - 1]) + args[0][:num - 1]]
          else:
            result += [bytes([255]) + args[0][:num - 1]]
        args.pop(0)
      else:
        raise StructError("arg for string format not a string")

    else:
      if len(args) < num:
        raise StructError("insufficient arguments to pack")
      for var in args[:num]:
        result += [format['pack'](var, format['size'], endianness)]
      args = args[num:]
    num = None
    i += 1
  if len(args) != 0:
    raise StructError("too many arguments for pack format")
  return b''.join(result)

Response: pack returns a string containing values v1 v2... packed according to fmt.


Instruction:
Write a Python 3 function for
unpacking the string containing packed C structure data according to the format string fmt.

Response:
def unpack(fmt, data):
  """unpack(fmt, string) -> (v1, v2, ...)
     Unpack the string, containing packed C structure data, according
     to fmt.  Requires len(string)==calcsize(fmt).
     See struct.__doc__ for more on format strings."""
  formatdef, endianness, i = getmode(fmt)
  j = 0
  num = 0
  result = []
  length = calcsize(fmt)
  if length != len(data):
    raise StructError("unpack str size does not match format")
  while i < len(fmt):
    num, i = getNum(fmt, i)
    cur = fmt[i]
    i += 1
    try:
      format = formatdef[cur]
    except KeyError:
      raise StructError("%s is not a valid format" % cur)

    if not num:
      num = 1

    if cur == 'x':
      j += num
    elif cur == 's':
      result.append(data[j:j + num])
      j += num
    elif cur == 'p':
      n = data[j]
      if n >= num:
        n = num - 1
      result.append(data[j + 1:j + n + 1])
      j += num
    else:
      for n in range(num):
        result += [format['unpack'](data, j, format['size'], endianness)]
        j += format['size']

  return tuple(result)


Instruction:
Can you implement a function in Python 3 that
returns the human - readable representation of the diagnostic in the source file.

Response:
def render(self, only_line=False, colored=False):
        """
        Returns the human-readable location of the diagnostic in the source,
        the formatted message, the source line corresponding
        to ``location`` and a line emphasizing the problematic
        locations in the source line using ASCII art, as a list of lines.
        Appends the result of calling :meth:`render` on ``notes``, if any.

        For example: ::

            <input>:1:8-9: error: cannot add integer and string
            x + (1 + "a")
                 ~ ^ ~~~

        :param only_line: (bool) If true, only print line number, not line and column range
        """
        source_line = self.location.source_line().rstrip("\n")
        highlight_line = bytearray(re.sub(r"[^\t]", " ", source_line), "utf-8")

        for hilight in self.highlights:
            if hilight.line() == self.location.line():
                lft, rgt = hilight.column_range()
                highlight_line[lft:rgt] = bytearray("~", "utf-8") * (rgt - lft)

        lft, rgt = self.location.column_range()
        if rgt == lft: # Expand zero-length ranges to one ^
            rgt = lft + 1
        highlight_line[lft:rgt] = bytearray("^", "utf-8") * (rgt - lft)

        if only_line:
            location = "%s:%s" % (self.location.source_buffer.name, self.location.line())
        else:
            location = str(self.location)

        notes = list(self.notes)
        if self.level != "note":
            expanded_location = self.location.expanded_from
            while expanded_location is not None:
                notes.insert(0, Diagnostic("note",
                    "expanded from here", {},
                    self.location.expanded_from))
                expanded_location = expanded_location.expanded_from

        rendered_notes = reduce(list.__add__, [note.render(only_line, colored)
                                               for note in notes], [])
        if colored:
            if self.level in ("error", "fatal"):
                level_color = 31 # red
            elif self.level == "warning":
                level_color = 35 # magenta
            else: # level == "note"
                level_color = 30 # gray
            return [
                "\x1b[1;37m{}: \x1b[{}m{}:\x1b[37m {}\x1b[0m".
                    format(location, level_color, self.level, self.message()),
                source_line,
                "\x1b[1;32m{}\x1b[0m".format(highlight_line.decode("utf-8"))
            ] + rendered_notes
        else:
            return [
                "{}: {}: {}".format(location, self.level, self.message()),
                source_line,
                highlight_line.decode("utf-8")
            ] + rendered_notes


Instruction:
Explain what the following Python 3 code does
def decode(input, output, encoding):
    if encoding == 'base64':
        import base64
        return base64.decode(input, output)
    if encoding == 'quoted-printable':
        import quopri
        return quopri.decode(input, output)
    if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'):
        import uu
        return uu.decode(input, output)
    if encoding in ('7bit', '8bit'):
        return output.write(input.read())
    if encoding in decodetab:
        pipethrough(input, decodetab[encoding], output)
    else:
        raise ValueError, \
              'unknown Content-Transfer-Encoding: %s' % encoding

Response: Decode common content - transfer - encodings.


Instruction:
Can you generate the documentation for the following Python 3 function
def encode(input, output, encoding):
    if encoding == 'base64':
        import base64
        return base64.encode(input, output)
    if encoding == 'quoted-printable':
        import quopri
        return quopri.encode(input, output, 0)
    if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'):
        import uu
        return uu.encode(input, output)
    if encoding in ('7bit', '8bit'):
        return output.write(input.read())
    if encoding in encodetab:
        pipethrough(input, encodetab[encoding], output)
    else:
        raise ValueError, \
              'unknown Content-Transfer-Encoding: %s' % encoding

Response: Encode common content - transfer - encodings.


Instruction:
Create a Python 3 function to
print the list of tuples as returned by extract_tb or CTYPE extract_stack as a formatted stack trace to the given file.

Response:
def print_list(extracted_list, file=None):
    """Print the list of tuples as returned by extract_tb() or
    extract_stack() as a formatted stack trace to the given file."""
    if file is None:
        file = sys.stderr
    for filename, lineno, name, line in extracted_list:
        _print(file,
               '  File "%s", line %d, in %s' % (filename,lineno,name))
        if line:
            _print(file, '    %s' % line.strip())


Instruction:
Here you have a function in Python 3, explain what it does
def format_list(extracted_list):
    list = []
    for filename, lineno, name, line in extracted_list:
        item = '  File "%s", line %d, in %s\n' % (filename,lineno,name)
        if line:
            item = item + '    %s\n' % line.strip()
        list.append(item)
    return list

Response: Format a list of tuples for printing.


Instruction:
Write a Python 3 function for
printing up to limit stack trace entries from the traceback tb.

Response:
def print_tb(tb, limit=None, file=None):
    """Print up to 'limit' stack trace entries from the traceback 'tb'.

    If 'limit' is omitted or None, all entries are printed.  If 'file'
    is omitted or None, the output goes to sys.stderr; otherwise
    'file' should be an open file or file-like object with a write()
    method.
    """
    if file is None:
        file = sys.stderr
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    n = 0
    while tb is not None and (limit is None or n < limit):
        f = tb.tb_frame
        lineno = tb.tb_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        _print(file,
               '  File "%s", line %d, in %s' % (filename, lineno, name))
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        if line: _print(file, '    ' + line.strip())
        tb = tb.tb_next
        n = n+1


Instruction:
Can you generate a brief explanation for the following Python 3 code
def print_exception(etype, value, tb, limit=None, file=None):
    if file is None:
        # TODO: Use sys.stderr when that's implemented.
        file = open('/dev/stderr', 'w')
        #file = sys.stderr
    if tb:
        _print(file, 'Traceback (most recent call last):')
        print_tb(tb, limit, file)
    lines = format_exception_only(etype, value)
    for line in lines:
        _print(file, line, '')

Response: Print an exception to file.


Instruction:
Can you implement a function in Python 3 that
formats a stack trace and the exception information.

Response:
def format_exception(etype, value, tb, limit = None):
    """Format a stack trace and the exception information.

    The arguments have the same meaning as the corresponding arguments
    to print_exception().  The return value is a list of strings, each
    ending in a newline and some containing internal newlines.  When
    these lines are concatenated and printed, exactly the same text is
    printed as does print_exception().
    """
    if tb:
        list = ['Traceback (most recent call last):\n']
        list = list + format_tb(tb, limit)
    else:
        list = []
    list = list + format_exception_only(etype, value)
    return list


Instruction:
Can you tell what is the following Python 3 function doing
def format_exception_only(etype, value):

    # An instance should not have a meaningful value parameter, but
    # sometimes does, particularly for string exceptions, such as
    # >>> raise string1, string2  # deprecated
    #
    # Clear these out first because issubtype(string1, SyntaxError)
    # would raise another exception and mask the original problem.
    if (isinstance(etype, BaseException) or
#        isinstance(etype, types.InstanceType) or
        etype is None or type(etype) is str):
        return [_format_final_exc_line(etype, value)]

    stype = etype.__name__

    if not issubclass(etype, SyntaxError):
        return [_format_final_exc_line(stype, value)]

    # It was a syntax error; show exactly where the problem was found.
    lines = []
    try:
        msg, (filename, lineno, offset, badline) = value.args
    except Exception:
        pass
    else:
        filename = filename or "<string>"
        lines.append('  File "%s", line %d\n' % (filename, lineno))
        if badline is not None:
            lines.append('    %s\n' % badline.strip())
            if offset is not None:
                caretspace = badline.rstrip('\n')
                offset = min(len(caretspace), offset) - 1
                caretspace = caretspace[:offset].lstrip()
                # non-space whitespace (likes tabs) must be kept for alignment
                caretspace = ((c.isspace() and c or ' ') for c in caretspace)
                lines.append('    %s^\n' % ''.join(caretspace))
        value = msg

    lines.append(_format_final_exc_line(stype, value))
    return lines

Response: Format an exception only exception in a list of strings.


Instruction:
Write a Python 3 script to
return a list of a single line for format_exception_only

Response:
def _format_final_exc_line(etype, value):
    """Return a list of a single line -- normal case for format_exception_only"""
    valuestr = _some_str(value)
    if value is None or not valuestr:
        line = "%s\n" % etype
    else:
        line = "%s: %s\n" % (etype, valuestr)
    return line


Instruction:
Make a summary of the following Python 3 code
def print_exc(limit=None, file=None):
    if file is None:
        # TODO: Use sys.stderr when that's implemented.
        file = open('/dev/stderr', 'w')
        #file = sys.stderr
    try:
        etype, value, tb = sys.exc_info()
        print_exception(etype, value, tb, limit, file)
    finally:
        etype = value = tb = None

Response: Print the current exception and all its sub - exceptions.


Instruction:
Here you have a function in Python 3, explain what it does
def print_stack(f=None, limit=None, file=None):
    if f is None:
        try:
            raise ZeroDivisionError
        except ZeroDivisionError:
            f = sys.exc_info()[2].tb_frame.f_back
    print_list(extract_stack(f, limit), file)

Response: Print a stack trace from its invocation point.


Instruction:
How would you explain what the following Python 3 function does
def extract_stack(f=None, limit = None):
    if f is None:
        try:
            raise ZeroDivisionError
        except ZeroDivisionError:
            f = sys.exc_info()[2].tb_frame.f_back
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    list = []
    n = 0
    while f is not None and (limit is None or n < limit):
        lineno = f.f_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        if line: line = line.strip()
        else: line = None
        list.append((filename, lineno, name, line))
        f = f.f_back
        n = n+1
    list.reverse()
    return list

Response: Extract the raw traceback from the current stack frame.


Instruction:
Create a Python 3 function to
initialize internal state of the random number generator.

Response:
def seed(self, a=None):
        """Initialize internal state of the random number generator.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or is an int or long, hash(a) is used instead.
        Hash values for some types are nondeterministic when the
        PYTHONHASHSEED environment variable is enabled.
        """

        super(Random, self).seed(a)
        self.gauss_next = None


Instruction:
How would you explain what the following Python 3 function does
def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=1L<<BPF):

        # This code is a bit messy to make it fast for the
        # common case while still doing adequate error checking.
        istart = _int(start)
        if istart != start:
            raise ValueError, "non-integer arg 1 for randrange()"
        if stop is None:
            if istart > 0:
                if istart >= _maxwidth:
                    return self._randbelow(istart)
                return _int(self.random() * istart)
            raise ValueError, "empty range for randrange()"

        # stop argument supplied.
        istop = _int(stop)
        if istop != stop:
            raise ValueError, "non-integer stop for randrange()"
        width = istop - istart
        if step == 1 and width > 0:
            # Note that
            #     int(istart + self.random()*width)
            # instead would be incorrect.  For example, consider istart
            # = -2 and istop = 0.  Then the guts would be in
            # -2.0 to 0.0 exclusive on both ends (ignoring that random()
            # might return 0.0), and because int() truncates toward 0, the
            # final result would be -1 or 0 (instead of -2 or -1).
            #     istart + int(self.random()*width)
            # would also be incorrect, for a subtler reason:  the RHS
            # can return a long, and then randrange() would also return
            # a long, but we're supposed to return an int (for backward
            # compatibility).

            if width >= _maxwidth:
                return _int(istart + self._randbelow(width))
            return _int(istart + _int(self.random()*width))
        if step == 1:
            raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)

        # Non-unit step argument supplied.
        istep = _int(step)
        if istep != step:
            raise ValueError, "non-integer step for randrange()"
        if istep > 0:
            n = (width + istep - 1) // istep
        elif istep < 0:
            n = (width + istep + 1) // istep
        else:
            raise ValueError, "zero step for randrange()"

        if n <= 0:
            raise ValueError, "empty range for randrange()"

        if n >= _maxwidth:
            return istart + istep*self._randbelow(n)
        return istart + istep*_int(self.random() * n)

Response: Return a random item from the range start to stop.


Instruction:
How would you implement a function in Python 3 that
shuffles list x in place

Response:
def shuffle(self, x, random=None):
        """x, random=random.random -> shuffle list x in place; return None.

        Optional arg random is a 0-argument function returning a random
        float in [0.0, 1.0); by default, the standard random.random.

        """

        if random is None:
            random = self.random
        _int = int
        for i in reversed(xrange(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = _int(random() * (i+1))
            x[i], x[j] = x[j], x[i]


Instruction:
Explain what the following Python 3 code does
def _slotnames(cls):

    # Get the value from a cache in the class if possible
    names = cls.__dict__.get("__slotnames__")
    if names is not None:
        return names

    # Not cached -- calculate the value
    names = []
    if not hasattr(cls, "__slots__"):
        # This class has no slots
        pass
    else:
        # Slots found -- gather slot names from all base classes
        for c in cls.__mro__:
            if "__slots__" in c.__dict__:
                slots = c.__dict__['__slots__']
                # if class has a single slot, it can be given as a string
                if isinstance(slots, basestring):
                    slots = (slots,)
                for name in slots:
                    # special descriptors
                    if name in ("__dict__", "__weakref__"):
                        continue
                    # mangled names
                    elif name.startswith('__') and not name.endswith('__'):
                        names.append('_%s%s' % (c.__name__, name))
                    else:
                        names.append(name)

    # Cache the outcome in the class if at all possible
    try:
        cls.__slotnames__ = names
    except:
        pass # But don't die if we can't

    return names

Response: Return a list of slot names for a given class.


Instruction:
Given the following Python 3 function, write the documentation
def add_extension(module, name, code):
    code = int(code)
    if not 1 <= code <= 0x7fffffff:
        raise ValueError, "code out of range"
    key = (module, name)
    if (_extension_registry.get(key) == code and
        _inverted_registry.get(code) == key):
        return # Redundant registrations are benign
    if key in _extension_registry:
        raise ValueError("key %s is already registered with code %s" %
                         (key, _extension_registry[key]))
    if code in _inverted_registry:
        raise ValueError("code %s is already in use for key %s" %
                         (code, _inverted_registry[code]))
    _extension_registry[key] = code
    _inverted_registry[code] = key

Response: Register an extension code.


Instruction:
Explain what the following Python 3 code does
def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):
    """Update a wrapper function to look like the wrapped function

       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        setattr(wrapper, attr, getattr(wrapped, attr))
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

Response: Update a wrapper function to look like the original function that is updated by the given parameters.


Instruction:
Can you implement a function in Python 3 that
converts a cmp = function into a key = function

Response:
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K


Instruction:
Can you generate the documentation for the following Python 3 function
def unquote(s):
    if len(s) > 1:
        if s.startswith('"') and s.endswith('"'):
            return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
        if s.startswith('<') and s.endswith('>'):
            return s[1:-1]
    return s

Response: Remove quotes from a string.


Instruction:
Write a Python 3 script for
parsing an address into a tuple.

Response:
def parseaddr(address):
    """Parse an address into a (realname, mailaddr) tuple."""
    a = AddressList(address)
    lst = a.addresslist
    if not lst:
        return (None, None)
    return lst[0]


Instruction:
How would you explain what the following Python 3 function does
def mktime_tz(data):
    if data[9] is None:
        # No zone info, so localtime is better assumption than GMT
        return time.mktime(data[:8] + (-1,))
    else:
        t = time.mktime(data[:8] + (0,))
        return t - data[9] - time.timezone

Response: Turn a 10 - tuple as returned by parsedate_tz() into a UTC timestamp.


Instruction:
Explain what the following Python 3 code does
def formatdate(timeval=None):
    if timeval is None:
        timeval = time.time()
    timeval = time.gmtime(timeval)
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
            ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
            timeval[2],
            ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
                                timeval[0], timeval[3], timeval[4], timeval[5])

Response: Returns a date string for the given timeval.


Instruction:
Implement a function in Python 3 to
rewind the file to the start of the body.

Response:
def rewindbody(self):
        """Rewind the file to the start of the body (if seekable)."""
        if not self.seekable:
            raise IOError, "unseekable file"
        self.fp.seek(self.startofbody)


Instruction:
Make a summary of the following Python 3 code
def readheaders(self):
        self.dict = {}
        self.unixfrom = ''
        self.headers = lst = []
        self.status = ''
        headerseen = ""
        firstline = 1
        startofline = unread = tell = None
        if hasattr(self.fp, 'unread'):
            unread = self.fp.unread
        elif self.seekable:
            tell = self.fp.tell
        while 1:
            if tell:
                try:
                    startofline = tell()
                except IOError:
                    startofline = tell = None
                    self.seekable = 0
            line = self.fp.readline()
            if not line:
                self.status = 'EOF in headers'
                break
            # Skip unix From name time lines
            if firstline and line.startswith('From '):
                self.unixfrom = self.unixfrom + line
                continue
            firstline = 0
            if headerseen and line[0] in ' \t':
                # It's a continuation line.
                lst.append(line)
                x = (self.dict[headerseen] + "\n " + line.strip())
                self.dict[headerseen] = x.strip()
                continue
            elif self.iscomment(line):
                # It's a comment.  Ignore it.
                continue
            elif self.islast(line):
                # Note! No pushback here!  The delimiter line gets eaten.
                break
            headerseen = self.isheader(line)
            if headerseen:
                # It's a legal header line, save it.
                lst.append(line)
                self.dict[headerseen] = line[len(headerseen)+1:].strip()
                continue
            elif headerseen is not None:
                # An empty header name. These aren't allowed in HTTP, but it's
                # probably a benign mistake. Don't add the header, just keep
                # going.
                continue
            else:
                # It's not a header line; throw it back and stop here.
                if not self.dict:
                    self.status = 'No headers'
                else:
                    self.status = 'Non-header line where header expected'
                # Try to undo the read.
                if unread:
                    unread(line)
                elif tell:
                    self.fp.seek(startofline)
                else:
                    self.status = self.status + '; bad seek'
                break

Response: Reads the header lines from the file and returns a list of the header lines.


Instruction:
Write a Python 3 function that can
determine whether a given line is a legal header.

Response:
def isheader(self, line):
        """Determine whether a given line is a legal header.

        This method should return the header name, suitably canonicalized.
        You may override this method in order to use Message parsing on tagged
        data in RFC 2822-like formats with special header formats.
        """
        i = line.find(':')
        if i > -1:
            return line[:i].lower()
        return None


Instruction:
How would you explain what the following Python 3 function does
def getfirstmatchingheader(self, name):
        name = name.lower() + ':'
        n = len(name)
        lst = []
        hit = 0
        for line in self.headers:
            if hit:
                if not line[:1].isspace():
                    break
            elif line[:n].lower() == name:
                hit = 1
            if hit:
                lst.append(line)
        return lst

Response: Get the first matching header line matching name.


Instruction:
Given the following Python 3 function, write the documentation
def getrawheader(self, name):

        lst = self.getfirstmatchingheader(name)
        if not lst:
            return None
        lst[0] = lst[0][len(name) + 1:]
        return ''.join(lst)

Response: A higher - level interface to getfirstmatchingheader.


Instruction:
Write a Python 3 script to
get the value of a given header name.

Response:
def getheader(self, name, default=None):
        """Get the header value for a name.

        This is the normal interface: it returns a stripped version of the
        header value for a given header name, or None if it doesn't exist.
        This uses the dictionary version which finds the *last* such header.
        """
        return self.dict.get(name.lower(), default)


Instruction:
Can you write a function in Python 3 where it
gets all values for a header. This returns a list of values for headers given more than once ; each value in the list is stripped in the same way as the result of getallmatchingheaders.

Response:
def getheaders(self, name):
        """Get all values for a header.

        This returns a list of values for headers given more than once; each
        value in the result list is stripped in the same way as the result of
        getheader().  If the header is not given, return an empty list.
        """
        result = []
        current = ''
        have_header = 0
        for s in self.getallmatchingheaders(name):
            if s[0].isspace():
                if current:
                    current = "%s\n %s" % (current, s.strip())
                else:
                    current = s.strip()
            else:
                if have_header:
                    result.append(current)
                current = s[s.find(":") + 1:].strip()
                have_header = 1
        if have_header:
            result.append(current)
        return result


Instruction:
Write a Python 3 script to
get a list of addresses from a header.

Response:
def getaddrlist(self, name):
        """Get a list of addresses from a header.

        Retrieves a list of addresses from a header, where each address is a
        tuple as returned by getaddr().  Scans all named headers, so it works
        properly with multiple To: or Cc: headers for example.
        """
        raw = []
        for h in self.getallmatchingheaders(name):
            if h[0] in ' \t':
                raw.append(h)
            else:
                if raw:
                    raw.append(', ')
                i = h.find(':')
                if i > 0:
                    addr = h[i+1:]
                raw.append(addr)
        alladdrs = ''.join(raw)
        a = AddressList(alladdrs)
        return a.addresslist


Instruction:
How would you implement a function in Python 3 that
parses up to the next address.

Response:
def gotonext(self):
        """Parse up to the start of the next address."""
        while self.pos < len(self.field):
            if self.field[self.pos] in self.LWS + '\n\r':
                self.pos = self.pos + 1
            elif self.field[self.pos] == '(':
                self.commentlist.append(self.getcomment())
            else: break


Instruction:
Write a Python 3 script to
parse all addresses. Returns a list containing all of the addresses.

Response:
def getaddrlist(self):
        """Parse all addresses.

        Returns a list containing all of the addresses.
        """
        result = []
        ad = self.getaddress()
        while ad:
            result += ad
            ad = self.getaddress()
        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getrouteaddr(self):
        if self.field[self.pos] != '<':
            return

        expectroute = 0
        self.pos += 1
        self.gotonext()
        adlist = ""
        while self.pos < len(self.field):
            if expectroute:
                self.getdomain()
                expectroute = 0
            elif self.field[self.pos] == '>':
                self.pos += 1
                break
            elif self.field[self.pos] == '@':
                self.pos += 1
                expectroute = 1
            elif self.field[self.pos] == ':':
                self.pos += 1
            else:
                adlist = self.getaddrspec()
                self.pos += 1
                break
            self.gotonext()

        return adlist

Response: Parse a route address. This method just skips all the route stuff and returns the addrspec.


Instruction:
Write a Python 3 script for
parsing an RFC 2822 addr - spec.

Response:
def getaddrspec(self):
        """Parse an RFC 2822 addr-spec."""
        aslist = []

        self.gotonext()
        while self.pos < len(self.field):
            if self.field[self.pos] == '.':
                aslist.append('.')
                self.pos += 1
            elif self.field[self.pos] == '"':
                aslist.append('"%s"' % self.getquote())
            elif self.field[self.pos] in self.atomends:
                break
            else: aslist.append(self.getatom())
            self.gotonext()

        if self.pos >= len(self.field) or self.field[self.pos] != '@':
            return ''.join(aslist)

        aslist.append('@')
        self.pos += 1
        self.gotonext()
        return ''.join(aslist) + self.getdomain()


Instruction:
Create a Python 3 function to
get the complete domain name from an address.

Response:
def getdomain(self):
        """Get the complete domain name from an address."""
        sdlist = []
        while self.pos < len(self.field):
            if self.field[self.pos] in self.LWS:
                self.pos += 1
            elif self.field[self.pos] == '(':
                self.commentlist.append(self.getcomment())
            elif self.field[self.pos] == '[':
                sdlist.append(self.getdomainliteral())
            elif self.field[self.pos] == '.':
                self.pos += 1
                sdlist.append('.')
            elif self.field[self.pos] in self.atomends:
                break
            else: sdlist.append(self.getatom())
        return ''.join(sdlist)


Instruction:
Can you tell what is the following Python 3 function doing
def getdelimited(self, beginchar, endchars, allowcomments = 1):
        if self.field[self.pos] != beginchar:
            return ''

        slist = ['']
        quote = 0
        self.pos += 1
        while self.pos < len(self.field):
            if quote == 1:
                slist.append(self.field[self.pos])
                quote = 0
            elif self.field[self.pos] in endchars:
                self.pos += 1
                break
            elif allowcomments and self.field[self.pos] == '(':
                slist.append(self.getcomment())
                continue        # have already advanced pos from getcomment
            elif self.field[self.pos] == '\\':
                quote = 1
            else:
                slist.append(self.field[self.pos])
            self.pos += 1

        return ''.join(slist)

Response: Parse a header fragment delimited by special characters.


Instruction:
Can you tell what is the following Python 3 function doing
def getphraselist(self):
        plist = []

        while self.pos < len(self.field):
            if self.field[self.pos] in self.LWS:
                self.pos += 1
            elif self.field[self.pos] == '"':
                plist.append(self.getquote())
            elif self.field[self.pos] == '(':
                self.commentlist.append(self.getcomment())
            elif self.field[self.pos] in self.phraseends:
                break
            else:
                plist.append(self.getatom(self.phraseends))

        return plist

Response: Parse a sequence of RFC 2822 phrases.


Instruction:
Write a Python 3 function for
constructing a date from a POSIX timestamp ( like time. time()).

Response:
def fromtimestamp(cls, t):
        "Construct a date from a POSIX timestamp (like time.time())."
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
        return cls(y, m, d)


Instruction:
Can you write a function in Python 3 where it
returns ctime () style string.

Response:
def ctime(self):
        "Return ctime() style string."
        weekday = self.toordinal() % 7 or 7
        return "%s %s %2d 00:00:00 %04d" % (
            _DAYNAMES[weekday],
            _MONTHNAMES[self._month],
            self._day, self._year)


Instruction:
Write a Python 3 function that can
return the date formatted according to ISO.

Response:
def isoformat(self):
        """Return the date formatted according to ISO.

        This is 'YYYY-MM-DD'.

        References:
        - http://www.w3.org/TR/NOTE-datetime
        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
        """
        # return "%04d-%02d-%02d" % (self._year, self._month, self._day)
        return "%s-%s-%s" % (str(self._year).zfill(4), str(self._month).zfill(2), str(self._day).zfill(2))


Instruction:
Make a summary of the following Python 3 code
def replace(self, year=None, month=None, day=None):
        if year is None:
            year = self._year
        if month is None:
            month = self._month
        if day is None:
            day = self._day
        return date.__new__(type(self), year, month, day)

Response: Return a new date with new values for the specified fields.


Instruction:
Write a Python 3 script for
returning a 3 - tuple containing the ISO year week number and weekday.

Response:
def isocalendar(self):
        """Return a 3-tuple containing ISO year, week number, and weekday.

        The first ISO week of the year is the (Mon-Sun) week
        containing the year's first Thursday; everything else derives
        from that.

        The first week is 1; Monday is 1 ... Sunday is 7.

        ISO calendar algorithm taken from
        http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
        """
        year = self._year
        week1monday = _isoweek1monday(year)
        today = _ymd2ord(self._year, self._month, self._day)
        # Internally, week and day have origin 0
        week, day = divmod(today - week1monday, 7)
        if week < 0:
            year -= 1
            week1monday = _isoweek1monday(year)
            week, day = divmod(today - week1monday, 7)
        elif week >= 52:
            if today >= _isoweek1monday(year+1):
                year += 1
                week = 0
        return year, week+1, day+1


Instruction:
How would you explain what the following Python 3 function does
def _tzstr(self, sep=":"):
        off = self._utcoffset()
        if off is not None:
            if off < 0:
                sign = "-"
                off = -off
            else:
                sign = "+"
            hh, mm = divmod(off, 60)
            assert 0 <= hh < 24
            off = "%s%02d%s%02d" % (sign, hh, sep, mm)
        return off

Response: Return formatted timezone offset.


Instruction:
Can you tell what is the following Python 3 function doing
def isoformat(self):
        s = _format_time(self._hour, self._minute, self._second,
                         self._microsecond)
        tz = self._tzstr()
        if tz:
            s += tz
        return s

Response: Return the time formatted according to ISO.


Instruction:
Can you generate the documentation for the following Python 3 function
def tzname(self):
        if self._tzinfo is None:
            return None
        name = self._tzinfo.tzname(None)
        _check_tzname(name)
        return name

Response: Return the timezone name of the current object.


Instruction:
Given the following Python 3 function, write the documentation
def dst(self):
        if self._tzinfo is None:
            return None
        offset = self._tzinfo.dst(None)
        offset = _check_utc_offset("dst", offset)
        if offset is not None:
            offset = timedelta._create(0, offset * 60, 0, True)
        return offset

Response: Return the DST offset of the entry in the current timezone.


Instruction:
How would you code a function in Python 3 to
return a new time with new values for the specified fields.

Response:
def replace(self, hour=None, minute=None, second=None, microsecond=None,
                tzinfo=True):
        """Return a new time with new values for the specified fields."""
        if hour is None:
            hour = self.hour
        if minute is None:
            minute = self.minute
        if second is None:
            second = self.second
        if microsecond is None:
            microsecond = self.microsecond
        if tzinfo is True:
            tzinfo = self.tzinfo
        return time.__new__(type(self),
                            hour, minute, second, microsecond, tzinfo)


Instruction:
How would you implement a function in Python 3 that
constructs a datetime object from a POSIX timestamp.

Response:
def fromtimestamp(cls, timestamp, tz=None):
        """Construct a datetime from a POSIX timestamp (like time.time()).

        A timezone info object may be passed in as well.
        """
        _check_tzinfo_arg(tz)
        converter = _time.localtime if tz is None else _time.gmtime
        self = cls._from_timestamp(converter, timestamp, tz)
        if tz is not None:
            self = tz.fromutc(self)
        return self


Instruction:
Write a Python 3 function that can
construct a datetime from time. time() and optional time zone info.

Response:
def now(cls, tz=None):
        "Construct a datetime from time.time() and optional time zone info."
        t = _time.time()
        return cls.fromtimestamp(t, tz)


Instruction:
How would you code a function in Python 3 to
construct a datetime from a given date and a given time.

Response:
def combine(cls, date, time):
        "Construct a datetime from a given date and a given time."
        if not isinstance(date, _date_class):
            raise TypeError("date argument must be a date instance")
        if not isinstance(time, _time_class):
            raise TypeError("time argument must be a time instance")
        return cls(date.year, date.month, date.day,
                   time.hour, time.minute, time.second, time.microsecond,
                   time.tzinfo)


Instruction:
Can you generate the documentation for the following Python 3 function
def utctimetuple(self):
        "Return UTC time tuple compatible with time.gmtime()."
        y, m, d = self.year, self.month, self.day
        hh, mm, ss = self.hour, self.minute, self.second
        offset = self._utcoffset()
        if offset:  # neither None nor 0
            mm -= offset
            y, m, d, hh, mm, ss, _ = _normalize_datetime(
                y, m, d, hh, mm, ss, 0, ignore_overflow=True)
        return _build_struct_time(y, m, d, hh, mm, ss, 0)

Response: Return UTC time tuple compatible with time. gmtime().


Instruction:
How would you explain what the following Python 3 function does
def time(self):
        "Return the time part, with tzinfo None."
        return time(self.hour, self.minute, self.second, self.microsecond)

Response: Return the time part with tzinfo None.


Instruction:
Create a Python 3 function to
return the time part with same tzinfo.

Response:
def timetz(self):
        "Return the time part, with same tzinfo."
        return time(self.hour, self.minute, self.second, self.microsecond,
                    self._tzinfo)


Instruction:
How would you code a function in Python 3 to
return a new datetime with new values for the specified fields.

Response:
def replace(self, year=None, month=None, day=None, hour=None,
                minute=None, second=None, microsecond=None, tzinfo=True):
        """Return a new datetime with new values for the specified fields."""
        if year is None:
            year = self.year
        if month is None:
            month = self.month
        if day is None:
            day = self.day
        if hour is None:
            hour = self.hour
        if minute is None:
            minute = self.minute
        if second is None:
            second = self.second
        if microsecond is None:
            microsecond = self.microsecond
        if tzinfo is True:
            tzinfo = self.tzinfo
        return datetime.__new__(type(self),
                                year, month, day, hour, minute, second,
                                microsecond, tzinfo)


Instruction:
Make a summary of the following Python 3 code
def ctime(self):
        "Return ctime() style string."
        weekday = self.toordinal() % 7 or 7
        return "%s %s %2d %02d:%02d:%02d %04d" % (
            _DAYNAMES[weekday],
            _MONTHNAMES[self._month],
            self._day,
            self._hour, self._minute, self._second,
            self._year)

Response: Return ctime () style string.


Instruction:
Can you tell what is the following Python 3 function doing
def isoformat(self, sep='T'):
        s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) +
             _format_time(self._hour, self._minute, self._second,
                          self._microsecond))
        off = self._utcoffset()
        if off is not None:
            if off < 0:
                sign = "-"
                off = -off
            else:
                sign = "+"
            hh, mm = divmod(off, 60)
            s += "%s%02d:%02d" % (sign, hh, mm)
        return s

Response: Return the time formatted according to ISO.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def utcoffset(self):
        if self._tzinfo is None:
            return None
        offset = self._tzinfo.utcoffset(self)
        offset = _check_utc_offset("utcoffset", offset)
        if offset is not None:
            offset = timedelta._create(0, offset * 60, 0, True)
        return offset

Response:
Return the timezone offset in minutes east of UTC ( negative west of
        UTC


Instruction:
Can you create a Python 3 function that
returns the number of times b occurs in a.

Response:
def countOf(a, b):
    "Return the number of times b occurs in a."
    count = 0
    for i in a:
        if i == b:
            count += 1
    return count


Instruction:
Can you generate the documentation for the following Python 3 function
def indexOf(a, b):
    "Return the first index of b in a."
    for i, j in enumerate(a):
        if j == b:
            return i
    else:
        raise ValueError('sequence.index(x): x not in sequence')

Response: Return the first index of b in a.


Instruction:
Make a summary of the following Python 3 code
def length_hint(obj, default=0):
    if not isinstance(default, int):
        msg = ("'%s' object cannot be interpreted as an integer" %
               type(default).__name__)
        raise TypeError(msg)

    try:
        return len(obj)
    except TypeError:
        pass

    try:
        hint = type(obj).__length_hint__
    except AttributeError:
        return default

    try:
        val = hint(obj)
    except TypeError:
        return default
    if val is NotImplemented:
        return default
    if not isinstance(val, int):
        msg = ('__length_hint__ must be integer, not %s' %
               type(val).__name__)
        raise TypeError(msg)
    if val < 0:
        msg = '__length_hint__() should return >= 0'
        raise ValueError(msg)
    return val

Response: Return an estimate of the number of items in obj.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def iconcat(a, b):
    "Same as a += b, for a and b sequences."
    if not hasattr(a, '__getitem__'):
        msg = "'%s' object can't be concatenated" % type(a).__name__
        raise TypeError(msg)
    a += b
    return a

Response: Same as a += b for a and b sequences.


Instruction:
Make a summary of the following Python 3 code
def itruediv(a, b):
    "Same as a /= b."
    if type(a) == int or type(a) == long:
        a = float(a)
    a /= b
    return a

Response: Same as a /= b.


Instruction:
Can you create a Python 3 function that
returns a dialect corresponding to the sample and returns None if the sample is not a valid CSV file.

Response:
def sniff(self, sample, delimiters=None):
        """
        Returns a dialect (or None) corresponding to the sample
        """

        quotechar, doublequote, delimiter, skipinitialspace = \
                   self._guess_quote_and_delimiter(sample, delimiters)
        if not delimiter:
            delimiter, skipinitialspace = self._guess_delimiter(sample,
                                                                delimiters)

        if not delimiter:
            raise Error, "Could not determine delimiter"

        class dialect(Dialect):
            _name = "sniffed"
            lineterminator = '\r\n'
            quoting = QUOTE_MINIMAL
            # escapechar = ''

        dialect.doublequote = doublequote
        dialect.delimiter = delimiter
        # _csv.reader won't accept a quotechar of ''
        dialect.quotechar = quotechar or '"'
        dialect.skipinitialspace = skipinitialspace

        return dialect


Instruction:
How would you code a function in Python 3 to
guess the quote and delimiter from the data.

Response:
def _guess_quote_and_delimiter(self, data, delimiters):
        """
        Looks for text enclosed between two identical quotes
        (the probable quotechar) which are preceded and followed
        by the same character (the probable delimiter).
        For example:
                         ,'some text',
        The quote with the most wins, same with the delimiter.
        If there is no quotechar the delimiter can't be determined
        this way.
        """

        matches = []
        for restr in ('(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
                      '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)',   #  ".*?",
                      '(?P<delim>>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)',  # ,".*?"
                      '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'):                            #  ".*?" (no delim, no space)
            regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
            matches = regexp.findall(data)
            if matches:
                break

        if not matches:
            # (quotechar, doublequote, delimiter, skipinitialspace)
            return ('', False, None, 0)
        quotes = {}
        delims = {}
        spaces = 0
        for m in matches:
            n = regexp.groupindex['quote'] - 1
            key = m[n]
            if key:
                quotes[key] = quotes.get(key, 0) + 1
            try:
                n = regexp.groupindex['delim'] - 1
                key = m[n]
            except KeyError:
                continue
            if key and (delimiters is None or key in delimiters):
                delims[key] = delims.get(key, 0) + 1
            try:
                n = regexp.groupindex['space'] - 1
            except KeyError:
                continue
            if m[n]:
                spaces += 1

        quotechar = reduce(lambda a, b, quotes = quotes:
                           (quotes[a] > quotes[b]) and a or b, quotes.keys())

        if delims:
            delim = reduce(lambda a, b, delims = delims:
                           (delims[a] > delims[b]) and a or b, delims.keys())
            skipinitialspace = delims[delim] == spaces
            if delim == '\n': # most likely a file with a single column
                delim = ''
        else:
            # there is *no* delimiter, it's a single column of quoted data
            delim = ''
            skipinitialspace = 0

        # if we see an extra quote between delimiters, we've got a
        # double quoted format
        dq_regexp = re.compile(
                               r"((%(delim)s)|^)\W*%(quote)s[^%(delim)s\n]*%(quote)s[^%(delim)s\n]*%(quote)s\W*((%(delim)s)|$)" % \
                               {'delim':re.escape(delim), 'quote':quotechar}, re.MULTILINE)

        if dq_regexp.search(data):
            doublequote = True
        else:
            doublequote = False

        return (quotechar, doublequote, delim, skipinitialspace)


Instruction:
Can you implement a function in Python 3 that
guesses the delimiter for the current canon entry.

Response:
def _guess_delimiter(self, data, delimiters):
        """
        The delimiter /should/ occur the same number of times on
        each row. However, due to malformed data, it may not. We don't want
        an all or nothing approach, so we allow for small variations in this
        number.
          1) build a table of the frequency of each character on every line.
          2) build a table of frequencies of this frequency (meta-frequency?),
             e.g.  'x occurred 5 times in 10 rows, 6 times in 1000 rows,
             7 times in 2 rows'
          3) use the mode of the meta-frequency to determine the /expected/
             frequency for that character
          4) find out how often the character actually meets that goal
          5) the character that best meets its goal is the delimiter
        For performance reasons, the data is evaluated in chunks, so it can
        try and evaluate the smallest portion of the data possible, evaluating
        additional chunks as necessary.
        """

        data = filter(None, data.split('\n'))

        ascii = [chr(c) for c in range(127)] # 7-bit ASCII

        # build frequency tables
        chunkLength = min(10, len(data))
        iteration = 0
        charFrequency = {}
        modes = {}
        delims = {}
        start, end = 0, min(chunkLength, len(data))
        while start < len(data):
            iteration += 1
            for line in data[start:end]:
                for char in ascii:
                    metaFrequency = charFrequency.get(char, {})
                    # must count even if frequency is 0
                    freq = line.count(char)
                    # value is the mode
                    metaFrequency[freq] = metaFrequency.get(freq, 0) + 1
                    charFrequency[char] = metaFrequency

            for char in charFrequency.keys():
                items = charFrequency[char].items()
                if len(items) == 1 and items[0][0] == 0:
                    continue
                # get the mode of the frequencies
                if len(items) > 1:
                    modes[char] = reduce(lambda a, b: a[1] > b[1] and a or b,
                                         items)
                    # adjust the mode - subtract the sum of all
                    # other frequencies
                    items.remove(modes[char])
                    modes[char] = (modes[char][0], modes[char][1]
                                   - reduce(lambda a, b: (0, a[1] + b[1]),
                                            items)[1])
                else:
                    modes[char] = items[0]

            # build a list of possible delimiters
            modeList = modes.items()
            total = float(chunkLength * iteration)
            # (rows of consistent data) / (number of rows) = 100%
            consistency = 1.0
            # minimum consistency threshold
            threshold = 0.9
            while len(delims) == 0 and consistency >= threshold:
                for k, v in modeList:
                    if v[0] > 0 and v[1] > 0:
                        if ((v[1]/total) >= consistency and
                            (delimiters is None or k in delimiters)):
                            delims[k] = v
                consistency -= 0.01

            if len(delims) == 1:
                delim = delims.keys()[0]
                skipinitialspace = (data[0].count(delim) ==
                                    data[0].count("%c " % delim))
                return (delim, skipinitialspace)

            # analyze another chunkLength lines
            start = end
            end += chunkLength

        if not delims:
            return ('', 0)

        # if there's more than one, fall back to a 'preferred' list
        if len(delims) > 1:
            for d in self.preferred:
                if d in delims.keys():
                    skipinitialspace = (data[0].count(d) ==
                                        data[0].count("%c " % d))
                    return (d, skipinitialspace)

        # nothing else indicates a preference, pick the character that
        # dominates(?)
        items = [(v,k) for (k,v) in delims.items()]
        items.sort()
        delim = items[-1][1]

        skipinitialspace = (data[0].count(delim) ==
                            data[0].count("%c " % delim))
        return (delim, skipinitialspace)


Instruction:
Can you tell what is the following Python 3 function doing
def encode_basestring(s):
    def replace(match):
        return ESCAPE_DCT[match.group(0)]
    return '"' + ESCAPE.sub(replace, s) + '"'

Response: Return a JSON representation of a Python string


Instruction:
Given the following Python 3 function, write the documentation
def sub(pattern, repl, string, count=0, flags=0):
    return _compile(pattern, flags).sub(repl, string, count)

Response:
Return the string obtained by replacing the leftmost
    non - overlapping occurrences of the pattern in string by the repl.


Instruction:
Implement a function in Python 3 to
return a 2 - tuple containing the string obtained by replacing the leftmost non - overlapping occurrences of the pattern with the replacement repl.

Response:
def subn(pattern, repl, string, count=0, flags=0):
    """Return a 2-tuple containing (new_string, number).
    new_string is the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in the source
    string by the replacement repl.  number is the number of
    substitutions that were made. repl can be either a string or a
    callable; if a string, backslash escapes in it are processed.
    If it is a callable, it's passed the match object and must
    return a replacement string to be used."""
    return _compile(pattern, flags).subn(repl, string, count)


Instruction:
Given the following Python 3 function, write the documentation
def split(pattern, string, maxsplit=0, flags=0):
    return _compile(pattern, flags).split(string, maxsplit)

Response: Splits the source string by the occurrences of the pattern and returns a list containing the resulting substrings.


Instruction:
Can you write a function in Python 3 where it
returns a list of all non - overlapping matches in the string.

Response:
def findall(pattern, string, flags=0):
    """Return a list of all non-overlapping matches in the string.

    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result."""
    return _compile(pattern, flags).findall(string)

    # if sys.hexversion >= 0x02020000:
    #     __all__.append("finditer")
    def finditer(pattern, string, flags=0):
        """Return an iterator over all non-overlapping matches in the
        string.  For each match, the iterator returns a match object.

        Empty matches are included in the result."""
        return _compile(pattern, flags).finditer(string)


Instruction:
Can you write a function in Python 3 where it
escapes all non - alphanumeric characters in pattern.

Response:
def escape(pattern):
    "Escape all non-alphanumeric characters in pattern."
    s = list(pattern)
    alphanum = _alphanum
    for i, c in enumerate(pattern):
        if c not in alphanum:
            if c == "\000":
                s[i] = "\\000"
            else:
                s[i] = "\\" + c
    return pattern[:0].join(s)


Instruction:
Can you tell what is the following Python 3 function doing
def alloc_temp(self, type_='*πg.Object'):
    for v in sorted(self.free_temps, key=lambda k: k.name):
      if v.type_ == type_:
        self.free_temps.remove(v)
        self.used_temps.add(v)
        return v
    self.temp_index += 1
    name = 'πTemp{:03d}'.format(self.temp_index)
    v = expr.GeneratedTempVar(self, name, type_)
    self.used_temps.add(v)
    return v

Response: Allocate a temporary Go variable having type type_ for this block.


Instruction:
How would you implement a function in Python 3 that
releases the GeneratedTempVar v so it can be reused.

Response:
def free_temp(self, v):
    """Release the GeneratedTempVar v so it can be reused."""
    self.used_temps.remove(v)
    self.free_temps.add(v)


Instruction:
Implement a Python 3 function for
parsing a buffer and return an AST and comments as well.

Response:
def parse_buffer(buffer, mode="exec", flags=[], version=None, engine=None):
    """
    Like :meth:`parse`, but accepts a :class:`source.Buffer` instead of
    source and filename, and returns comments as well.

    :see: :meth:`parse`
    :return: (:class:`ast.AST`, list of :class:`source.Comment`)
        Abstract syntax tree and comments
    """

    if version is None:
        version = sys.version_info[0:2]

    if engine is None:
        engine = pythonparser_diagnostic.Engine()

    lexer = pythonparser_lexer.Lexer(buffer, version, engine)
    if mode in ("single", "eval"):
        lexer.interactive = True

    parser = pythonparser_parser.Parser(lexer, version, engine)
    parser.add_flags(flags)

    if mode == "exec":
        return parser.file_input(), lexer.comments
    elif mode == "single":
        return parser.single_input(), lexer.comments
    elif mode == "eval":
        return parser.eval_input(), lexer.comments


Instruction:
Write a Python 3 script to
parse a string into an abstract syntax tree.

Response:
def parse(source, filename="<unknown>", mode="exec",
          flags=[], version=None, engine=None):
    """
    Parse a string into an abstract syntax tree.
    This is the replacement for the built-in :meth:`..ast.parse`.

    :param source: (string) Source code in the correct encoding
    :param filename: (string) Filename of the source (used in diagnostics)
    :param mode: (string) Execution mode. Pass ``"exec"`` to parse a module,
        ``"single"`` to parse a single (interactive) statement,
        and ``"eval"`` to parse an expression. In the last two cases,
        ``source`` must be terminated with an empty line
        (i.e. end with ``"\\n\\n"``).
    :param flags: (list of string) Future flags.
        Equivalent to ``from __future__ import <flags>``.
    :param version: (2-tuple of int) Major and minor version of Python
        syntax to recognize, ``sys.version_info[0:2]`` by default.
    :param engine: (:class:`diagnostic.Engine`) Diagnostic engine,
        a fresh one is created by default
    :return: (:class:`ast.AST`) Abstract syntax tree
    :raise: :class:`diagnostic.Error`
        if the source code is not well-formed
    """
    ast, comments = parse_buffer(pythonparser_source.Buffer(source, filename),
                                 mode, flags, version, engine)
    return ast


Instruction:
Explain what the following Python 3 code does
def encode(in_file, out_file, name=None, mode=None):
    #
    # If in_file is a pathname open it and change defaults
    #
    opened_files = []
    try:
        if in_file == '-':
            in_file = sys.stdin
        elif isinstance(in_file, basestring):
            if name is None:
                name = os.path.basename(in_file)
            if mode is None:
                try:
                    mode = os.stat(in_file).st_mode
                except AttributeError:
                    pass
            in_file = open(in_file, 'rb')
            opened_files.append(in_file)
        #
        # Open out_file if it is a pathname
        #
        if out_file == '-':
            out_file = sys.stdout
        elif isinstance(out_file, basestring):
            out_file = open(out_file, 'wb')
            opened_files.append(out_file)
        #
        # Set defaults for name and mode
        #
        if name is None:
            name = '-'
        if mode is None:
            mode = 0666
        #
        # Write the data
        #
        out_file.write('begin %o %s\n' % ((mode&0777),name))
        data = in_file.read(45)
        while len(data) > 0:
            out_file.write(binascii.b2a_uu(data))
            data = in_file.read(45)
        out_file.write(' \nend\n')
    finally:
        for f in opened_files:
            f.close()

Response: Encode a single uuencoded file.


Instruction:
Implement a Python 3 function for
decoding a uuencoded file into a single file.

Response:
def decode(in_file, out_file=None, mode=None, quiet=0):
    """Decode uuencoded file"""
    #
    # Open the input file, if needed.
    #
    opened_files = []
    if in_file == '-':
        in_file = sys.stdin
    elif isinstance(in_file, basestring):
        in_file = open(in_file)
        opened_files.append(in_file)
    try:
        #
        # Read until a begin is encountered or we've exhausted the file
        #
        while True:
            hdr = in_file.readline()
            if not hdr:
                raise Error('No valid begin line found in input file')
            if not hdr.startswith('begin'):
                continue
            hdrfields = hdr.split(' ', 2)
            if len(hdrfields) == 3 and hdrfields[0] == 'begin':
                try:
                    int(hdrfields[1], 8)
                    break
                except ValueError:
                    pass
        if out_file is None:
            out_file = hdrfields[2].rstrip()
            if os.path.exists(out_file):
                raise Error('Cannot overwrite existing file: %s' % out_file)
        if mode is None:
            mode = int(hdrfields[1], 8)
        #
        # Open the output file
        #
        if out_file == '-':
            out_file = sys.stdout
        elif isinstance(out_file, basestring):
            fp = open(out_file, 'wb')
            try:
                os.path.chmod(out_file, mode)
            except AttributeError:
                pass
            out_file = fp
            opened_files.append(out_file)
        #
        # Main decoding loop
        #
        s = in_file.readline()
        while s and s.strip() != 'end':
            try:
                data = binascii.a2b_uu(s)
            except binascii.Error, v:
                # Workaround for broken uuencoders by /Fredrik Lundh
                nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3
                data = binascii.a2b_uu(s[:nbytes])
                if not quiet:
                    sys.stderr.write("Warning: %s\n" % v)
            out_file.write(data)
            s = in_file.readline()
        if not s:
            raise Error('Truncated input file')
    finally:
        for f in opened_files:
            f.close()


Instruction:
Write a Python 3 script to
split the argument into words using split capitalize each word using capitalize and join the capitalized words using join.

Response:
def capwords(s, sep=None):
    """capwords(s [,sep]) -> string

    Split the argument into words using split, capitalize each
    word using capitalize, and join the capitalized words using
    join.  If the optional second argument sep is absent or None,
    runs of whitespace characters are replaced by a single space
    and leading and trailing whitespace are removed, otherwise
    sep is used to split and join the words.

    """
    return (sep or ' ').join(x.capitalize() for x in s.split(sep))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def maketrans(fromstr, tostr):
    if len(fromstr) != len(tostr):
        raise ValueError, "maketrans arguments must have same length"
    global _idmapL
    if not _idmapL:
        _idmapL = list(_idmap)
    L = _idmapL[:]
    fromstr = map(ord, fromstr)
    for i in range(len(fromstr)):
        L[fromstr[i]] = tostr[i]
    return ''.join(L)

Response: Create a translation table from two strings.


Instruction:
Write a Python 3 script for
returning a string with zeros on the left of x with the specified width.

Response:
def zfill(x, width):
    """zfill(x, width) -> string

    Pad a numeric string x with zeros on the left, to fill a field
    of the specified width.  The string x is never truncated.

    """
    if not isinstance(x, basestring):
        x = repr(x)
    return x.zfill(width)


Instruction:
Explain what the following Python 3 code does
def translate(s, table, deletions=""):
    if deletions or table is None:
        return s.translate(table, deletions)
    else:
        # Add s[:0] so that if s is Unicode and table is an 8-bit string,
        # table is converted to Unicode.  This means that table *cannot*
        # be a dictionary -- for that feature, use u.translate() directly.
        return s.translate(table + s[:0])

Response: Translate a string s to a Unicode string s.


Instruction:
How would you code a function in Python 3 to
return a copy of string s with all occurrences of old replaced by new.

Response:
def replace(s, old, new, maxreplace=-1):
    """replace (str, old, new[, maxreplace]) -> string

    Return a copy of string str with all occurrences of substring
    old replaced by new. If the optional argument maxreplace is
    given, only the first maxreplace occurrences are replaced.

    """
    return s.replace(old, new, maxreplace)


Instruction:
Write a Python 3 script for
using SequenceMatcher to return list of the best good enough matches for word and list of possibilities.

Response:
def get_close_matches(word, possibilities, n=3, cutoff=0.6):
    """Use SequenceMatcher to return list of the best "good enough" matches.

    word is a sequence for which close matches are desired (typically a
    string).

    possibilities is a list of sequences against which to match word
    (typically a list of strings).

    Optional arg n (default 3) is the maximum number of close matches to
    return.  n must be > 0.

    Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities
    that don't score at least that similar to word are ignored.

    The best (no more than n) matches among the possibilities are returned
    in a list, sorted by similarity score, most similar first.

    >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
    ['apple', 'ape']
    >>> import keyword as _keyword
    >>> get_close_matches("wheel", _keyword.kwlist)
    ['while']
    >>> get_close_matches("apple", _keyword.kwlist)
    []
    >>> get_close_matches("accept", _keyword.kwlist)
    ['except']
    """

    if not n >  0:
        raise ValueError("n must be > 0: %r" % (n,))
    if not 0.0 <= cutoff <= 1.0:
        raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
    result = []
    s = SequenceMatcher()
    s.set_seq2(word)
    for x in possibilities:
        s.set_seq1(x)
        if s.real_quick_ratio() >= cutoff and \
           s.quick_ratio() >= cutoff and \
           s.ratio() >= cutoff:
            result.append((s.ratio(), x))

    # Move the best scorers to head of list
    result = heapq.nlargest(n, result)
    # Strip scores for the best n matches
    return [x for score, x in result]


Instruction:
How would you explain what the following Python 3 function does
def _count_leading(line, ch):

    i, n = 0, len(line)
    while i < n and line[i] == ch:
        i += 1
    return i

Response: Return number of ch characters at the start of line.


Instruction:
Can you generate the documentation for the following Python 3 function
def _format_range_unified(start, stop):
    'Convert range to the "ed" format'
    # Per the diff spec at http://www.unix.org/single_unix_specification/
    beginning = start + 1     # lines start numbering with one
    length = stop - start
    if length == 1:
        # return '{}'.format(beginning)
        return '%s' % (beginning)
    if not length:
        beginning -= 1        # empty ranges begin at line just before the range
    return '%s,%s' % (beginning, length)

Response: Convert range to the ed format


Instruction:
Make a summary of the following Python 3 code
def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
                 tofiledate='', n=3, lineterm='\n'):
    r"""
    Compare two sequences of lines; generate the delta as a unified diff.

    Unified diffs are a compact way of showing line changes and a few
    lines of context.  The number of context lines is set by 'n' which
    defaults to three.

    By default, the diff control lines (those with ---, +++, or @@) are
    created with a trailing newline.  This is helpful so that inputs
    created from file.readlines() result in diffs that are suitable for
    file.writelines() since both the inputs and outputs have trailing
    newlines.

    For inputs that do not have trailing newlines, set the lineterm
    argument to "" so that the output will be uniformly newline free.

    The unidiff format normally has a header for filenames and modification
    times.  Any or all of these may be specified using strings for
    'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
    The modification times are normally expressed in the ISO 8601 format.

    Example:

    >>> for line in unified_diff('one two three four'.split(),
    ...             'zero one tree four'.split(), 'Original', 'Current',
    ...             '2005-01-26 23:30:50', '2010-04-02 10:20:52',
    ...             lineterm=''):
    ...     print line                  # doctest: +NORMALIZE_WHITESPACE
    --- Original        2005-01-26 23:30:50
    +++ Current         2010-04-02 10:20:52
    @@ -1,4 +1,4 @@
    +zero
     one
    -two
    -three
    +tree
     four
    """

    started = False
    for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
        if not started:
            started = True
            # fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
            fromdate = '\t%s' % (fromfiledate) if fromfiledate else ''
            # todate = '\t{}'.format(tofiledate) if tofiledate else ''
            todate = '\t%s' % (tofiledate) if tofiledate else ''
            # yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
            yield '--- %s%s%s' % (fromfile, fromdate, lineterm)
            # yield '+++ {}{}{}'.format(tofile, todate, lineterm)
            yield '+++ %s%s%s' % (tofile, todate, lineterm)

        first, last = group[0], group[-1]
        file1_range = _format_range_unified(first[1], last[2])
        file2_range = _format_range_unified(first[3], last[4])
        # yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
        yield '@@ -%s +%s @@%s' % (file1_range, file2_range, lineterm)

        for tag, i1, i2, j1, j2 in group:
            if tag == 'equal':
                for line in a[i1:i2]:
                    yield ' ' + line
                continue
            if tag in ('replace', 'delete'):
                for line in a[i1:i2]:
                    yield '-' + line
            if tag in ('replace', 'insert'):
                for line in b[j1:j2]:
                    yield '+' + line

Response: r Generate a unified diff between two sequences of lines.


Instruction:
Can you generate the documentation for the following Python 3 function
def _format_range_context(start, stop):
    'Convert range to the "ed" format'
    # Per the diff spec at http://www.unix.org/single_unix_specification/
    beginning = start + 1     # lines start numbering with one
    length = stop - start
    if not length:
        beginning -= 1        # empty ranges begin at line just before the range
    if length <= 1:
        # return '{}'.format(beginning)
        return '%s' % (beginning)
    # return '{},{}'.format(beginning, beginning + length - 1)
    return '%s,%s' % (beginning, beginning + length - 1)

Response: Convert range to the ed format


Instruction:
Make a summary of the following Python 3 code
def context_diff(a, b, fromfile='', tofile='',
                 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
    r"""
    Compare two sequences of lines; generate the delta as a context diff.

    Context diffs are a compact way of showing line changes and a few
    lines of context.  The number of context lines is set by 'n' which
    defaults to three.

    By default, the diff control lines (those with *** or ---) are
    created with a trailing newline.  This is helpful so that inputs
    created from file.readlines() result in diffs that are suitable for
    file.writelines() since both the inputs and outputs have trailing
    newlines.

    For inputs that do not have trailing newlines, set the lineterm
    argument to "" so that the output will be uniformly newline free.

    The context diff format normally has a header for filenames and
    modification times.  Any or all of these may be specified using
    strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
    The modification times are normally expressed in the ISO 8601 format.
    If not specified, the strings default to blanks.

    Example:

    >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
    ...       'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
    *** Original
    --- Current
    ***************
    *** 1,4 ****
      one
    ! two
    ! three
      four
    --- 1,4 ----
    + zero
      one
    ! tree
      four
    """

    prefix = dict(insert='+ ', delete='- ', replace='! ', equal='  ')
    started = False
    for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
        if not started:
            started = True
            # fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
            fromdate = '\t%s' % (fromfiledate) if fromfiledate else ''
            # todate = '\t{}'.format(tofiledate) if tofiledate else ''
            todate = '\t%s' % (tofiledate) if tofiledate else ''
            # yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
            yield '*** %s%s%s' % (fromfile, fromdate, lineterm)
            # yield '--- {}{}{}'.format(tofile, todate, lineterm)
            yield '--- %s%s%s' % (tofile, todate, lineterm)

        first, last = group[0], group[-1]
        yield '***************' + lineterm

        file1_range = _format_range_context(first[1], last[2])
        # yield '*** {} ****{}'.format(file1_range, lineterm)
        yield '*** %s ****%s' % (file1_range, lineterm)

        if any(tag in ('replace', 'delete') for tag, _, _, _, _ in group):
            for tag, i1, i2, _, _ in group:
                if tag != 'insert':
                    for line in a[i1:i2]:
                        yield prefix[tag] + line

        file2_range = _format_range_context(first[3], last[4])
        # yield '--- {} ----{}'.format(file2_range, lineterm)
        yield '--- %s ----%s' % (file2_range, lineterm)

        if any(tag in ('replace', 'insert') for tag, _, _, _, _ in group):
            for tag, _, _, j1, j2 in group:
                if tag != 'delete':
                    for line in b[j1:j2]:
                        yield prefix[tag] + line

Response: r Generate a context diff between two sequences of lines.


Instruction:
Can you generate the documentation for the following Python 3 function
def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
    return Differ(linejunk, charjunk).compare(a, b)

Response: r Compare two lists of strings and return a Differ - style delta.