Instruction:
Here you have a function in Python 3, explain what it does
def imagej_description(shape, rgb=None, colormaped=False, version=None,
                       hyperstack=None, mode=None, loop=None, **kwargs):
    """Return ImageJ image description from data shape.

    ImageJ can handle up to 6 dimensions in order TZCYXS.

    >>> imagej_description((51, 5, 2, 196, 171))  # doctest: +SKIP
    ImageJ=1.11a
    images=510
    channels=2
    slices=5
    frames=51
    hyperstack=true
    mode=grayscale
    loop=false

    """
    if colormaped:
        raise NotImplementedError('ImageJ colormapping not supported')
    if version is None:
        version = '1.11a'
    shape = imagej_shape(shape, rgb=rgb)
    rgb = shape[-1] in (3, 4)

    result = ['ImageJ=%s' % version]
    append = []
    result.append('images=%i' % product(shape[:-3]))
    if hyperstack is None:
        hyperstack = True
        append.append('hyperstack=true')
    else:
        append.append('hyperstack=%s' % bool(hyperstack))
    if shape[2] > 1:
        result.append('channels=%i' % shape[2])
    if mode is None and not rgb:
        mode = 'grayscale'
    if hyperstack and mode:
        append.append('mode=%s' % mode)
    if shape[1] > 1:
        result.append('slices=%i' % shape[1])
    if shape[0] > 1:
        result.append('frames=%i' % shape[0])
        if loop is None:
            append.append('loop=false')
    if loop is not None:
        append.append('loop=%s' % bool(loop))
    for key, value in kwargs.items():
        append.append('%s=%s' % (key.lower(), value))

    return '\n'.join(result + append + [''])

Response: Return ImageJ image description from data shape.


Instruction:
Can you create a Python 3 function that
returns shape normalized to 6D ImageJ hyperstack TZCYXS.

Response:
def imagej_shape(shape, rgb=None):
    """Return shape normalized to 6D ImageJ hyperstack TZCYXS.

    Raise ValueError if not a valid ImageJ hyperstack shape.

    >>> imagej_shape((2, 3, 4, 5, 3), False)
    (2, 3, 4, 5, 3, 1)

    """
    shape = tuple(int(i) for i in shape)
    ndim = len(shape)
    if 1 > ndim > 6:
        raise ValueError('invalid ImageJ hyperstack: not 2 to 6 dimensional')
    if rgb is None:
        rgb = shape[-1] in (3, 4) and ndim > 2
    if rgb and shape[-1] not in (3, 4):
        raise ValueError('invalid ImageJ hyperstack: not a RGB image')
    if not rgb and ndim == 6 and shape[-1] != 1:
        raise ValueError('invalid ImageJ hyperstack: not a non-RGB image')
    if rgb or shape[-1] == 1:
        return (1, ) * (6 - ndim) + shape
    return (1, ) * (5 - ndim) + shape + (1,)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def json_description(shape, **metadata):
    metadata.update(shape=shape)
    return json.dumps(metadata)

Response: Return JSON image description from data shape and other metadata.


Instruction:
Given the following Python 3 function, write the documentation
def json_description_metadata(description):
    if description[:6] == 'shape=':
        # old-style 'shaped' description; not JSON
        shape = tuple(int(i) for i in description[7:-1].split(','))
        return dict(shape=shape)
    if description[:1] == '{' and description[-1:] == '}':
        # JSON description
        return json.loads(description)
    raise ValueError('invalid JSON image description', description)

Response: Return metatata from JSON formated image description as dict.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fluoview_description_metadata(description, ignoresections=None):
    if not description.startswith('['):
        raise ValueError('invalid FluoView image description')
    if ignoresections is None:
        ignoresections = {'Region Info (Fields)', 'Protocol Description'}

    result = {}
    sections = [result]
    comment = False
    for line in description.splitlines():
        if not comment:
            line = line.strip()
        if not line:
            continue
        if line[0] == '[':
            if line[-5:] == ' End]':
                # close section
                del sections[-1]
                section = sections[-1]
                name = line[1:-5]
                if comment:
                    section[name] = '\n'.join(section[name])
                if name[:4] == 'LUT ':
                    a = numpy.array(section[name], dtype='uint8')
                    a.shape = -1, 3
                    section[name] = a
                continue
            # new section
            comment = False
            name = line[1:-1]
            if name[:4] == 'LUT ':
                section = []
            elif name in ignoresections:
                section = []
                comment = True
            else:
                section = {}
            sections.append(section)
            result[name] = section
            continue
        # add entry
        if comment:
            section.append(line)
            continue
        line = line.split('=', 1)
        if len(line) == 1:
            section[line[0].strip()] = None
            continue
        key, value = line
        if key[:4] == 'RGB ':
            section.extend(int(rgb) for rgb in value.split())
        else:
            section[key.strip()] = astype(value.strip())
    return result

Response: Return metatata from FluoView image description as dict.


Instruction:
How would you explain what the following Python 3 function does
def pilatus_description_metadata(description):
    result = {}
    if not description.startswith('# '):
        return result
    for c in '#:=,()':
        description = description.replace(c, ' ')
    for line in description.split('\n'):
        if line[:2] != '  ':
            continue
        line = line.split()
        name = line[0]
        if line[0] not in TIFF.PILATUS_HEADER:
            try:
                result['DateTime'] = datetime.datetime.strptime(
                    ' '.join(line), '%Y-%m-%dT%H %M %S.%f')
            except Exception:
                result[name] = ' '.join(line[1:])
            continue
        indices, dtype = TIFF.PILATUS_HEADER[line[0]]
        if isinstance(indices[0], slice):
            # assumes one slice
            values = line[indices[0]]
        else:
            values = [line[i] for i in indices]
        if dtype is float and values[0] == 'not':
            values = ['NaN']
        values = tuple(dtype(v) for v in values)
        if dtype == str:
            values = ' '.join(values)
        elif len(values) == 1:
            values = values[0]
        result[name] = values
    return result

Response: Return metatata from Pilatus image description as dict.


Instruction:
Create a Python 3 function for
returning metatata from Aperio image description as dict.

Response:
def svs_description_metadata(description):
    """Return metatata from Aperio image description as dict.

    The Aperio image description format is unspecified. Expect failures.

    >>> svs_description_metadata('Aperio Image Library v1.0')
    {'Aperio Image Library': 'v1.0'}

    """
    if not description.startswith('Aperio Image Library '):
        raise ValueError('invalid Aperio image description')
    result = {}
    lines = description.split('\n')
    key, value = lines[0].strip().rsplit(None, 1)  # 'Aperio Image Library'
    result[key.strip()] = value.strip()
    if len(lines) == 1:
        return result
    items = lines[1].split('|')
    result[''] = items[0].strip()  # TODO: parse this?
    for item in items[1:]:
        key, value = item.split(' = ')
        result[key.strip()] = astype(value.strip())
    return result


Instruction:
Write a Python 3 function for
returning metadata from MetaMorph image description as list of dict.

Response:
def stk_description_metadata(description):
    """Return metadata from MetaMorph image description as list of dict.

    The MetaMorph image description format is unspecified. Expect failures.

    """
    description = description.strip()
    if not description:
        return []
    try:
        description = bytes2str(description)
    except UnicodeDecodeError as exc:
        log.warning('stk_description_metadata: %s: %s',
                    exc.__class__.__name__, exc)
        return []
    result = []
    for plane in description.split('\x00'):
        d = {}
        for line in plane.split('\r\n'):
            line = line.split(':', 1)
            if len(line) > 1:
                name, value = line
                d[name.strip()] = astype(value.strip())
            else:
                value = line[0].strip()
                if value:
                    if '' in d:
                        d[''].append(value)
                    else:
                        d[''] = [value]
        result.append(d)
    return result


Instruction:
Create a Python 3 function to
return metatata from MetaSeries image description as dict.

Response:
def metaseries_description_metadata(description):
    """Return metatata from MetaSeries image description as dict."""
    if not description.startswith('<MetaData>'):
        raise ValueError('invalid MetaSeries image description')

    from xml.etree import cElementTree as etree  # delayed import
    root = etree.fromstring(description)
    types = {'float': float, 'int': int,
             'bool': lambda x: asbool(x, 'on', 'off')}

    def parse(root, result):
        # recursive
        for child in root:
            attrib = child.attrib
            if not attrib:
                result[child.tag] = parse(child, {})
                continue
            if 'id' in attrib:
                i = attrib['id']
                t = attrib['type']
                v = attrib['value']
                if t in types:
                    result[i] = types[t](v)
                else:
                    result[i] = v
        return result

    adict = parse(root, {})
    if 'Description' in adict:
        adict['Description'] = adict['Description'].replace('
', '\n')
    return adict


Instruction:
How would you code a function in Python 3 to
return metatata from ScanImage artist tag as dict.

Response:
def scanimage_artist_metadata(artist):
    """Return metatata from ScanImage artist tag as dict."""
    try:
        return json.loads(artist)
    except ValueError as exc:
        log.warning('scanimage_artist_metadata: %s: %s',
                    exc.__class__.__name__, exc)


Instruction:
How would you code a function in Python 3 to
return OlympusSIS metadata from INI string.

Response:
def olympusini_metadata(inistr):
    """Return OlympusSIS metadata from INI string.

    No documentation is available.

    """
    def keyindex(key):
        # split key into name and index
        index = 0
        i = len(key.rstrip('0123456789'))
        if i < len(key):
            index = int(key[i:]) - 1
            key = key[:i]
        return key, index

    result = {}
    bands = []
    zpos = None
    tpos = None
    for line in inistr.splitlines():
        line = line.strip()
        if line == '' or line[0] == ';':
            continue
        if line[0] == '[' and line[-1] == ']':
            section_name = line[1:-1]
            result[section_name] = section = {}
            if section_name == 'Dimension':
                result['axes'] = axes = []
                result['shape'] = shape = []
            elif section_name == 'ASD':
                result[section_name] = []
            elif section_name == 'Z':
                if 'Dimension' in result:
                    result[section_name]['ZPos'] = zpos = []
            elif section_name == 'Time':
                if 'Dimension' in result:
                    result[section_name]['TimePos'] = tpos = []
            elif section_name == 'Band':
                nbands = result['Dimension']['Band']
                bands = [{'LUT': []} for i in range(nbands)]
                result[section_name] = bands
                iband = 0
        else:
            key, value = line.split('=')
            if value.strip() == '':
                value = None
            elif ',' in value:
                value = tuple(astype(v) for v in value.split(','))
            else:
                value = astype(value)

            if section_name == 'Dimension':
                section[key] = value
                axes.append(key)
                shape.append(value)
            elif section_name == 'ASD':
                if key == 'Count':
                    result['ASD'] = [{}] * value
                else:
                    key, index = keyindex(key)
                    result['ASD'][index][key] = value
            elif section_name == 'Band':
                if key[:3] == 'LUT':
                    lut = bands[iband]['LUT']
                    value = struct.pack('<I', value)
                    lut.append(
                        [ord(value[0:1]), ord(value[1:2]), ord(value[2:3])])
                else:
                    key, iband = keyindex(key)
                    bands[iband][key] = value
            elif key[:4] == 'ZPos' and zpos is not None:
                zpos.append(value)
            elif key[:7] == 'TimePos' and tpos is not None:
                tpos.append(value)
            else:
                section[key] = value

    if 'axes' in result:
        sisaxes = {'Band': 'C'}
        axes = []
        shape = []
        for i, x in zip(result['shape'], result['axes']):
            if i > 1:
                axes.append(sisaxes.get(x, x[0].upper()))
                shape.append(i)
        result['axes'] = ''.join(axes)
        result['shape'] = tuple(shape)
    try:
        result['Z']['ZPos'] = numpy.array(
            result['Z']['ZPos'][:result['Dimension']['Z']], 'float64')
    except Exception:
        pass
    try:
        result['Time']['TimePos'] = numpy.array(
            result['Time']['TimePos'][:result['Dimension']['Time']], 'int32')
    except Exception:
        pass
    for band in bands:
        band['LUT'] = numpy.array(band['LUT'], 'uint8')

    return result


Instruction:
Create a Python 3 function for
decoding tile segment bytes into 5D output array.

Response:
def tile_decode(tile, tileindex, tileshape, tiledshape,
                lsb2msb, decompress, unpack, unpredict, out):
    """Decode tile segment bytes into 5D output array."""
    _, imagedepth, imagelength, imagewidth, _ = out.shape
    tileddepth, tiledlength, tiledwidth = tiledshape
    tiledepth, tilelength, tilewidth, samples = tileshape
    tilesize = tiledepth * tilelength * tilewidth * samples

    pl = tileindex // (tiledwidth * tiledlength * tileddepth)
    td = (tileindex // (tiledwidth * tiledlength)) % tileddepth * tiledepth
    tl = (tileindex // tiledwidth) % tiledlength * tilelength
    tw = tileindex % tiledwidth * tilewidth

    if tile:
        if lsb2msb:
            tile = bitorder_decode(tile, out=tile)
        tile = decompress(tile)
        tile = unpack(tile)
        # decompression / unpacking might return too many bytes
        tile = tile[:tilesize]
        try:
            # complete tile according to TIFF specification
            tile.shape = tileshape
        except ValueError:
            # tile fills remaining space; found in some JPEG compressed slides
            s = (min(imagedepth - td, tiledepth),
                 min(imagelength - tl, tilelength),
                 min(imagewidth - tw, tilewidth),
                 samples)
            try:
                tile.shape = s
            except ValueError:
                # incomplete tile; see gdal issue #1179
                log.warning('tile_decode: incomplete tile %s %s',
                            tile.shape, tileshape)
                t = numpy.zeros(tilesize, tile.dtype)
                s = min(tile.size, tilesize)
                t[:s] = tile[:s]
                tile = t.reshape(tileshape)

        tile = unpredict(tile, axis=-2, out=tile)
        out[pl, td:td+tiledepth, tl:tl+tilelength, tw:tw+tilewidth] = (
            tile[:imagedepth-td, :imagelength-tl, :imagewidth-tw])
    else:
        out[pl, td:td+tiledepth, tl:tl+tilelength, tw:tw+tilewidth] = 0


Instruction:
Create a Python 3 function for
unpacking a byte string containing packed RGB samples.

Response:
def unpack_rgb(data, dtype=None, bitspersample=None, rescale=True):
    """Return array from byte string containing packed samples.

    Use to unpack RGB565 or RGB555 to RGB888 format.

    Parameters
    ----------
    data : byte str
        The data to be decoded. Samples in each pixel are stored consecutively.
        Pixels are aligned to 8, 16, or 32 bit boundaries.
    dtype : numpy.dtype
        The sample data type. The byteorder applies also to the data stream.
    bitspersample : tuple
        Number of bits for each sample in a pixel.
    rescale : bool
        Upscale samples to the number of bits in dtype.

    Returns
    -------
    numpy.ndarray
        Flattened array of unpacked samples of native dtype.

    Examples
    --------
    >>> data = struct.pack('BBBB', 0x21, 0x08, 0xff, 0xff)
    >>> print(unpack_rgb(data, '<B', (5, 6, 5), False))
    [ 1  1  1 31 63 31]
    >>> print(unpack_rgb(data, '<B', (5, 6, 5)))
    [  8   4   8 255 255 255]
    >>> print(unpack_rgb(data, '<B', (5, 5, 5)))
    [ 16   8   8 255 255 255]

    """
    if bitspersample is None:
        bitspersample = (5, 6, 5)
    if dtype is None:
        dtype = '<B'
    dtype = numpy.dtype(dtype)
    bits = int(numpy.sum(bitspersample))
    if not (bits <= 32 and all(i <= dtype.itemsize*8 for i in bitspersample)):
        raise ValueError('sample size not supported: %s' % str(bitspersample))
    dt = next(i for i in 'BHI' if numpy.dtype(i).itemsize*8 >= bits)
    data = numpy.frombuffer(data, dtype.byteorder+dt)
    result = numpy.empty((data.size, len(bitspersample)), dtype.char)
    for i, bps in enumerate(bitspersample):
        t = data >> int(numpy.sum(bitspersample[i+1:]))
        t &= int('0b'+'1'*bps, 2)
        if rescale:
            o = ((dtype.itemsize * 8) // bps + 1) * bps
            if o > data.dtype.itemsize * 8:
                t = t.astype('I')
            t *= (2**o - 1) // (2**bps - 1)
            t //= 2**(o - (dtype.itemsize * 8))
        result[:, i] = t
    return result.reshape(-1)


Instruction:
Here you have a function in Python 3, explain what it does
def bitorder_decode(data, out=None, _bitorder=[]):
    if not _bitorder:
        _bitorder.append(
            b'\x00\x80@\xc0 \xa0`\xe0\x10\x90P\xd00\xb0p\xf0\x08\x88H\xc8('
            b'\xa8h\xe8\x18\x98X\xd88\xb8x\xf8\x04\x84D\xc4$\xa4d\xe4\x14'
            b'\x94T\xd44\xb4t\xf4\x0c\x8cL\xcc,\xacl\xec\x1c\x9c\\\xdc<\xbc|'
            b'\xfc\x02\x82B\xc2"\xa2b\xe2\x12\x92R\xd22\xb2r\xf2\n\x8aJ\xca*'
            b'\xaaj\xea\x1a\x9aZ\xda:\xbaz\xfa\x06\x86F\xc6&\xa6f\xe6\x16'
            b'\x96V\xd66\xb6v\xf6\x0e\x8eN\xce.\xaen\xee\x1e\x9e^\xde>\xbe~'
            b'\xfe\x01\x81A\xc1!\xa1a\xe1\x11\x91Q\xd11\xb1q\xf1\t\x89I\xc9)'
            b'\xa9i\xe9\x19\x99Y\xd99\xb9y\xf9\x05\x85E\xc5%\xa5e\xe5\x15'
            b'\x95U\xd55\xb5u\xf5\r\x8dM\xcd-\xadm\xed\x1d\x9d]\xdd=\xbd}'
            b'\xfd\x03\x83C\xc3#\xa3c\xe3\x13\x93S\xd33\xb3s\xf3\x0b\x8bK'
            b'\xcb+\xabk\xeb\x1b\x9b[\xdb;\xbb{\xfb\x07\x87G\xc7\'\xa7g\xe7'
            b'\x17\x97W\xd77\xb7w\xf7\x0f\x8fO\xcf/\xafo\xef\x1f\x9f_'
            b'\xdf?\xbf\x7f\xff')
        _bitorder.append(numpy.frombuffer(_bitorder[0], dtype='uint8'))
    try:
        view = data.view('uint8')
        numpy.take(_bitorder[1], view, out=view)
        return data
    except AttributeError:
        return data.translate(_bitorder[0])
    except ValueError:
        raise NotImplementedError('slices of arrays not supported')
    return None

Response: Decode data into a byte string or numpy array.


Instruction:
Implement a function in Python 3 to
decompress byte string to array of integers.

Response:
def packints_decode(data, dtype, numbits, runlen=0, out=None):
    """Decompress byte string to array of integers.

    This implementation only handles itemsizes 1, 8, 16, 32, and 64 bits.
    Install the imagecodecs package for decoding other integer sizes.

    Parameters
    ----------
    data : byte str
        Data to decompress.
    dtype : numpy.dtype or str
        A numpy boolean or integer type.
    numbits : int
        Number of bits per integer.
    runlen : int
        Number of consecutive integers, after which to start at next byte.

    Examples
    --------
    >>> packints_decode(b'a', 'B', 1)
    array([0, 1, 1, 0, 0, 0, 0, 1], dtype=uint8)

    """
    if numbits == 1:  # bitarray
        data = numpy.frombuffer(data, '|B')
        data = numpy.unpackbits(data)
        if runlen % 8:
            data = data.reshape(-1, runlen + (8 - runlen % 8))
            data = data[:, :runlen].reshape(-1)
        return data.astype(dtype)
    if numbits in (8, 16, 32, 64):
        return numpy.frombuffer(data, dtype)
    raise NotImplementedError('unpacking %s-bit integers to %s not supported'
                              % (numbits, numpy.dtype(dtype)))


Instruction:
How would you implement a function in Python 3 that
returns the palette - colored image.

Response:
def apply_colormap(image, colormap, contig=True):
    """Return palette-colored image.

    The image values are used to index the colormap on axis 1. The returned
    image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype.

    Parameters
    ----------
    image : numpy.ndarray
        Indexes into the colormap.
    colormap : numpy.ndarray
        RGB lookup table aka palette of shape (3, 2**bits_per_sample).
    contig : bool
        If True, return a contiguous array.

    Examples
    --------
    >>> image = numpy.arange(256, dtype='uint8')
    >>> colormap = numpy.vstack([image, image, image]).astype('uint16') * 256
    >>> apply_colormap(image, colormap)[-1]
    array([65280, 65280, 65280], dtype=uint16)

    """
    image = numpy.take(colormap, image, axis=1)
    image = numpy.rollaxis(image, 0, image.ndim)
    if contig:
        image = numpy.ascontiguousarray(image)
    return image


Instruction:
Write a Python 3 function that can
return a reoriented version of an image array.

Response:
def reorient(image, orientation):
    """Return reoriented view of image array.

    Parameters
    ----------
    image : numpy.ndarray
        Non-squeezed output of asarray() functions.
        Axes -3 and -2 must be image length and width respectively.
    orientation : int or str
        One of TIFF.ORIENTATION names or values.

    """
    orient = TIFF.ORIENTATION
    orientation = enumarg(orient, orientation)

    if orientation == orient.TOPLEFT:
        return image
    if orientation == orient.TOPRIGHT:
        return image[..., ::-1, :]
    if orientation == orient.BOTLEFT:
        return image[..., ::-1, :, :]
    if orientation == orient.BOTRIGHT:
        return image[..., ::-1, ::-1, :]
    if orientation == orient.LEFTTOP:
        return numpy.swapaxes(image, -3, -2)
    if orientation == orient.RIGHTTOP:
        return numpy.swapaxes(image, -3, -2)[..., ::-1, :]
    if orientation == orient.RIGHTBOT:
        return numpy.swapaxes(image, -3, -2)[..., ::-1, :, :]
    if orientation == orient.LEFTBOT:
        return numpy.swapaxes(image, -3, -2)[..., ::-1, ::-1, :]
    return image


Instruction:
Can you write a function in Python 3 where it
returns read - only view into input array with elements repeated.

Response:
def repeat_nd(a, repeats):
    """Return read-only view into input array with elements repeated.

    Zoom nD image by integer factors using nearest neighbor interpolation
    (box filter).

    Parameters
    ----------
    a : array_like
        Input array.
    repeats : sequence of int
        The number of repetitions to apply along each dimension of input array.

    Examples
    --------
    >>> repeat_nd([[1, 2], [3, 4]], (2, 2))
    array([[1, 1, 2, 2],
           [1, 1, 2, 2],
           [3, 3, 4, 4],
           [3, 3, 4, 4]])

    """
    a = numpy.asarray(a)
    reshape = []
    shape = []
    strides = []
    for i, j, k in zip(a.strides, a.shape, repeats):
        shape.extend((j, k))
        strides.extend((i, 0))
        reshape.append(j * k)
    return numpy.lib.stride_tricks.as_strided(
        a, shape, strides, writeable=False).reshape(reshape)


Instruction:
Can you generate the documentation for the following Python 3 function
def reshape_nd(data_or_shape, ndim):
    is_shape = isinstance(data_or_shape, tuple)
    shape = data_or_shape if is_shape else data_or_shape.shape
    if len(shape) >= ndim:
        return data_or_shape
    shape = (1,) * (ndim - len(shape)) + shape
    return shape if is_shape else data_or_shape.reshape(shape)

Response: Return image array or shape with at least ndim dimensions.


Instruction:
Make a summary of the following Python 3 code
def squeeze_axes(shape, axes, skip=None):
    if len(shape) != len(axes):
        raise ValueError('dimensions of axes and shape do not match')
    if skip is None:
        skip = 'XY'
    shape, axes = zip(*(i for i in zip(shape, axes)
                        if i[0] > 1 or i[1] in skip))
    return tuple(shape), ''.join(axes)

Response: Return shape and axes with single - dimensional entries removed.


Instruction:
Create a Python 3 function for
returning image with its axes permuted to match specified axes.

Response:
def transpose_axes(image, axes, asaxes=None):
    """Return image with its axes permuted to match specified axes.

    A view is returned if possible.

    >>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape
    (5, 2, 1, 3, 4)

    """
    for ax in axes:
        if ax not in asaxes:
            raise ValueError('unknown axis %s' % ax)
    # add missing axes to image
    if asaxes is None:
        asaxes = 'CTZYX'
    shape = image.shape
    for ax in reversed(asaxes):
        if ax not in axes:
            axes = ax + axes
            shape = (1,) + shape
    image = image.reshape(shape)
    # transpose axes
    image = image.transpose([axes.index(ax) for ax in asaxes])
    return image


Instruction:
Write a Python 3 script for
returning axes matching new shape. By default unknown dimensions are labelled Q.

Response:
def reshape_axes(axes, shape, newshape, unknown=None):
    """Return axes matching new shape.

    By default, unknown dimensions are labelled 'Q'.

    >>> reshape_axes('YXS', (219, 301, 1), (219, 301))
    'YX'
    >>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1))
    'QQYQXQ'

    """
    shape = tuple(shape)
    newshape = tuple(newshape)
    if len(axes) != len(shape):
        raise ValueError('axes do not match shape')

    size = product(shape)
    newsize = product(newshape)
    if size != newsize:
        raise ValueError('cannot reshape %s to %s' % (shape, newshape))
    if not axes or not newshape:
        return ''

    lendiff = max(0, len(shape) - len(newshape))
    if lendiff:
        newshape = newshape + (1,) * lendiff

    i = len(shape)-1
    prodns = 1
    prods = 1
    result = []
    for ns in newshape[::-1]:
        prodns *= ns
        while i > 0 and shape[i] == 1 and ns != 1:
            i -= 1
        if ns == shape[i] and prodns == prods*shape[i]:
            prods *= shape[i]
            result.append(axes[i])
            i -= 1
        elif unknown:
            result.append(unknown)
        else:
            unknown = 'Q'
            result.append(unknown)

    return ''.join(reversed(result[lendiff:]))


Instruction:
Write a Python 3 function that can
read data from sequence of TiffPage and stack them vertically.

Response:
def stack_pages(pages, out=None, maxworkers=None, **kwargs):
    """Read data from sequence of TiffPage and stack them vertically.

    Additional parameters are passsed to the TiffPage.asarray function.

    """
    npages = len(pages)
    if npages == 0:
        raise ValueError('no pages')

    if npages == 1:
        kwargs['maxworkers'] = maxworkers
        return pages[0].asarray(out=out, **kwargs)

    page0 = next(p for p in pages if p is not None).keyframe
    page0.asarray(validate=None)  # ThreadPoolExecutor swallows exceptions
    shape = (npages,) + page0.shape
    dtype = page0.dtype
    out = create_output(out, shape, dtype)

    if maxworkers is None:
        if page0.compression > 1:
            if page0.is_tiled:
                maxworkers = 1
                kwargs['maxworkers'] = 0
            else:
                maxworkers = 0
        else:
            maxworkers = 1
    if maxworkers == 0:
        import multiprocessing  # noqa: delay import
        maxworkers = multiprocessing.cpu_count() // 2
    if maxworkers > 1:
        kwargs['maxworkers'] = 1

    page0.parent.filehandle.lock = maxworkers > 1

    filecache = OpenFileCache(size=max(4, maxworkers),
                              lock=page0.parent.filehandle.lock)

    def func(page, index, out=out, filecache=filecache, kwargs=kwargs):
        """Read, decode, and copy page data."""
        if page is not None:
            filecache.open(page.parent.filehandle)
            out[index] = page.asarray(lock=filecache.lock, reopen=False,
                                      validate=False, **kwargs)
            filecache.close(page.parent.filehandle)

    if maxworkers < 2:
        for i, page in enumerate(pages):
            func(page, i)
    else:
        # TODO: add exception handling
        with ThreadPoolExecutor(maxworkers) as executor:
            executor.map(func, pages, range(npages))

    filecache.clear()
    page0.parent.filehandle.lock = None

    return out


Instruction:
Write a Python 3 script for
returning cleaned offsets and byte counts.

Response:
def clean_offsetscounts(offsets, counts):
    """Return cleaned offsets and byte counts.

    Remove zero offsets and counts.
    Use to sanitize StripOffsets and StripByteCounts tag values.

    """
    # TODO: cythonize this
    offsets = list(offsets)
    counts = list(counts)
    size = len(offsets)
    if size != len(counts):
        raise ValueError('StripOffsets and StripByteCounts mismatch')
    j = 0
    for i, (o, b) in enumerate(zip(offsets, counts)):
        if b > 0:
            if o > 0:
                if i > j:
                    offsets[j] = o
                    counts[j] = b
                j += 1
                continue
            raise ValueError('invalid offset')
        log.warning('clean_offsetscounts: empty bytecount')
    if size == len(offsets):
        return offsets, counts
    if j == 0:
        return [offsets[0]], [counts[0]]
    return offsets[:j], counts[:j]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def buffered_read(fh, lock, offsets, bytecounts, buffersize=None):
    if buffersize is None:
        buffersize = 2**26
    length = len(offsets)
    i = 0
    while i < length:
        data = []
        with lock:
            size = 0
            while size < buffersize and i < length:
                fh.seek(offsets[i])
                bytecount = bytecounts[i]
                data.append(fh.read(bytecount))
                # buffer = bytearray(bytecount)
                # n = fh.readinto(buffer)
                # data.append(buffer[:n])
                size += bytecount
                i += 1
        for segment in data:
            yield segment

Response: Return iterator over segments read from file.


Instruction:
Write a Python 3 script to
create an array of numpy arrays of compatible shape and dtype.

Response:
def create_output(out, shape, dtype, mode='w+', suffix=None):
    """Return numpy array where image data of shape and dtype can be copied.

    The 'out' parameter may have the following values or types:

    None
        An empty array of shape and dtype is created and returned.
    numpy.ndarray
        An existing writable array of compatible dtype and shape. A view of
        the same array is returned after verification.
    'memmap' or 'memmap:tempdir'
        A memory-map to an array stored in a temporary binary file on disk
        is created and returned.
    str or open file
        The file name or file object used to create a memory-map to an array
        stored in a binary file on disk. The created memory-mapped array is
        returned.

    """
    if out is None:
        return numpy.zeros(shape, dtype)
    if isinstance(out, str) and out[:6] == 'memmap':
        import tempfile  # noqa: delay import
        tempdir = out[7:] if len(out) > 7 else None
        if suffix is None:
            suffix = '.memmap'
        with tempfile.NamedTemporaryFile(dir=tempdir, suffix=suffix) as fh:
            return numpy.memmap(fh, shape=shape, dtype=dtype, mode=mode)
    if isinstance(out, numpy.ndarray):
        if product(shape) != product(out.shape):
            raise ValueError('incompatible output shape')
        if not numpy.can_cast(dtype, out.dtype):
            raise ValueError('incompatible output dtype')
        return out.reshape(shape)
    if isinstance(out, pathlib.Path):
        out = str(out)
    return numpy.memmap(out, shape=shape, dtype=dtype, mode=mode)


Instruction:
Create a Python 3 function for
returning Python object from Matlab string representation.

Response:
def matlabstr2py(string):
    """Return Python object from Matlab string representation.

    Return str, bool, int, float, list (Matlab arrays or cells), or
    dict (Matlab structures) types.

    Use to access ScanImage metadata.

    >>> matlabstr2py('1')
    1
    >>> matlabstr2py("['x y z' true false; 1 2.0 -3e4; NaN Inf @class]")
    [['x y z', True, False], [1, 2.0, -30000.0], [nan, inf, '@class']]
    >>> d = matlabstr2py("SI.hChannels.channelType = {'stripe' 'stripe'}\\n"
    ...                  "SI.hChannels.channelsActive = 2")
    >>> d['SI.hChannels.channelType']
    ['stripe', 'stripe']

    """
    # TODO: handle invalid input
    # TODO: review unboxing of multidimensional arrays

    def lex(s):
        # return sequence of tokens from matlab string representation
        tokens = ['[']
        while True:
            t, i = next_token(s)
            if t is None:
                break
            if t == ';':
                tokens.extend((']', '['))
            elif t == '[':
                tokens.extend(('[', '['))
            elif t == ']':
                tokens.extend((']', ']'))
            else:
                tokens.append(t)
            s = s[i:]
        tokens.append(']')
        return tokens

    def next_token(s):
        # return next token in matlab string
        length = len(s)
        if length == 0:
            return None, 0
        i = 0
        while i < length and s[i] == ' ':
            i += 1
        if i == length:
            return None, i
        if s[i] in '{[;]}':
            return s[i], i + 1
        if s[i] == "'":
            j = i + 1
            while j < length and s[j] != "'":
                j += 1
            return s[i: j+1], j + 1
        if s[i] == '<':
            j = i + 1
            while j < length and s[j] != '>':
                j += 1
            return s[i: j+1], j + 1
        j = i
        while j < length and not s[j] in ' {[;]}':
            j += 1
        return s[i:j], j

    def value(s, fail=False):
        # return Python value of token
        s = s.strip()
        if not s:
            return s
        if len(s) == 1:
            try:
                return int(s)
            except Exception:
                if fail:
                    raise ValueError()
                return s
        if s[0] == "'":
            if fail and s[-1] != "'" or "'" in s[1:-1]:
                raise ValueError()
            return s[1:-1]
        if s[0] == '<':
            if fail and s[-1] != '>' or '<' in s[1:-1]:
                raise ValueError()
            return s
        if fail and any(i in s for i in " ';[]{}"):
            raise ValueError()
        if s[0] == '@':
            return s
        if s in ('true', 'True'):
            return True
        if s in ('false', 'False'):
            return False
        if s[:6] == 'zeros(':
            return numpy.zeros([int(i) for i in s[6:-1].split(',')]).tolist()
        if s[:5] == 'ones(':
            return numpy.ones([int(i) for i in s[5:-1].split(',')]).tolist()
        if '.' in s or 'e' in s:
            try:
                return float(s)
            except Exception:
                pass
        try:
            return int(s)
        except Exception:
            pass
        try:
            return float(s)  # nan, inf
        except Exception:
            if fail:
                raise ValueError()
        return s

    def parse(s):
        # return Python value from string representation of Matlab value
        s = s.strip()
        try:
            return value(s, fail=True)
        except ValueError:
            pass
        result = add2 = []
        levels = [add2]
        for t in lex(s):
            if t in '[{':
                add2 = []
                levels.append(add2)
            elif t in ']}':
                x = levels.pop()
                if len(x) == 1 and isinstance(x[0], (list, str)):
                    x = x[0]
                add2 = levels[-1]
                add2.append(x)
            else:
                add2.append(value(t))
        if len(result) == 1 and isinstance(result[0], (list, str)):
            result = result[0]
        return result

    if '\r' in string or '\n' in string:
        # structure
        d = {}
        for line in string.splitlines():
            line = line.strip()
            if not line or line[0] == '%':
                continue
            k, v = line.split('=', 1)
            k = k.strip()
            if any(c in k for c in " ';[]{}<>"):
                continue
            d[k] = parse(v)
        return d
    return parse(string)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def stripascii(string):
    # TODO: pythonize this
    i = len(string)
    while i:
        i -= 1
        if 8 < byte2int(string[i]) < 127:
            break
    else:
        i = -1
    return string[:i+1]

Response: Return string truncated at last byte that is 7 - bit ASCII.


Instruction:
Here you have a function in Python 3, explain what it does
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')):
    value = value.strip().lower()
    if value in true:  # might raise UnicodeWarning/BytesWarning
        return True
    if value in false:
        return False
    raise TypeError()

Response: Return string as bool if possible else raise TypeError.


Instruction:
How would you implement a function in Python 3 that
returns argument as one of types if possible.

Response:
def astype(value, types=None):
    """Return argument as one of types if possible.

    >>> astype('42')
    42
    >>> astype('3.14')
    3.14
    >>> astype('True')
    True
    >>> astype(b'Neee-Wom')
    'Neee-Wom'

    """
    if types is None:
        types = int, float, asbool, bytes2str
    for typ in types:
        try:
            return typ(value)
        except (ValueError, AttributeError, TypeError, UnicodeEncodeError):
            pass
    return value


Instruction:
Implement a Python 3 function for
returning file size as string from byte size.

Response:
def format_size(size, threshold=1536):
    """Return file size as string from byte size.

    >>> format_size(1234)
    '1234 B'
    >>> format_size(12345678901)
    '11.50 GiB'

    """
    if size < threshold:
        return "%i B" % size
    for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
        size /= 1024.0
        if size < threshold:
            return "%.2f %s" % (size, unit)
    return 'ginormous'


Instruction:
Can you create a Python 3 function that
returns a list of strings in natural order.

Response:
def natural_sorted(iterable):
    """Return human sorted list of strings.

    E.g. for sorting file names.

    >>> natural_sorted(['f1', 'f2', 'f10'])
    ['f1', 'f2', 'f10']

    """
    def sortkey(x):
        return [(int(c) if c.isdigit() else c) for c in re.split(numbers, x)]

    numbers = re.compile(r'(\d+)')
    return sorted(iterable, key=sortkey)


Instruction:
Write a Python 3 function for
returning datetime object from timestamp in Excel serial format.

Response:
def excel_datetime(timestamp, epoch=None):
    """Return datetime object from timestamp in Excel serial format.

    Convert LSM time stamps.

    >>> excel_datetime(40237.029999999795)
    datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)

    """
    if epoch is None:
        epoch = datetime.datetime.fromordinal(693594)
    return epoch + datetime.timedelta(timestamp)


Instruction:
Can you generate the documentation for the following Python 3 function
def julian_datetime(julianday, milisecond=0):
    if julianday <= 1721423:
        # no datetime before year 1
        return None

    a = julianday + 1
    if a > 2299160:
        alpha = math.trunc((a - 1867216.25) / 36524.25)
        a += 1 + alpha - alpha // 4
    b = a + (1524 if a > 1721423 else 1158)
    c = math.trunc((b - 122.1) / 365.25)
    d = math.trunc(365.25 * c)
    e = math.trunc((b - d) / 30.6001)

    day = b - d - math.trunc(30.6001 * e)
    month = e - (1 if e < 13.5 else 13)
    year = c - (4716 if month > 2.5 else 4715)

    hour, milisecond = divmod(milisecond, 1000 * 60 * 60)
    minute, milisecond = divmod(milisecond, 1000 * 60)
    second, milisecond = divmod(milisecond, 1000)

    return datetime.datetime(year, month, day,
                             hour, minute, second, milisecond)

Response: Convert Julian dates according to MetaMorph.


Instruction:
Make a summary of the following Python 3 code
def byteorder_isnative(byteorder):
    if byteorder in ('=', sys.byteorder):
        return True
    keys = {'big': '>', 'little': '<'}
    return keys.get(byteorder, byteorder) == keys[sys.byteorder]

Response: Return True if byteorder matches the system s byteorder.


Instruction:
Create a Python 3 function for
returning numpy. recarray as dict.

Response:
def recarray2dict(recarray):
    """Return numpy.recarray as dict."""
    # TODO: subarrays
    result = {}
    for descr, value in zip(recarray.dtype.descr, recarray):
        name, dtype = descr[:2]
        if dtype[1] == 'S':
            value = bytes2str(stripnull(value))
        elif value.ndim < 2:
            value = value.tolist()
        result[name] = value
    return result


Instruction:
How would you explain what the following Python 3 function does
def xml2dict(xml, sanitize=True, prefix=None):
    from xml.etree import cElementTree as etree  # delayed import

    at = tx = ''
    if prefix:
        at, tx = prefix

    def astype(value):
        # return value as int, float, bool, or str
        for t in (int, float, asbool):
            try:
                return t(value)
            except Exception:
                pass
        return value

    def etree2dict(t):
        # adapted from https://stackoverflow.com/a/10077069/453463
        key = t.tag
        if sanitize:
            key = key.rsplit('}', 1)[-1]
        d = {key: {} if t.attrib else None}
        children = list(t)
        if children:
            dd = collections.defaultdict(list)
            for dc in map(etree2dict, children):
                for k, v in dc.items():
                    dd[k].append(astype(v))
            d = {key: {k: astype(v[0]) if len(v) == 1 else astype(v)
                       for k, v in dd.items()}}
        if t.attrib:
            d[key].update((at + k, astype(v)) for k, v in t.attrib.items())
        if t.text:
            text = t.text.strip()
            if children or t.attrib:
                if text:
                    d[key][tx + 'value'] = astype(text)
            else:
                d[key] = astype(text)
        return d

    return etree2dict(etree.fromstring(xml))

Response: Return XML as dict.


Instruction:
Make a summary of the following Python 3 code
def hexdump(bytestr, width=75, height=24, snipat=-2, modulo=2, ellipsis=None):
    size = len(bytestr)
    if size < 1 or width < 2 or height < 1:
        return ''
    if height == 1:
        addr = b''
        bytesperline = min(modulo * (((width - len(addr)) // 4) // modulo),
                           size)
        if bytesperline < 1:
            return ''
        nlines = 1
    else:
        addr = b'%%0%ix: ' % len(b'%x' % size)
        bytesperline = min(modulo * (((width - len(addr % 1)) // 4) // modulo),
                           size)
        if bytesperline < 1:
            return ''
        width = 3*bytesperline + len(addr % 1)
        nlines = (size - 1) // bytesperline + 1

    if snipat is None or snipat == 1:
        snipat = height
    elif 0 < abs(snipat) < 1:
        snipat = int(math.floor(height * snipat))
    if snipat < 0:
        snipat += height

    if height == 1 or nlines == 1:
        blocks = [(0, bytestr[:bytesperline])]
        addr = b''
        height = 1
        width = 3 * bytesperline
    elif height is None or nlines <= height:
        blocks = [(0, bytestr)]
    elif snipat <= 0:
        start = bytesperline * (nlines - height)
        blocks = [(start, bytestr[start:])]  # (start, None)
    elif snipat >= height or height < 3:
        end = bytesperline * height
        blocks = [(0, bytestr[:end])]  # (end, None)
    else:
        end1 = bytesperline * snipat
        end2 = bytesperline * (height - snipat - 1)
        blocks = [(0, bytestr[:end1]),
                  (size-end1-end2, None),
                  (size-end2, bytestr[size-end2:])]

    ellipsis = b'...' if ellipsis is None else str2bytes(ellipsis)
    result = []
    for start, bytestr in blocks:
        if bytestr is None:
            result.append(ellipsis)  # 'skip %i bytes' % start)
            continue
        hexstr = binascii.hexlify(bytestr)
        strstr = re.sub(br'[^\x20-\x7f]', b'.', bytestr)
        for i in range(0, len(bytestr), bytesperline):
            h = hexstr[2*i:2*i+bytesperline*2]
            r = (addr % (i + start)) if height > 1 else addr
            r += b' '.join(h[i:i+2] for i in range(0, 2*bytesperline, 2))
            r += b' ' * (width - len(r))
            r += strstr[i:i+bytesperline]
            result.append(r)
    result = b'\n'.join(result)
    if sys.version_info[0] == 3:
        result = result.decode('ascii')
    return result

Response: Return hexdump representation of byte string.


Instruction:
Given the following Python 3 function, write the documentation
def isprintable(string):
    string = string.strip()
    if not string:
        return True
    if sys.version_info[0] == 3:
        try:
            return string.isprintable()
        except Exception:
            pass
        try:
            return string.decode('utf-8').isprintable()
        except Exception:
            pass
    else:
        if string.isalnum():
            return True
        printable = ('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST'
                     'UVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c')
        return all(c in printable for c in string)

Response: Return True if all characters in string are printable.


Instruction:
Make a summary of the following Python 3 code
def clean_whitespace(string, compact=False):
    for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'),
                 ('\t', ' '), ('  ', ' ')):
        string = string.replace(a, b)
    if compact:
        for a, b in (('\n', ' '), ('[ ', '['),
                     ('  ', ' '), ('  ', ' '), ('  ', ' ')):
            string = string.replace(a, b)
    return string.strip()

Response: Return string with compressed whitespace.


Instruction:
Can you write a function in Python 3 where it
returns pretty formatted XML.

Response:
def pformat_xml(xml):
    """Return pretty formatted XML."""
    try:
        from lxml import etree  # delayed import
        if not isinstance(xml, bytes):
            xml = xml.encode('utf-8')
        xml = etree.parse(io.BytesIO(xml))
        xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
                             encoding=xml.docinfo.encoding)
        xml = bytes2str(xml)
    except Exception:
        if isinstance(xml, bytes):
            xml = bytes2str(xml)
        xml = xml.replace('><', '>\n<')
    return xml.replace('  ', ' ').replace('\t', ' ')


Instruction:
Given the following Python 3 function, write the documentation
def pformat(arg, width=79, height=24, compact=True):
    if height is None or height < 1:
        height = 1024
    if width is None or width < 1:
        width = 256

    npopt = numpy.get_printoptions()
    numpy.set_printoptions(threshold=100, linewidth=width)

    if isinstance(arg, basestring):
        if arg[:5].lower() in ('<?xml', b'<?xml'):
            if isinstance(arg, bytes):
                arg = bytes2str(arg)
            if height == 1:
                arg = arg[:4*width]
            else:
                arg = pformat_xml(arg)
        elif isinstance(arg, bytes):
            if isprintable(arg):
                arg = bytes2str(arg)
                arg = clean_whitespace(arg)
            else:
                numpy.set_printoptions(**npopt)
                return hexdump(arg, width=width, height=height, modulo=1)
        arg = arg.rstrip()
    elif isinstance(arg, numpy.record):
        arg = arg.pprint()
    else:
        import pprint  # delayed import
        compact = {} if sys.version_info[0] == 2 else dict(compact=compact)
        arg = pprint.pformat(arg, width=width, **compact)

    numpy.set_printoptions(**npopt)

    if height == 1:
        arg = clean_whitespace(arg, compact=True)
        return arg[:width]

    argl = list(arg.splitlines())
    if len(argl) > height:
        arg = '\n'.join(argl[:height//2] + ['...'] + argl[-height//2:])
    return arg

Response: Return pretty formatted representation of object as string.


Instruction:
Write a Python 3 script for
returning string cut to specified length.

Response:
def snipstr(string, width=79, snipat=None, ellipsis='...'):
    """Return string cut to specified length.

    >>> snipstr('abcdefghijklmnop', 8)
    'abc...op'

    """
    if snipat is None:
        snipat = 0.5
    if ellipsis is None:
        if isinstance(string, bytes):
            ellipsis = b'...'
        else:
            ellipsis = u'\u2026'  # does not print on win-py3.5
    esize = len(ellipsis)

    splitlines = string.splitlines()
    # TODO: finish and test multiline snip

    result = []
    for line in splitlines:
        if line is None:
            result.append(ellipsis)
            continue
        linelen = len(line)
        if linelen <= width:
            result.append(string)
            continue

        split = snipat
        if split is None or split == 1:
            split = linelen
        elif 0 < abs(split) < 1:
            split = int(math.floor(linelen * split))
        if split < 0:
            split += linelen
            if split < 0:
                split = 0

        if esize == 0 or width < esize + 1:
            if split <= 0:
                result.append(string[-width:])
            else:
                result.append(string[:width])
        elif split <= 0:
            result.append(ellipsis + string[esize-width:])
        elif split >= linelen or width < esize + 4:
            result.append(string[:width-esize] + ellipsis)
        else:
            splitlen = linelen - width + esize
            end1 = split - splitlen // 2
            end2 = end1 + splitlen
            result.append(string[:end1] + ellipsis + string[end2:])

    if isinstance(string, bytes):
        return b'\n'.join(result)
    return '\n'.join(result)


Instruction:
Explain what the following Python 3 code does
def enumarg(enum, arg):
    try:
        return enum(arg)
    except Exception:
        try:
            return enum[arg.upper()]
        except Exception:
            raise ValueError('invalid argument %s' % arg)

Response: Return enum member from its name or value.


Instruction:
Here you have a function in Python 3, explain what it does
def parse_kwargs(kwargs, *keys, **keyvalues):
    result = {}
    for key in keys:
        if key in kwargs:
            result[key] = kwargs[key]
            del kwargs[key]
    for key, value in keyvalues.items():
        if key in kwargs:
            result[key] = kwargs[key]
            del kwargs[key]
        else:
            result[key] = value
    return result

Response: Parse kwargs and return a dict with keys from keys and values from keyvals.


Instruction:
Write a Python 3 function that can
update dict with keys and values if keys do not already exist.

Response:
def update_kwargs(kwargs, **keyvalues):
    """Update dict with keys and values if keys do not already exist.

    >>> kwargs = {'one': 1, }
    >>> update_kwargs(kwargs, one=None, two=2)
    >>> kwargs == {'one': 1, 'two': 2}
    True

    """
    for key, value in keyvalues.items():
        if key not in kwargs:
            kwargs[key] = value


Instruction:
Make a summary of the following Python 3 code
def validate_jhove(filename, jhove=None, ignore=None):
    import subprocess  # noqa: delayed import
    if ignore is None:
        ignore = ['More than 50 IFDs']
    if jhove is None:
        jhove = 'jhove'
    out = subprocess.check_output([jhove, filename, '-m', 'TIFF-hul'])
    if b'ErrorMessage: ' in out:
        for line in out.splitlines():
            line = line.strip()
            if line.startswith(b'ErrorMessage: '):
                error = line[14:].decode('utf8')
                for i in ignore:
                    if i in error:
                        break
                else:
                    raise ValueError(error)
                break

Response: Validate TIFF file using JHOVE.


Instruction:
How would you explain what the following Python 3 function does
def lsm2bin(lsmfile, binfile=None, tile=None, verbose=True):
    verbose = print_ if verbose else nullfunc

    if tile is None:
        tile = (256, 256)

    if binfile is None:
        binfile = lsmfile
    elif binfile.lower() == 'none':
        binfile = None
    if binfile:
        binfile += '_(z%ic%iy%ix%i)_m%%ip%%it%%03iy%%ix%%i.bin'

    verbose('\nOpening LSM file... ', end='', flush=True)
    start_time = time.time()

    with TiffFile(lsmfile) as lsm:
        if not lsm.is_lsm:
            verbose('\n', lsm, flush=True)
            raise ValueError('not a LSM file')
        series = lsm.series[0]  # first series contains the image data
        shape = series.shape
        axes = series.axes
        dtype = series.dtype
        size = product(shape) * dtype.itemsize

        verbose('%.3f s' % (time.time() - start_time))
        # verbose(lsm, flush=True)
        verbose('Image\n  axes:  %s\n  shape: %s\n  dtype: %s\n  size:  %s'
                % (axes, shape, dtype, format_size(size)), flush=True)
        if not series.axes.endswith('TZCYX'):
            raise ValueError('not a *TZCYX LSM file')

        verbose('Copying image from LSM to BIN files', end='', flush=True)
        start_time = time.time()
        tiles = shape[-2] // tile[-2], shape[-1] // tile[-1]
        if binfile:
            binfile = binfile % (shape[-4], shape[-3], tile[0], tile[1])
        shape = (1,) * (7-len(shape)) + shape
        # cache for ZCYX stacks and output files
        data = numpy.empty(shape[3:], dtype=dtype)
        out = numpy.empty((shape[-4], shape[-3], tile[0], tile[1]),
                          dtype=dtype)
        # iterate over Tiff pages containing data
        pages = iter(series.pages)
        for m in range(shape[0]):  # mosaic axis
            for p in range(shape[1]):  # position axis
                for t in range(shape[2]):  # time axis
                    for z in range(shape[3]):  # z slices
                        data[z] = next(pages).asarray()
                    for y in range(tiles[0]):  # tile y
                        for x in range(tiles[1]):  # tile x
                            out[:] = data[...,
                                          y*tile[0]:(y+1)*tile[0],
                                          x*tile[1]:(x+1)*tile[1]]
                            if binfile:
                                out.tofile(binfile % (m, p, t, y, x))
                            verbose('.', end='', flush=True)
        verbose(' %.3f s' % (time.time() - start_time))

Response: Convert a LSM file to a series of BIN files.


Instruction:
Write a Python 3 function that can
plot n - dimensional images using matplotlib. pyplot.

Response:
def imshow(data, photometric=None, planarconfig=None, bitspersample=None,
           interpolation=None, cmap=None, vmin=None, vmax=None,
           figure=None, title=None, dpi=96, subplot=None, maxdim=None,
           **kwargs):
    """Plot n-dimensional images using matplotlib.pyplot.

    Return figure, subplot and plot axis.
    Requires pyplot already imported C{from matplotlib import pyplot}.

    Parameters
    ----------
    data : nd array
        The image data.
    photometric : {'MINISWHITE', 'MINISBLACK', 'RGB', or 'PALETTE'}
        The color space of the image data.
    planarconfig : {'CONTIG' or 'SEPARATE'}
        Defines how components of each pixel are stored.
    bitspersample : int
        Number of bits per channel in integer RGB images.
    interpolation : str
        The image interpolation method used in matplotlib.imshow. By default,
        'nearest' will be used for image dimensions <= 512, else 'bilinear'.
    cmap : str or matplotlib.colors.Colormap
        The colormap maps non-RGBA scalar data to colors.
    vmin, vmax : scalar
        Data range covered by the colormap. By default, the complete
        range of the data is covered.
    figure : matplotlib.figure.Figure
        Matplotlib figure to use for plotting.
    title : str
        Window and subplot title.
    subplot : int
        A matplotlib.pyplot.subplot axis.
    maxdim : int
        Maximum image width and length.
    kwargs : dict
        Additional arguments for matplotlib.pyplot.imshow.

    """
    # TODO: rewrite detection of isrgb, iscontig
    # TODO: use planarconfig
    if photometric is None:
        photometric = 'RGB'
    if maxdim is None:
        maxdim = 2**16
    isrgb = photometric in ('RGB', 'YCBCR')  # 'PALETTE', 'YCBCR'

    if data.dtype == 'float16':
        data = data.astype('float32')

    if data.dtype.kind == 'b':
        isrgb = False

    if isrgb and not (data.shape[-1] in (3, 4) or (
            data.ndim > 2 and data.shape[-3] in (3, 4))):
        isrgb = False
        photometric = 'MINISBLACK'

    data = data.squeeze()
    if photometric in ('MINISWHITE', 'MINISBLACK', None):
        data = reshape_nd(data, 2)
    else:
        data = reshape_nd(data, 3)

    dims = data.ndim
    if dims < 2:
        raise ValueError('not an image')
    if dims == 2:
        dims = 0
        isrgb = False
    else:
        if isrgb and data.shape[-3] in (3, 4):
            data = numpy.swapaxes(data, -3, -2)
            data = numpy.swapaxes(data, -2, -1)
        elif not isrgb and (data.shape[-1] < data.shape[-2] // 8 and
                            data.shape[-1] < data.shape[-3] // 8 and
                            data.shape[-1] < 5):
            data = numpy.swapaxes(data, -3, -1)
            data = numpy.swapaxes(data, -2, -1)
        isrgb = isrgb and data.shape[-1] in (3, 4)
        dims -= 3 if isrgb else 2

    if interpolation is None:
        threshold = 512
    elif isinstance(interpolation, int):
        threshold = interpolation
    else:
        threshold = 0

    if isrgb:
        data = data[..., :maxdim, :maxdim, :maxdim]
        if threshold:
            if (data.shape[-2] > threshold or data.shape[-3] > threshold):
                interpolation = 'bilinear'
            else:
                interpolation = 'nearest'
    else:
        data = data[..., :maxdim, :maxdim]
        if threshold:
            if (data.shape[-1] > threshold or data.shape[-2] > threshold):
                interpolation = 'bilinear'
            else:
                interpolation = 'nearest'

    if photometric == 'PALETTE' and isrgb:
        datamax = data.max()
        if datamax > 255:
            data = data >> 8  # possible precision loss
        data = data.astype('B')
    elif data.dtype.kind in 'ui':
        if not (isrgb and data.dtype.itemsize <= 1) or bitspersample is None:
            try:
                bitspersample = int(math.ceil(math.log(data.max(), 2)))
            except Exception:
                bitspersample = data.dtype.itemsize * 8
        elif not isinstance(bitspersample, inttypes):
            # bitspersample can be tuple, e.g. (5, 6, 5)
            bitspersample = data.dtype.itemsize * 8
        datamax = 2**bitspersample
        if isrgb:
            if bitspersample < 8:
                data = data << (8 - bitspersample)
            elif bitspersample > 8:
                data = data >> (bitspersample - 8)  # precision loss
            data = data.astype('B')
    elif data.dtype.kind == 'f':
        datamax = data.max()
        if isrgb and datamax > 1.0:
            if data.dtype.char == 'd':
                data = data.astype('f')
                data /= datamax
            else:
                data = data / datamax
    elif data.dtype.kind == 'b':
        datamax = 1
    elif data.dtype.kind == 'c':
        data = numpy.absolute(data)
        datamax = data.max()

    if isrgb:
        vmin = 0
    else:
        if vmax is None:
            vmax = datamax
        if vmin is None:
            if data.dtype.kind == 'i':
                dtmin = numpy.iinfo(data.dtype).min
                vmin = numpy.min(data)
                if vmin == dtmin:
                    vmin = numpy.min(data[data > dtmin])
            elif data.dtype.kind == 'f':
                dtmin = numpy.finfo(data.dtype).min
                vmin = numpy.min(data)
                if vmin == dtmin:
                    vmin = numpy.min(data[data > dtmin])
            else:
                vmin = 0

    pyplot = sys.modules['matplotlib.pyplot']

    if figure is None:
        pyplot.rc('font', family='sans-serif', weight='normal', size=8)
        figure = pyplot.figure(dpi=dpi, figsize=(10.3, 6.3), frameon=True,
                               facecolor='1.0', edgecolor='w')
        try:
            figure.canvas.manager.window.title(title)
        except Exception:
            pass
        size = len(title.splitlines()) if title else 1
        pyplot.subplots_adjust(bottom=0.03*(dims+2), top=0.98-size*0.03,
                               left=0.1, right=0.95, hspace=0.05, wspace=0.0)
    if subplot is None:
        subplot = 111
    subplot = pyplot.subplot(subplot)
    subplot.set_facecolor((0, 0, 0))

    if title:
        try:
            title = unicode(title, 'Windows-1252')
        except TypeError:
            pass
        pyplot.title(title, size=11)

    if cmap is None:
        if data.dtype.char == '?':
            cmap = 'gray'
        elif data.dtype.kind in 'buf' or vmin == 0:
            cmap = 'viridis'
        else:
            cmap = 'coolwarm'
        if photometric == 'MINISWHITE':
            cmap += '_r'

    image = pyplot.imshow(numpy.atleast_2d(data[(0,) * dims].squeeze()),
                          vmin=vmin, vmax=vmax, cmap=cmap,
                          interpolation=interpolation, **kwargs)

    if not isrgb:
        pyplot.colorbar()  # panchor=(0.55, 0.5), fraction=0.05

    def format_coord(x, y):
        # callback function to format coordinate display in toolbar
        x = int(x + 0.5)
        y = int(y + 0.5)
        try:
            if dims:
                return '%s @ %s [%4i, %4i]' % (
                    curaxdat[1][y, x], current, y, x)
            return '%s @ [%4i, %4i]' % (data[y, x], y, x)
        except IndexError:
            return ''

    def none(event):
        return ''

    subplot.format_coord = format_coord
    image.get_cursor_data = none
    image.format_cursor_data = none

    if dims:
        current = list((0,) * dims)
        curaxdat = [0, data[tuple(current)].squeeze()]
        sliders = [pyplot.Slider(
            pyplot.axes([0.125, 0.03*(axis+1), 0.725, 0.025]),
            'Dimension %i' % axis, 0, data.shape[axis]-1, 0, facecolor='0.5',
            valfmt='%%.0f [%i]' % data.shape[axis]) for axis in range(dims)]
        for slider in sliders:
            slider.drawon = False

        def set_image(current, sliders=sliders, data=data):
            # change image and redraw canvas
            curaxdat[1] = data[tuple(current)].squeeze()
            image.set_data(curaxdat[1])
            for ctrl, index in zip(sliders, current):
                ctrl.eventson = False
                ctrl.set_val(index)
                ctrl.eventson = True
            figure.canvas.draw()

        def on_changed(index, axis, data=data, current=current):
            # callback function for slider change event
            index = int(round(index))
            curaxdat[0] = axis
            if index == current[axis]:
                return
            if index >= data.shape[axis]:
                index = 0
            elif index < 0:
                index = data.shape[axis] - 1
            current[axis] = index
            set_image(current)

        def on_keypressed(event, data=data, current=current):
            # callback function for key press event
            key = event.key
            axis = curaxdat[0]
            if str(key) in '0123456789':
                on_changed(key, axis)
            elif key == 'right':
                on_changed(current[axis] + 1, axis)
            elif key == 'left':
                on_changed(current[axis] - 1, axis)
            elif key == 'up':
                curaxdat[0] = 0 if axis == len(data.shape)-1 else axis + 1
            elif key == 'down':
                curaxdat[0] = len(data.shape)-1 if axis == 0 else axis - 1
            elif key == 'end':
                on_changed(data.shape[axis] - 1, axis)
            elif key == 'home':
                on_changed(0, axis)

        figure.canvas.mpl_connect('key_press_event', on_keypressed)
        for axis, ctrl in enumerate(sliders):
            ctrl.on_changed(lambda k, a=axis: on_changed(k, a))

    return figure, subplot, image


Instruction:
Can you generate the documentation for the following Python 3 function
def askopenfilename(**kwargs):
    try:
        from Tkinter import Tk
        import tkFileDialog as filedialog
    except ImportError:
        from tkinter import Tk, filedialog
    root = Tk()
    root.withdraw()
    root.update()
    filenames = filedialog.askopenfilename(**kwargs)
    root.destroy()
    return filenames

Response: Return file name s from Tkinter s file open dialog.