Instruction:
Can you generate the documentation for the following Python 3 function
def _parse(self, command):
        cmd, id_, args = command[0], command[1], command[2:]

        if cmd == 'CURRENT':
            # This context is made current
            self.env.clear()
            self._gl_initialize()
            self.env['fbo'] = args[0]
            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, args[0])
        elif cmd == 'FUNC':
            # GL function call
            args = [as_enum(a) for a in args]
            try:
                getattr(gl, id_)(*args)
            except AttributeError:
                logger.warning('Invalid gl command: %r' % id_)
        elif cmd == 'CREATE':
            # Creating an object
            if args[0] is not None:
                klass = self._classmap[args[0]]
                self._objects[id_] = klass(self, id_)
            else:
                self._invalid_objects.add(id_)
        elif cmd == 'DELETE':
            # Deleting an object
            ob = self._objects.get(id_, None)
            if ob is not None:
                self._objects[id_] = JUST_DELETED
                ob.delete()
        else:
            # Doing somthing to an object
            ob = self._objects.get(id_, None)
            if ob == JUST_DELETED:
                return
            if ob is None:
                if id_ not in self._invalid_objects:
                    raise RuntimeError('Cannot %s object %i because it '
                                       'does not exist' % (cmd, id_))
                return
            # Triage over command. Order of commands is set so most
            # common ones occur first.
            if cmd == 'DRAW':  # Program
                ob.draw(*args)
            elif cmd == 'TEXTURE':  # Program
                ob.set_texture(*args)
            elif cmd == 'UNIFORM':  # Program
                ob.set_uniform(*args)
            elif cmd == 'ATTRIBUTE':  # Program
                ob.set_attribute(*args)
            elif cmd == 'DATA':  # VertexBuffer, IndexBuffer, Texture
                ob.set_data(*args)
            elif cmd == 'SIZE':  # VertexBuffer, IndexBuffer,
                ob.set_size(*args)  # Texture[1D, 2D, 3D], RenderBuffer
            elif cmd == 'ATTACH':  # FrameBuffer
                ob.attach(*args)
            elif cmd == 'FRAMEBUFFER':  # FrameBuffer
                ob.set_framebuffer(*args)
            elif cmd == 'SHADERS':  # Program
                ob.set_shaders(*args)
            elif cmd == 'WRAPPING':  # Texture1D, Texture2D, Texture3D
                ob.set_wrapping(*args)
            elif cmd == 'INTERPOLATION':  # Texture1D, Texture2D, Texture3D
                ob.set_interpolation(*args)
            else:
                logger.warning('Invalid GLIR command %r' % cmd)

Response: Parses a single command.


Instruction:
Make a summary of the following Python 3 code
def parse(self, commands):

        # Get rid of dummy objects that represented deleted objects in
        # the last parsing round.
        to_delete = []
        for id_, val in self._objects.items():
            if val == JUST_DELETED:
                to_delete.append(id_)
        for id_ in to_delete:
            self._objects.pop(id_)

        for command in commands:
            self._parse(command)

Response: Parse a list of commands.


Instruction:
Can you generate the documentation for the following Python 3 function
def _gl_initialize(self):
        if '.es' in gl.current_backend.__name__:
            pass  # ES2: no action required
        else:
            # Desktop, enable sprites
            GL_VERTEX_PROGRAM_POINT_SIZE = 34370
            GL_POINT_SPRITE = 34913
            gl.glEnable(GL_VERTEX_PROGRAM_POINT_SIZE)
            gl.glEnable(GL_POINT_SPRITE)
        if self.capabilities['max_texture_size'] is None:  # only do once
            self.capabilities['gl_version'] = gl.glGetParameter(gl.GL_VERSION)
            self.capabilities['max_texture_size'] = \
                gl.glGetParameter(gl.GL_MAX_TEXTURE_SIZE)
            this_version = self.capabilities['gl_version'].split(' ')[0]
            this_version = LooseVersion(this_version)

Response:
Deal with compatibility ; desktop does not have sprites
            enabled by default. ES2 does not have sprites
            enabled by default.


Instruction:
Here you have a function in Python 3, explain what it does
def activate(self):
        if self._handle != self._parser.env.get('current_program', False):
            self._parser.env['current_program'] = self._handle
            gl.glUseProgram(self._handle)

Response: Activate the current program.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def deactivate(self):
        if self._parser.env.get('current_program', 0) != 0:
            self._parser.env['current_program'] = 0
            gl.glUseProgram(0)

Response: Deactivate the current program.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_active_attributes_and_uniforms(self):
        # This match a name of the form "name[size]" (= array)
        regex = re.compile("""(?P<name>\w+)\s*(\[(?P<size>\d+)\])\s*""")
        # Get how many active attributes and uniforms there are
        cu = gl.glGetProgramParameter(self._handle, gl.GL_ACTIVE_UNIFORMS)
        ca = gl.glGetProgramParameter(self.handle, gl.GL_ACTIVE_ATTRIBUTES)
        # Get info on each one
        attributes = []
        uniforms = []
        for container, count, func in [(attributes, ca, gl.glGetActiveAttrib),
                                       (uniforms, cu, gl.glGetActiveUniform)]:
            for i in range(count):
                name, size, gtype = func(self._handle, i)
                m = regex.match(name)  # Check if xxx[0] instead of xx
                if m:
                    name = m.group('name')
                    for i in range(size):
                        container.append(('%s[%d]' % (name, i), gtype))
                else:
                    container.append((name, gtype))
        #return attributes, uniforms
        return set([v[0] for v in attributes] + [v[0] for v in uniforms])

Response: Retrieve the active attributes and uniforms for this GLIR program.


Instruction:
Here you have a function in Python 3, explain what it does
def _parse_error(self, error):
        error = str(error)
        # Nvidia
        # 0(7): error C1008: undefined variable "MV"
        m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', error)
        if m:
            return int(m.group(2)), m.group(3)
        # ATI / Intel
        # ERROR: 0:131: '{' : syntax error parse error
        m = re.match(r'ERROR:\s(\d+):(\d+):\s(.*)', error)
        if m:
            return int(m.group(2)), m.group(3)
        # Nouveau
        # 0:28(16): error: syntax error, unexpected ')', expecting '('
        m = re.match(r'(\d+):(\d+)\((\d+)\):\s(.*)', error)
        if m:
            return int(m.group(2)), m.group(4)
        # Other ...
        return None, error

Response: Parses a single GLSL error and extracts the linenr and description of the object.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_error(self, code, errors, indentation=0):
        # Init
        results = []
        lines = None
        if code is not None:
            lines = [line.strip() for line in code.split('\n')]

        for error in errors.split('\n'):
            # Strip; skip empy lines
            error = error.strip()
            if not error:
                continue
            # Separate line number from description (if we can)
            linenr, error = self._parse_error(error)
            if None in (linenr, lines):
                results.append('%s' % error)
            else:
                results.append('on line %i: %s' % (linenr, error))
                if linenr > 0 and linenr < len(lines):
                    results.append('  %s' % lines[linenr - 1])

        # Add indentation and return
        results = [' ' * indentation + r for r in results]
        return '\n'.join(results)

Response:
Get error and show the faulty line + some context
        Other GLIR implementations may omit this.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_texture(self, name, value):
        if not self._linked:
            raise RuntimeError('Cannot set uniform when program has no code')
        # Get handle for the uniform, first try cache
        handle = self._handles.get(name, -1)
        if handle < 0:
            if name in self._known_invalid:
                return
            handle = gl.glGetUniformLocation(self._handle, name)
            self._unset_variables.discard(name)  # Mark as set
            self._handles[name] = handle  # Store in cache
            if handle < 0:
                self._known_invalid.add(name)
                logger.info('Variable %s is not an active uniform' % name)
                return
        # Program needs to be active in order to set uniforms
        self.activate()
        if True:
            # Sampler: the value is the id of the texture
            tex = self._parser.get_object(value)
            if tex == JUST_DELETED:
                return
            if tex is None:
                raise RuntimeError('Could not find texture with id %i' % value)
            unit = len(self._samplers)
            if name in self._samplers:
                unit = self._samplers[name][-1]  # Use existing unit
            self._samplers[name] = tex._target, tex.handle, unit
            gl.glUniform1i(handle, unit)

Response: Set a texture sampler. Value is the id of the texture to link.


Instruction:
Can you write a function in Python 3 where it
sets a uniform value.

Response:
def set_uniform(self, name, type_, value):
        """ Set a uniform value. Value is assumed to have been checked.
        """
        if not self._linked:
            raise RuntimeError('Cannot set uniform when program has no code')
        # Get handle for the uniform, first try cache
        handle = self._handles.get(name, -1)
        count = 1
        if handle < 0:
            if name in self._known_invalid:
                return
            handle = gl.glGetUniformLocation(self._handle, name)
            self._unset_variables.discard(name)  # Mark as set
            # if we set a uniform_array, mark all as set
            if not type_.startswith('mat'):
                count = value.nbytes // (4 * self.ATYPEINFO[type_][0])
            if count > 1:
                for ii in range(count):
                    if '%s[%s]' % (name, ii) in self._unset_variables:
                        self._unset_variables.discard('%s[%s]' % (name, ii))

            self._handles[name] = handle  # Store in cache
            if handle < 0:
                self._known_invalid.add(name)
                logger.info('Variable %s is not an active uniform' % name)
                return
        # Look up function to call
        funcname = self.UTYPEMAP[type_]
        func = getattr(gl, funcname)
        # Program needs to be active in order to set uniforms
        self.activate()
        # Triage depending on type
        if type_.startswith('mat'):
            # Value is matrix, these gl funcs have alternative signature
            transpose = False  # OpenGL ES 2.0 does not support transpose
            func(handle, 1, transpose, value)
        else:
            # Regular uniform
            func(handle, count, value)


Instruction:
Explain what the following Python 3 code does
def set_attribute(self, name, type_, value):
        if not self._linked:
            raise RuntimeError('Cannot set attribute when program has no code')
        # Get handle for the attribute, first try cache
        handle = self._handles.get(name, -1)
        if handle < 0:
            if name in self._known_invalid:
                return
            handle = gl.glGetAttribLocation(self._handle, name)
            self._unset_variables.discard(name)  # Mark as set
            self._handles[name] = handle  # Store in cache
            if handle < 0:
                self._known_invalid.add(name)
                if value[0] != 0 and value[2] > 0:  # VBO with offset
                    return  # Probably an unused element in a structured VBO
                logger.info('Variable %s is not an active attribute' % name)
                return
        # Program needs to be active in order to set uniforms
        self.activate()
        # Triage depending on VBO or tuple data
        if value[0] == 0:
            # Look up function call
            funcname = self.ATYPEMAP[type_]
            func = getattr(gl, funcname)
            # Set data
            self._attributes[name] = 0, handle, func, value[1:]
        else:
            # Get meta data
            vbo_id, stride, offset = value
            size, gtype, dtype = self.ATYPEINFO[type_]
            # Get associated VBO
            vbo = self._parser.get_object(vbo_id)
            if vbo == JUST_DELETED:
                return
            if vbo is None:
                raise RuntimeError('Could not find VBO with id %i' % vbo_id)
            # Set data
            func = gl.glVertexAttribPointer
            args = size, gtype, gl.GL_FALSE, stride, offset
            self._attributes[name] = vbo.handle, handle, func, args

Response: Set an attribute value.


Instruction:
Make a summary of the following Python 3 code
def draw(self, mode, selection):
        if not self._linked:
            raise RuntimeError('Cannot draw program if code has not been set')
        # Init
        gl.check_error('Check before draw')
        mode = as_enum(mode)
        # Draw
        if len(selection) == 3:
            # Selection based on indices
            id_, gtype, count = selection
            if count:
                self._pre_draw()
                ibuf = self._parser.get_object(id_)
                ibuf.activate()
                gl.glDrawElements(mode, count, as_enum(gtype), None)
                ibuf.deactivate()
        else:
            # Selection based on start and count
            first, count = selection
            if count:
                self._pre_draw()
                gl.glDrawArrays(mode, first, count)
        # Wrap up
        gl.check_error('Check after draw')
        self._post_draw()

Response: Draw program in given mode with given selection.


Instruction:
Can you tell what is the following Python 3 function doing
def as_matrix_transform(transform):
    if isinstance(transform, ChainTransform):
        matrix = np.identity(4)
        for tr in transform.transforms:
            # We need to do the matrix multiplication manually because VisPy
            # somehow doesn't mutliply matrices if there is a perspective
            # component. The equation below looks like it's the wrong way
            # around, but the VisPy matrices are transposed.
            matrix = np.matmul(as_matrix_transform(tr).matrix, matrix)
        return MatrixTransform(matrix)
    elif isinstance(transform, InverseTransform):
        matrix = as_matrix_transform(transform._inverse)
        return MatrixTransform(matrix.inv_matrix)
    elif isinstance(transform, NullTransform):
        return MatrixTransform()
    elif isinstance(transform, STTransform):
        return transform.as_matrix()
    elif isinstance(transform, MatrixTransform):
        return transform
    else:
        raise TypeError("Could not simplify transform of type {0}".format(type(transform)))

Response:
Simplify a transform to a single matrix transform which makes it a lot
    faster to compute transformations.


Instruction:
Write a Python 3 function that can
generate a list of nodes and line vertices for a single circle.

Response:
def circular(adjacency_mat, directed=False):
    """Places all nodes on a single circle.

    Parameters
    ----------
    adjacency_mat : matrix or sparse
        The graph adjacency matrix
    directed : bool
        Whether the graph is directed. If this is True, is will also
        generate the vertices for arrows, which can be passed to an
        ArrowVisual.

    Yields
    ------
    (node_vertices, line_vertices, arrow_vertices) : tuple
        Yields the node and line vertices in a tuple. This layout only yields a
        single time, and has no builtin animation
    """

    if issparse(adjacency_mat):
        adjacency_mat = adjacency_mat.tocoo()

    num_nodes = adjacency_mat.shape[0]

    t = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False, dtype=np.float32)

    # Visual coordinate system is between 0 and 1, so generate a circle with
    # radius 0.5 and center it at the point (0.5, 0.5).
    node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T

    line_vertices, arrows = _straight_line_vertices(adjacency_mat,
                                                    node_coords, directed)

    yield node_coords, line_vertices, arrows


Instruction:
Write a Python 3 script for
appending a new set of vertices to the current set of vertices.

Response:
def append(self, P, closed=False, itemsize=None, **kwargs):
        """
        Append a new set of vertices to the collection.

        For kwargs argument, n is the number of vertices (local) or the number
        of item (shared)

        Parameters
        ----------

        P : np.array
            Vertices positions of the path(s) to be added

        closed: bool
            Whether path(s) is/are closed

        itemsize: int or None
            Size of an individual path

        caps : list, array or 2-tuple
           Path start /end cap

        join : list, array or float
           path segment join

        color : list, array or 4-tuple
           Path color

        miter_limit : list, array or float
           Miter limit for join

        linewidth : list, array or float
           Path linewidth

        antialias : list, array or float
           Path antialias area
        """

        itemsize = itemsize or len(P)
        itemcount = len(P) / itemsize

        # Computes the adjacency information
        n, p = len(P), P.shape[-1]
        Z = np.tile(P, 2).reshape(2 * len(P), p)
        V = np.empty(n, dtype=self.vtype)

        V['p0'][1:-1] = Z[0::2][:-2]
        V['p1'][:-1] = Z[1::2][:-1]
        V['p2'][:-1] = Z[1::2][+1:]
        V['p3'][:-2] = Z[0::2][+2:]

        # Apply default values on vertices
        for name in self.vtype.names:
            if name not in ['collection_index', 'p0', 'p1', 'p2', 'p3']:
                V[name] = kwargs.get(name, self._defaults[name])

        # Extract relevant segments only
        V = (V.reshape(n / itemsize, itemsize)[:, :-1])
        if closed:
            V['p0'][:, 0] = V['p2'][:, -1]
            V['p3'][:, -1] = V['p1'][:, 0]
        else:
            V['p0'][:, 0] = V['p1'][:, 0]
            V['p3'][:, -1] = V['p2'][:, -1]
        V = V.ravel()

        # Quadruple each point (we're using 2 triangles / segment)
        # No shared vertices between segment because of joins
        V = np.repeat(V, 4, axis=0).reshape((len(V), 4))
        V['uv'] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        V = V.ravel()

        n = itemsize
        if closed:
            # uint16 for WebGL
            I = np.resize(
                np.array([0, 1, 2, 1, 2, 3], dtype=np.uint32), n * 2 * 3)
            I += np.repeat(4 * np.arange(n, dtype=np.uint32), 6)
            I[-6:] = 4 * n - 6, 4 * n - 5, 0, 4 * n - 5, 0, 1
        else:
            I = np.resize(
                np.array([0, 1, 2, 1, 2, 3], dtype=np.uint32), (n - 1) * 2 * 3)
            I += np.repeat(4 * np.arange(n - 1, dtype=np.uint32), 6)
        I = I.ravel()

        # Uniforms
        if self.utype:
            U = np.zeros(itemcount, dtype=self.utype)
            for name in self.utype.names:
                if name not in ["__unused__"]:
                    U[name] = kwargs.get(name, self._defaults[name])
        else:
            U = None

        Collection.append(self, vertices=V, uniforms=U,
                          indices=I, itemsize=itemsize * 4 - 4)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def draw(self, mode="triangles"):

        gl.glDepthMask(0)
        Collection.draw(self, mode)
        gl.glDepthMask(1)

Response: Draw the current context.


Instruction:
Explain what the following Python 3 code does
def set_data(self, pos=None, symbol='o', size=10., edge_width=1.,
                 edge_width_rel=None, edge_color='black', face_color='white',
                 scaling=False):
        """ Set the data used to display this visual.

        Parameters
        ----------
        pos : array
            The array of locations to display each symbol.
        symbol : str
            The style of symbol to draw (see Notes).
        size : float or array
            The symbol size in px.
        edge_width : float | None
            The width of the symbol outline in pixels.
        edge_width_rel : float | None
            The width as a fraction of marker size. Exactly one of
            `edge_width` and `edge_width_rel` must be supplied.
        edge_color : Color | ColorArray
            The color used to draw each symbol outline.
        face_color : Color | ColorArray
            The color used to draw each symbol interior.
        scaling : bool
            If set to True, marker scales when rezooming.

        Notes
        -----
        Allowed style strings are: disc, arrow, ring, clobber, square, diamond,
        vbar, hbar, cross, tailed_arrow, x, triangle_up, triangle_down,
        and star.
        """
        assert (isinstance(pos, np.ndarray) and
                pos.ndim == 2 and pos.shape[1] in (2, 3))
        if (edge_width is not None) + (edge_width_rel is not None) != 1:
            raise ValueError('exactly one of edge_width and edge_width_rel '
                             'must be non-None')
        if edge_width is not None:
            if edge_width < 0:
                raise ValueError('edge_width cannot be negative')
        else:
            if edge_width_rel < 0:
                raise ValueError('edge_width_rel cannot be negative')
        self.symbol = symbol
        self.scaling = scaling

        edge_color = ColorArray(edge_color).rgba
        if len(edge_color) == 1:
            edge_color = edge_color[0]

        face_color = ColorArray(face_color).rgba
        if len(face_color) == 1:
            face_color = face_color[0]

        n = len(pos)
        data = np.zeros(n, dtype=[('a_position', np.float32, 3),
                                  ('a_fg_color', np.float32, 4),
                                  ('a_bg_color', np.float32, 4),
                                  ('a_size', np.float32, 1),
                                  ('a_edgewidth', np.float32, 1)])
        data['a_fg_color'] = edge_color
        data['a_bg_color'] = face_color
        if edge_width is not None:
            data['a_edgewidth'] = edge_width
        else:
            data['a_edgewidth'] = size*edge_width_rel
        data['a_position'][:, :pos.shape[1]] = pos
        data['a_size'] = size
        self.shared_program['u_antialias'] = self.antialias  # XXX make prop
        self._data = data
        self._vbo.set_data(data)
        self.shared_program.bind(self._vbo)
        self.update()

Response: Set the data used to display the symbol in the current page.


Instruction:
How would you explain what the following Python 3 function does
def hook_changed(self, hook_name, widget, new_data):
        if hook_name == 'song':
            self.song_changed(widget, new_data)
        elif hook_name == 'state':
            self.state_changed(widget, new_data)
        elif hook_name == 'elapsed_and_total':
            elapsed, total = new_data
            self.time_changed(widget, elapsed, total)

Response: Handle a hook upate.


Instruction:
Can you create a Python 3 function that
updates the signature of func with the data in self

Response:
def update(self, func, **kw):
        "Update the signature of func with the data in self"
        func.__name__ = self.name
        func.__doc__ = getattr(self, 'doc', None)
        func.__dict__ = getattr(self, 'dict', {})
        func.__defaults__ = getattr(self, 'defaults', ())
        func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
        func.__annotations__ = getattr(self, 'annotations', None)
        callermodule = sys._getframe(3).f_globals.get('__name__', '?')
        func.__module__ = getattr(self, 'module', callermodule)
        func.__dict__.update(kw)


Instruction:
How would you code a function in Python 3 to
make a new function from a given template and update the signature

Response:
def make(self, src_templ, evaldict=None, addsource=False, **attrs):
        "Make a new function from a given template and update the signature"
        src = src_templ % vars(self) # expand name and signature
        evaldict = evaldict or {}
        mo = DEF.match(src)
        if mo is None:
            raise SyntaxError('not a valid function template\n%s' % src)
        name = mo.group(1) # extract the function name
        names = set([name] + [arg.strip(' *') for arg in
                             self.shortsignature.split(',')])
        for n in names:
            if n in ('_func_', '_call_'):
                raise NameError('%s is overridden in\n%s' % (n, src))
        if not src.endswith('\n'): # add a newline just for safety
            src += '\n' # this is needed in old versions of Python
        try:
            code = compile(src, '<string>', 'single')
            # print >> sys.stderr, 'Compiling %s' % src
            exec(code, evaldict)
        except:
            print('Error in generated code:', file=sys.stderr)
            print(src, file=sys.stderr)
            raise
        func = evaldict[name]
        if addsource:
            attrs['__source__'] = src
        self.update(func, **attrs)
        return func


Instruction:
How would you code a function in Python 3 to
create a function from the strings name signature and body.

Response:
def create(cls, obj, body, evaldict, defaults=None,
               doc=None, module=None, addsource=True, **attrs):
        """
        Create a function from the strings name, signature and body.
        evaldict is the evaluation dictionary. If addsource is true an attribute
        __source__ is added to the result. The attributes attrs are added,
        if any.
        """
        if isinstance(obj, str): # "name(signature)"
            name, rest = obj.strip().split('(', 1)
            signature = rest[:-1] #strip a right parens
            func = None
        else: # a function
            name = None
            signature = None
            func = obj
        self = cls(func, name, signature, defaults, doc, module)
        ibody = '\n'.join('    ' + line for line in body.splitlines())
        return self.make('def %(name)s(%(signature)s):\n' + ibody,
                        evaldict, addsource, **attrs)


Instruction:
Create a Python 3 function for
setting the scalar array data

Response:
def set_data(self, data=None, vertex_colors=None, face_colors=None,
                 color=None):
        """ Set the scalar array data

        Parameters
        ----------
        data : ndarray
            A 3D array of scalar values. The isosurface is constructed to show
            all locations in the scalar field equal to ``self.level``.
        vertex_colors : array-like | None
            Colors to use for each vertex.
        face_colors : array-like | None
            Colors to use for each face.
        color : instance of Color
            The color to use.
        """
        # We only change the internal variables if they are provided
        if data is not None:
            self._data = data
            self._recompute = True
        if vertex_colors is not None:
            self._vertex_colors = vertex_colors
            self._update_meshvisual = True
        if face_colors is not None:
            self._face_colors = face_colors
            self._update_meshvisual = True
        if color is not None:
            self._color = Color(color)
            self._update_meshvisual = True
        self.update()


Instruction:
How would you explain what the following Python 3 function does
def get_scene_bounds(self, dim=None):
        # todo: handle sub-children
        # todo: handle transformations
        # Init
        bounds = [(np.inf, -np.inf), (np.inf, -np.inf), (np.inf, -np.inf)]
        # Get bounds of all children
        for ob in self.scene.children:
            if hasattr(ob, 'bounds'):
                for axis in (0, 1, 2):
                    if (dim is not None) and dim != axis:
                        continue
                    b = ob.bounds(axis)
                    if b is not None:
                        b = min(b), max(b)  # Ensure correct order
                        bounds[axis] = (min(bounds[axis][0], b[0]),
                                        max(bounds[axis][1], b[1]))
        # Set defaults
        for axis in (0, 1, 2):
            if any(np.isinf(bounds[axis])):
                bounds[axis] = -1, 1

        if dim is not None:
            return bounds[dim]
        else:
            return bounds

Response: Get the total bounds based on the visuals present in the scene.


Instruction:
Write a Python 3 script to
convert user string or hex color to rgb array

Response:
def _string_to_rgb(color):
    """Convert user string or hex color to color array (length 3 or 4)"""
    if not color.startswith('#'):
        if color.lower() not in _color_dict:
            raise ValueError('Color "%s" unknown' % color)
        color = _color_dict[color]
        assert color[0] == '#'
    # hex color
    color = color[1:]
    lc = len(color)
    if lc in (3, 4):
        color = ''.join(c + c for c in color)
        lc = len(color)
    if lc not in (6, 8):
        raise ValueError('Hex color must have exactly six or eight '
                         'elements following the # sign')
    color = np.array([int(color[i:i+2], 16) / 255. for i in range(0, lc, 2)])
    return color


Instruction:
Can you implement a function in Python 3 that
converts color from any set of fmts str hex or arr to RGB array

Response:
def _user_to_rgba(color, expand=True, clip=False):
    """Convert color(s) from any set of fmts (str/hex/arr) to RGB(A) array"""
    if color is None:
        color = np.zeros(4, np.float32)
    if isinstance(color, string_types):
        color = _string_to_rgb(color)
    elif isinstance(color, ColorArray):
        color = color.rgba
    # We have to treat this specially
    elif isinstance(color, (list, tuple)):
        if any(isinstance(c, string_types) for c in color):
            color = [_user_to_rgba(c, expand=expand, clip=clip) for c in color]
            if any(len(c) > 1 for c in color):
                raise RuntimeError('could not parse colors, are they nested?')
            color = [c[0] for c in color]
    color = np.atleast_2d(color).astype(np.float32)
    if color.shape[1] not in (3, 4):
        raise ValueError('color must have three or four elements')
    if expand and color.shape[1] == 3:  # only expand if requested
        color = np.concatenate((color, np.ones((color.shape[0], 1))),
                               axis=1)
    if color.min() < 0 or color.max() > 1:
        if clip:
            color = np.clip(color, 0, 1)
        else:
            raise ValueError("Color values must be between 0 and 1 (or use "
                             "clip=True to automatically clip the values).")
    return color


Instruction:
Can you generate the documentation for the following Python 3 function
def _array_clip_val(val):
    val = np.array(val)
    if val.max() > 1 or val.min() < 0:
        logger.warning('value will be clipped between 0 and 1')
    val[...] = np.clip(val, 0, 1)
    return val

Response: Helper to turn val into array and clip between 0 and 1


Instruction:
Implement a Python 3 function for
extending a ColorArray with new colors.

Response:
def extend(self, colors):
        """Extend a ColorArray with new colors

        Parameters
        ----------
        colors : instance of ColorArray
            The new colors.
        """
        colors = ColorArray(colors)
        self._rgba = np.vstack((self._rgba, colors._rgba))
        return self


Instruction:
How would you code a function in Python 3 to
set the color using an Nx4 array of RGBA floats

Response:
def rgba(self, val):
        """Set the color using an Nx4 array of RGBA floats"""
        # Note: all other attribute sets get routed here!
        # This method is meant to do the heavy lifting of setting data
        rgba = _user_to_rgba(val, expand=False)
        if self._rgba is None:
            self._rgba = rgba  # only on init
        else:
            self._rgba[:, :rgba.shape[1]] = rgba


Instruction:
Implement a Python 3 function for
setting the color using an Nx4 array of RGBA uint8 values

Response:
def RGBA(self, val):
        """Set the color using an Nx4 array of RGBA uint8 values"""
        # need to convert to normalized float
        val = np.atleast_1d(val).astype(np.float32) / 255
        self.rgba = val


Instruction:
Create a Python 3 function to
set the color using an Nx3 array of RGB uint8 values

Response:
def RGB(self, val):
        """Set the color using an Nx3 array of RGB uint8 values"""
        # need to convert to normalized float
        val = np.atleast_1d(val).astype(np.float32) / 255.
        self.rgba = val


Instruction:
Explain what the following Python 3 code does
def value(self, val):
        hsv = self._hsv
        hsv[:, 2] = _array_clip_val(val)
        self.rgba = _hsv_to_rgb(hsv)

Response: Set the color using length - N array of values.


Instruction:
Can you generate the documentation for the following Python 3 function
def lighter(self, dv=0.1, copy=True):
        color = self.copy() if copy else self
        color.value += dv
        return color

Response: Produce a lighter color.


Instruction:
Can you write a function in Python 3 where it
produces a darker color.

Response:
def darker(self, dv=0.1, copy=True):
        """Produce a darker color (if possible)

        Parameters
        ----------
        dv : float
            Amount to decrease the color value by.
        copy : bool
            If False, operation will be carried out in-place.

        Returns
        -------
        color : instance of ColorArray
            The darkened Color.
        """
        color = self.copy() if copy else self
        color.value -= dv
        return color


Instruction:
Here you have a function in Python 3, explain what it does
def _set_range(self, init):

        if init and (self._scale_factor is not None):
            return  # We don't have to set our scale factor

        # Get window size (and store factor now to sync with resizing)
        w, h = self._viewbox.size
        w, h = float(w), float(h)

        # Get range and translation for x and y
        x1, y1, z1 = self._xlim[0], self._ylim[0], self._zlim[0]
        x2, y2, z2 = self._xlim[1], self._ylim[1], self._zlim[1]
        rx, ry, rz = (x2 - x1), (y2 - y1), (z2 - z1)

        # Correct ranges for window size. Note that the window width
        # influences the x and y data range, while the height influences
        # the z data range.
        if w / h > 1:
            rx /= w / h
            ry /= w / h
        else:
            rz /= h / w

        # Convert to screen coordinates. In screen x, only x and y have effect.
        # In screen y, all three dimensions have effect. The idea of the lines
        # below is to calculate the range on screen when that will fit the
        # data under any rotation.
        rxs = (rx**2 + ry**2)**0.5
        rys = (rx**2 + ry**2 + rz**2)**0.5

        self.scale_factor = max(rxs, rys) * 1.04

Response: Reset the camera view using the known limits.


Instruction:
Write a Python 3 function for
handling a mouse event and updates the internal state of the object.

Response:
def viewbox_mouse_event(self, event):
        """
        The viewbox received a mouse event; update transform
        accordingly.

        Parameters
        ----------
        event : instance of Event
            The event.
        """
        if event.handled or not self.interactive:
            return

        PerspectiveCamera.viewbox_mouse_event(self, event)

        if event.type == 'mouse_release':
            self._event_value = None  # Reset
        elif event.type == 'mouse_press':
            event.handled = True
        elif event.type == 'mouse_move':
            if event.press_event is None:
                return

            modifiers = event.mouse_event.modifiers
            p1 = event.mouse_event.press_event.pos
            p2 = event.mouse_event.pos
            d = p2 - p1

            if 1 in event.buttons and not modifiers:
                # Rotate
                self._update_rotation(event)

            elif 2 in event.buttons and not modifiers:
                # Zoom
                if self._event_value is None:
                    self._event_value = (self._scale_factor, self._distance)
                zoomy = (1 + self.zoom_factor) ** d[1]

                self.scale_factor = self._event_value[0] * zoomy
                # Modify distance if its given
                if self._distance is not None:
                    self._distance = self._event_value[1] * zoomy
                self.view_changed()

            elif 1 in event.buttons and keys.SHIFT in modifiers:
                # Translate
                norm = np.mean(self._viewbox.size)
                if self._event_value is None or len(self._event_value) == 2:
                    self._event_value = self.center
                dist = (p1 - p2) / norm * self._scale_factor
                dist[1] *= -1
                # Black magic part 1: turn 2D into 3D translations
                dx, dy, dz = self._dist_to_trans(dist)
                # Black magic part 2: take up-vector and flipping into account
                ff = self._flip_factors
                up, forward, right = self._get_dim_vectors()
                dx, dy, dz = right * dx + forward * dy + up * dz
                dx, dy, dz = ff[0] * dx, ff[1] * dy, dz * ff[2]
                c = self._event_value
                self.center = c[0] + dx, c[1] + dy, c[2] + dz

            elif 2 in event.buttons and keys.SHIFT in modifiers:
                # Change fov
                if self._event_value is None:
                    self._event_value = self._fov
                fov = self._event_value - d[1] / 5.0
                self.fov = min(180.0, max(0.0, fov))


Instruction:
Here you have a function in Python 3, explain what it does
def _update_camera_pos(self):

        # transform will be updated several times; do not update camera
        # transform until we are done.
        ch_em = self.events.transform_change
        with ch_em.blocker(self._update_transform):
            tr = self.transform
            tr.reset()

            up, forward, right = self._get_dim_vectors()

            # Create mapping so correct dim is up
            pp1 = np.array([(0, 0, 0), (0, 0, -1), (1, 0, 0), (0, 1, 0)])
            pp2 = np.array([(0, 0, 0), forward, right, up])
            tr.set_mapping(pp1, pp2)

            tr.translate(-self._actual_distance * forward)
            self._rotate_tr()
            tr.scale([1.0/a for a in self._flip_factors])
            tr.translate(np.array(self.center))

Response: Update the camera position and orientation


Instruction:
Write a Python 3 script for
determining if the user requested interactive mode.

Response:
def is_interactive(self):
        """ Determine if the user requested interactive mode.
        """
        # The Python interpreter sets sys.flags correctly, so use them!
        if sys.flags.interactive:
            return True

        # IPython does not set sys.flags when -i is specified, so first
        # check it if it is already imported.
        if '__IPYTHON__' not in dir(six.moves.builtins):
            return False

        # Then we check the application singleton and determine based on
        # a variable it sets.
        try:
            from IPython.config.application import Application as App
            return App.initialized() and App.instance().interact
        except (ImportError, AttributeError):
            return False


Instruction:
Here you have a function in Python 3, explain what it does
def run(self, allow_interactive=True):

        if allow_interactive and self.is_interactive():
            inputhook.set_interactive(enabled=True, app=self)
        else:
            return self._backend._vispy_run()

Response: Enter the native GUI event loop.


Instruction:
Write a Python 3 script to
select a backend by name. See class docstring for details.

Response:
def _use(self, backend_name=None):
        """Select a backend by name. See class docstring for details.
        """
        # See if we're in a specific testing mode, if so DONT check to see
        # if it's a valid backend. If it isn't, it's a good thing we
        # get an error later because we should have decorated our test
        # with requires_application()
        test_name = os.getenv('_VISPY_TESTING_APP', None)

        # Check whether the given name is valid
        if backend_name is not None:
            if backend_name.lower() == 'default':
                backend_name = None  # Explicitly use default, avoid using test
            elif backend_name.lower() not in BACKENDMAP:
                raise ValueError('backend_name must be one of %s or None, not '
                                 '%r' % (BACKEND_NAMES, backend_name))
        elif test_name is not None:
            backend_name = test_name.lower()
            assert backend_name in BACKENDMAP

        # Should we try and load any backend, or just this specific one?
        try_others = backend_name is None

        # Get backends to try ...
        imported_toolkits = []  # Backends for which the native lib is imported
        backends_to_try = []
        if not try_others:
            # We should never hit this, since we check above
            assert backend_name.lower() in BACKENDMAP.keys()
            # Add it
            backends_to_try.append(backend_name.lower())
        else:
            # See if a backend is loaded
            for name, module_name, native_module_name in CORE_BACKENDS:
                if native_module_name and native_module_name in sys.modules:
                    imported_toolkits.append(name.lower())
                    backends_to_try.append(name.lower())
            # See if a default is given
            default_backend = config['default_backend'].lower()
            if default_backend.lower() in BACKENDMAP.keys():
                if default_backend not in backends_to_try:
                    backends_to_try.append(default_backend)
            # After this, try each one
            for name, module_name, native_module_name in CORE_BACKENDS:
                name = name.lower()
                if name not in backends_to_try:
                    backends_to_try.append(name)

        # Now try each one
        for key in backends_to_try:
            name, module_name, native_module_name = BACKENDMAP[key]
            TRIED_BACKENDS.append(name)
            mod_name = 'backends.' + module_name
            __import__(mod_name, globals(), level=1)
            mod = getattr(backends, module_name)
            if not mod.available:
                msg = ('Could not import backend "%s":\n%s'
                       % (name, str(mod.why_not)))
                if not try_others:
                    # Fail if user wanted to use a specific backend
                    raise RuntimeError(msg)
                elif key in imported_toolkits:
                    # Warn if were unable to use an already imported toolkit
                    msg = ('Although %s is already imported, the %s backend '
                           'could not\nbe used ("%s"). \nNote that running '
                           'multiple GUI toolkits simultaneously can cause '
                           'side effects.' %
                           (native_module_name, name, str(mod.why_not)))
                    logger.warning(msg)
                else:
                    # Inform otherwise
                    logger.info(msg)
            else:
                # Success!
                self._backend_module = mod
                logger.debug('Selected backend %s' % module_name)
                break
        else:
            raise RuntimeError('Could not import any of the backends. '
                               'You need to install any of %s. We recommend '
                               'PyQt' % [b[0] for b in CORE_BACKENDS])

        # Store classes for app backend and canvas backend
        self._backend = self.backend_module.ApplicationBackend()


Instruction:
Explain what the following Python 3 code does
def _process_key(evt):
    key = evt.GetKeyCode()
    if key in KEYMAP:
        return KEYMAP[key], ''
    if 97 <= key <= 122:
        key -= 32
    if key >= 32 and key <= 127:
        return keys.Key(chr(key)), chr(key)
    else:
        return None, None

Response: Helper function to convert wx keycode to vispy keycode


Instruction:
Write a Python 3 script to
check if a node is a child of the current node.

Response:
def is_child(self, node):
        """Check if a node is a child of the current node

        Parameters
        ----------
        node : instance of Node
            The potential child.

        Returns
        -------
        child : bool
            Whether or not the node is a child.
        """
        if node in self.children:
            return True
        for c in self.children:
            if c.is_child(node):
                return True
        return False


Instruction:
Can you generate the documentation for the following Python 3 function
def scene_node(self):
        if self._scene_node is None:
            from .subscene import SubScene
            p = self.parent
            while True:
                if isinstance(p, SubScene) or p is None:
                    self._scene_node = p
                    break
                p = p.parent
            if self._scene_node is None:
                self._scene_node = self
        return self._scene_node

Response:
The first ancestor of this node that is a SubScene instance or self
       .


Instruction:
Write a Python 3 function that can
update the node s properties.

Response:
def update(self):
        """
        Emit an event to inform listeners that properties of this Node have
        changed. Also request a canvas update.
        """
        self.events.update()
        c = getattr(self, 'canvas', None)
        if c is not None:
            c.update(node=self)


Instruction:
Here you have a function in Python 3, explain what it does
def set_transform(self, type_, *args, **kwargs):
        self.transform = create_transform(type_, *args, **kwargs)

Response: Create a new transform of type_ and assign it to this node.


Instruction:
Explain what the following Python 3 code does
def _update_trsys(self, event):
        for ch in self.children:
            ch._update_trsys(event)
        self.events.transform_change()
        self.update()

Response: Called when the transform system has changed.


Instruction:
Can you write a function in Python 3 where it
returns the list of parents starting from this node.

Response:
def parent_chain(self):
        """
        Return the list of parents starting from this node. The chain ends
        at the first node with no parents.
        """
        chain = [self]
        while True:
            try:
                parent = chain[-1].parent
            except Exception:
                break
            if parent is None:
                break
            chain.append(parent)
        return chain


Instruction:
Here you have a function in Python 3, explain what it does
def _describe_tree(self, prefix, with_transform):
        extra = ': "%s"' % self.name if self.name is not None else ''
        if with_transform:
            extra += (' [%s]' % self.transform.__class__.__name__)
        output = ''
        if len(prefix) > 0:
            output += prefix[:-3]
            output += '  +--'
        output += '%s%s\n' % (self.__class__.__name__, extra)

        n_children = len(self.children)
        for ii, child in enumerate(self.children):
            sub_prefix = prefix + ('   ' if ii+1 == n_children else '  |')
            output += child._describe_tree(sub_prefix, with_transform)
        return output

Response: Helper function to actuall construct the tree


Instruction:
Write a Python 3 script to
return the common parent of two entities.

Response:
def common_parent(self, node):
        """
        Return the common parent of two entities

        If the entities have no common parent, return None.

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        parent : instance of Node | None
            The parent.
        """
        p1 = self.parent_chain()
        p2 = node.parent_chain()
        for p in p1:
            if p in p2:
                return p
        return None


Instruction:
Given the following Python 3 function, write the documentation
def node_path_to_child(self, node):
        if node is self:
            return []

        # Go up from the child node as far as we can
        path1 = [node]
        child = node
        while child.parent is not None:
            child = child.parent
            path1.append(child)
            # Early exit
            if child is self:
                return list(reversed(path1))

        # Verify that we're not cut off
        if path1[-1].parent is None:
            raise RuntimeError('%r is not a child of %r' % (node, self))

        def _is_child(path, parent, child):
            path.append(parent)
            if child in parent.children:
                return path
            else:
                for c in parent.children:
                    possible_path = _is_child(path[:], c, child)
                    if possible_path:
                        return possible_path
            return None

        # Search from the parent towards the child
        path2 = _is_child([], self, path1[-1])
        if not path2:
            raise RuntimeError('%r is not a child of %r' % (node, self))

        # Return
        return path2 + list(reversed(path1))

Response: Return a list describing the path from this node to a child node.


Instruction:
Create a Python 3 function to
return two lists describing the path from this node to another node.

Response:
def node_path(self, node):
        """Return two lists describing the path from this node to another

        Parameters
        ----------
        node : instance of Node
            The other node.

        Returns
        -------
        p1 : list
            First path (see below).
        p2 : list
            Second path (see below).

        Notes
        -----
        The first list starts with this node and ends with the common parent
        between the endpoint nodes. The second list contains the remainder of
        the path from the common parent to the specified ending node.

        For example, consider the following scenegraph::

            A --- B --- C --- D
                   \
                    --- E --- F

        Calling `D.node_path(F)` will return::

            ([D, C, B], [E, F])

        """
        p1 = self.parent_chain()
        p2 = node.parent_chain()
        cp = None
        for p in p1:
            if p in p2:
                cp = p
                break
        if cp is None:
            raise RuntimeError("No single-path common parent between nodes %s "
                               "and %s." % (self, node))

        p1 = p1[:p1.index(cp)+1]
        p2 = p2[:p2.index(cp)][::-1]
        return p1, p2


Instruction:
Can you generate the documentation for the following Python 3 function
def node_path_transforms(self, node):
        a, b = self.node_path(node)
        return ([n.transform for n in a[:-1]] +
                [n.transform.inverse for n in b])[::-1]

Response: Returns the list of transforms along the path to another node.


Instruction:
Explain what the following Python 3 code does
def read(cls, fname):
        # Open file
        fmt = op.splitext(fname)[1].lower()
        assert fmt in ('.obj', '.gz')
        opener = open if fmt == '.obj' else gzip_open
        with opener(fname, 'rb') as f:
            try:
                reader = WavefrontReader(f)
                while True:
                    reader.readLine()
            except EOFError:
                pass

        # Done
        t0 = time.time()
        mesh = reader.finish()
        logger.debug('reading mesh took ' +
                     str(time.time() - t0) +
                     ' seconds')
        return mesh

Response: This classmethod is used to read the OBJ file. It is the entry point for reading the OBJ files.


Instruction:
How would you explain what the following Python 3 function does
def readLine(self):

        # Read line
        line = self._f.readline().decode('ascii', 'ignore')
        if not line:
            raise EOFError()
        line = line.strip()

        if line.startswith('v '):
            # self._vertices.append( *self.readTuple(line) )
            self._v.append(self.readTuple(line))
        elif line.startswith('vt '):
            self._vt.append(self.readTuple(line, 3))
        elif line.startswith('vn '):
            self._vn.append(self.readTuple(line))
        elif line.startswith('f '):
            self._faces.append(self.readFace(line))
        elif line.startswith('#'):
            pass  # Comment
        elif line.startswith('mtllib '):
            logger.warning('Notice reading .OBJ: material properties are '
                           'ignored.')
        elif any(line.startswith(x) for x in ('g ', 's ', 'o ', 'usemtl ')):
            pass  # Ignore groups and smoothing groups, obj names, material
        elif not line.strip():
            pass
        else:
            logger.warning('Notice reading .OBJ: ignoring %s command.'
                           % line.strip())

Response: Reads a single line and processes it.


Instruction:
Can you generate the documentation for the following Python 3 function
def readTuple(self, line, n=3):
        numbers = [num for num in line.split(' ') if num]
        return [float(num) for num in numbers[1:n + 1]]

Response: Reads a tuple of numbers. e. g. vertices normals or teture coords.


Instruction:
Can you generate the documentation for the following Python 3 function
def readFace(self, line):

        # Get parts (skip first)
        indexSets = [num for num in line.split(' ') if num][1:]

        final_face = []
        for indexSet in indexSets:

            # Did we see this exact index earlier? If so, it's easy
            final_index = self._facemap.get(indexSet)
            if final_index is not None:
                final_face.append(final_index)
                continue

            # If not, we need to sync the vertices/normals/texcords ...

            # Get and store final index
            final_index = len(self._vertices)
            final_face.append(final_index)
            self._facemap[indexSet] = final_index

            # What indices were given?
            indices = [i for i in indexSet.split('/')]

            # Store new set of vertex/normal/texcords.
            # If there is a single face that does not specify the texcord
            # index, the texcords are ignored. Likewise for the normals.
            if True:
                vertex_index = self._absint(indices[0], len(self._v))
                self._vertices.append(self._v[vertex_index])
            if self._texcords is not None:
                if len(indices) > 1 and indices[1]:
                    texcord_index = self._absint(indices[1], len(self._vt))
                    self._texcords.append(self._vt[texcord_index])
                else:
                    if self._texcords:
                        logger.warning('Ignoring texture coordinates because '
                                       'it is not specified for all faces.')
                    self._texcords = None
            if self._normals is not None:
                if len(indices) > 2 and indices[2]:
                    normal_index = self._absint(indices[2], len(self._vn))
                    self._normals.append(self._vn[normal_index])
                else:
                    if self._normals:
                        logger.warning('Ignoring normals because it is not '
                                       'specified for all faces.')
                    self._normals = None

        # Check face
        if self._faces and len(self._faces[0]) != len(final_face):
            raise RuntimeError(
                'Vispy requires that all faces are either triangles or quads.')

        # Done
        return final_face

Response: Reads a single face from a string.


Instruction:
Make a summary of the following Python 3 code
def finish(self):
        self._vertices = np.array(self._vertices, 'float32')
        if self._faces:
            self._faces = np.array(self._faces, 'uint32')
        else:
            # Use vertices only
            self._vertices = np.array(self._v, 'float32')
            self._faces = None
        if self._normals:
            self._normals = np.array(self._normals, 'float32')
        else:
            self._normals = self._calculate_normals()
        if self._texcords:
            self._texcords = np.array(self._texcords, 'float32')
        else:
            self._texcords = None

        return self._vertices, self._faces, self._normals, self._texcords

Response:
Converts gathere lists to numpy arrays and creates
            BaseMesh instance.


Instruction:
Here you have a function in Python 3, explain what it does
def write(cls, fname, vertices, faces, normals,
              texcoords, name='', reshape_faces=True):
        """ This classmethod is the entry point for writing mesh data to OBJ.

        Parameters
        ----------
        fname : string
            The filename to write to. Must end with ".obj" or ".gz".
        vertices : numpy array
            The vertex data
        faces : numpy array
            The face data
        texcoords : numpy array
            The texture coordinate per vertex
        name : str
            The name of the object (e.g. 'teapot')
        reshape_faces : bool
            Reshape the `faces` array to (Nf, 3). Set to `False`
            if you need to write a mesh with non triangular faces.
        """
        # Open file
        fmt = op.splitext(fname)[1].lower()
        if fmt not in ('.obj', '.gz'):
            raise ValueError('Filename must end with .obj or .gz, not "%s"'
                             % (fmt,))
        opener = open if fmt == '.obj' else gzip_open
        f = opener(fname, 'wb')
        try:
            writer = WavefrontWriter(f)
            writer.writeMesh(vertices, faces, normals,
                             texcoords, name, reshape_faces=reshape_faces)
        except EOFError:
            pass
        finally:
            f.close()

Response: This classmethod writes a mesh to an object file.


Instruction:
Write a Python 3 script for
writing a tuple of numbers on one line.

Response:
def writeTuple(self, val, what):
        """ Writes a tuple of numbers (on one line).
        """
        # Limit to three values. so RGBA data drops the alpha channel
        # Format can handle up to 3 texcords
        val = val[:3]
        # Make string
        val = ' '.join([str(v) for v in val])
        # Write line
        self.writeLine('%s %s' % (what, val))


Instruction:
How would you code a function in Python 3 to
write the face info to the net line.

Response:
def writeFace(self, val, what='f'):
        """ Write the face info to the net line.
        """
        # OBJ counts from 1
        val = [v + 1 for v in val]
        # Make string
        if self._hasValues and self._hasNormals:
            val = ' '.join(['%i/%i/%i' % (v, v, v) for v in val])
        elif self._hasNormals:
            val = ' '.join(['%i//%i' % (v, v) for v in val])
        elif self._hasValues:
            val = ' '.join(['%i/%i' % (v, v) for v in val])
        else:
            val = ' '.join(['%i' % v for v in val])
        # Write line
        self.writeLine('%s %s' % (what, val))


Instruction:
Explain what the following Python 3 code does
def writeMesh(self, vertices, faces, normals, values,
                  name='', reshape_faces=True):
        """ Write the given mesh instance.
        """

        # Store properties
        self._hasNormals = normals is not None
        self._hasValues = values is not None
        self._hasFaces = faces is not None

        # Get faces and number of vertices
        if faces is None:
            faces = np.arange(len(vertices))
            reshape_faces = True

        if reshape_faces:
            Nfaces = faces.size // 3
            faces = faces.reshape((Nfaces, 3))
        else:
            is_triangular = np.array([len(f) == 3
                                      for f in faces])
            if not(np.all(is_triangular)):
                logger.warning('''Faces doesn't appear to be triangular,
                be advised the file cannot be read back in vispy''')
        # Number of vertices
        N = vertices.shape[0]

        # Get string with stats
        stats = []
        stats.append('%i vertices' % N)
        if self._hasValues:
            stats.append('%i texcords' % N)
        else:
            stats.append('no texcords')
        if self._hasNormals:
            stats.append('%i normals' % N)
        else:
            stats.append('no normals')
        stats.append('%i faces' % faces.shape[0])

        # Write header
        self.writeLine('# Wavefront OBJ file')
        self.writeLine('# Created by vispy.')
        self.writeLine('#')
        if name:
            self.writeLine('# object %s' % name)
        else:
            self.writeLine('# unnamed object')
        self.writeLine('# %s' % ', '.join(stats))
        self.writeLine('')

        # Write data
        if True:
            for i in range(N):
                self.writeTuple(vertices[i], 'v')
        if self._hasNormals:
            for i in range(N):
                self.writeTuple(normals[i], 'vn')
        if self._hasValues:
            for i in range(N):
                self.writeTuple(values[i], 'vt')
        if True:
            for i in range(faces.shape[0]):
                self.writeFace(faces[i])

Response: Writes a mesh to the file.


Instruction:
Write a Python 3 script to
compute cross product between 2D arrays x and y.

Response:
def _fast_cross_3d(x, y):
    """Compute cross product between list of 3D vectors

    Much faster than np.cross() when the number of cross products
    becomes large (>500). This is because np.cross() methods become
    less memory efficient at this stage.

    Parameters
    ----------
    x : array
        Input array 1.
    y : array
        Input array 2.

    Returns
    -------
    z : array
        Cross product of x and y.

    Notes
    -----
    x and y must both be 2D row vectors. One must have length 1, or both
    lengths must match.
    """
    assert x.ndim == 2
    assert y.ndim == 2
    assert x.shape[1] == 3
    assert y.shape[1] == 3
    assert (x.shape[0] == 1 or y.shape[0] == 1) or x.shape[0] == y.shape[0]
    if max([x.shape[0], y.shape[0]]) >= 500:
        return np.c_[x[:, 1] * y[:, 2] - x[:, 2] * y[:, 1],
                     x[:, 2] * y[:, 0] - x[:, 0] * y[:, 2],
                     x[:, 0] * y[:, 1] - x[:, 1] * y[:, 0]]
    else:
        return np.cross(x, y)


Instruction:
Can you generate the documentation for the following Python 3 function
def resize(image, shape, kind='linear'):
    image = np.array(image, float)
    shape = np.array(shape, int)
    if shape.ndim != 1 or shape.size != 2:
        raise ValueError('shape must have two elements')
    if image.ndim < 2:
        raise ValueError('image must have two dimensions')
    if not isinstance(kind, string_types) or kind not in ('nearest', 'linear'):
        raise ValueError('mode must be "nearest" or "linear"')

    r = np.linspace(0, image.shape[0] - 1, shape[0])
    c = np.linspace(0, image.shape[1] - 1, shape[1])
    if kind == 'linear':
        r_0 = np.floor(r).astype(int)
        c_0 = np.floor(c).astype(int)
        r_1 = r_0 + 1
        c_1 = c_0 + 1

        top = (r_1 - r)[:, np.newaxis]
        bot = (r - r_0)[:, np.newaxis]
        lef = (c - c_0)[np.newaxis, :]
        rig = (c_1 - c)[np.newaxis, :]

        c_1 = np.minimum(c_1, image.shape[1] - 1)
        r_1 = np.minimum(r_1, image.shape[0] - 1)
        for arr in (top, bot, lef, rig):
            arr.shape = arr.shape + (1,) * (image.ndim - 2)
        out = top * rig * image[r_0][:, c_0, ...]
        out += bot * rig * image[r_1][:, c_0, ...]
        out += top * lef * image[r_0][:, c_1, ...]
        out += bot * lef * image[r_1][:, c_1, ...]
    else:  # kind == 'nearest'
        r = np.round(r).astype(int)
        c = np.round(c).astype(int)
        out = image[r][:, c, ...]
    return out

Response: Resizes an image into a new image with the specified shape.


Instruction:
Create a Python 3 function for
appending a new set of segments to the collection.

Response:
def append(self, P0, P1, itemsize=None, **kwargs):
        """
        Append a new set of segments to the collection.

        For kwargs argument, n is the number of vertices (local) or the number
        of item (shared)

        Parameters
        ----------

        P : np.array
            Vertices positions of the path(s) to be added

        closed: bool
            Whether path(s) is/are closed

        itemsize: int or None
            Size of an individual path

        color : list, array or 4-tuple
           Path color
        """

        itemsize = itemsize or 1
        itemcount = len(P0) / itemsize

        V = np.empty(itemcount, dtype=self.vtype)

        # Apply default values on vertices
        for name in self.vtype.names:
            if name not in ['collection_index', 'P']:
                V[name] = kwargs.get(name, self._defaults[name])

        V = np.repeat(V, 2, axis=0)
        V['P'][0::2] = P0
        V['P'][1::2] = P1

        # Uniforms
        if self.utype:
            U = np.zeros(itemcount, dtype=self.utype)
            for name in self.utype.names:
                if name not in ["__unused__"]:
                    U[name] = kwargs.get(name, self._defaults[name])
        else:
            U = None

        Collection.append(self, vertices=V, uniforms=U, itemsize=itemsize)


Instruction:
Given the following Python 3 function, write the documentation
def parse(self):
        for line in self.lines:
            # Parse the line
            field_defs = self.parse_line(line)
            fields = []

            # Convert field parameters into Field objects
            for (kind, options) in field_defs:
                logger.debug("Creating field %s(%r)", kind, options)
                fields.append(self.field_registry.create(kind, **options))

            # Add the list of Field objects to the 'fields per line'.
            self.line_fields.append(fields)

            # Pre-fill the list of widgets
            for field in fields:
                self.widgets[field] = None

Response: Parse the lines and fill self. line_fields accordingly.


Instruction:
How would you implement a function in Python 3 that
computes the relative position of the fields on a given line.

Response:
def compute_positions(cls, screen_width, line):
        """Compute the relative position of the fields on a given line.

        Args:
            screen_width (int): the width of the screen
            line (mpdlcd.display_fields.Field list): the list of fields on the
                line

        Returns:
            ((int, mpdlcd.display_fields.Field) list): the positions of fields,
                as (position, field) tuples.

        Raises:
            FormatError: if the line contains more than one flexible field, or
                is too long for the screen size.
        """
        # First index
        left = 1
        # Last index
        right = screen_width + 1
        # Current 'flexible' field
        flexible = None

        # Compute the space to the left and to the right of the (optional)
        # flexible field.
        for field in line:
            if field.is_flexible():
                if flexible:
                    raise FormatError(
                        'There can be only one flexible field per line.')
                flexible = field

            elif not flexible:
                left += field.width

            else:
                # Met a 'flexible', computing from the right
                right -= field.width

        # Available space for the 'flexible' field
        available = right - left
        if available <= 0:
            raise FormatError("Too much data for screen width")

        if flexible:
            if available < 1:
                raise FormatError(
                    "Not enough space to display flexible field %s" %
                    flexible.name)

            flexible.width = available

        positions = []
        left = 1
        for field in line:
            positions.append((left, field))
            left += field.width

        logger.debug('Positions are %r', positions)
        return positions


Instruction:
Write a Python 3 function for
adding the pattern to a screen.

Response:
def add_to_screen(self, screen_width, screen):
        """Add the pattern to a screen.

        Also fills self.widgets.

        Args:
            screen_width (int): the width of the screen
            screen (lcdprod.Screen): the screen to fill.
        """
        for lineno, fields in enumerate(self.line_fields):
            for left, field in self.compute_positions(screen_width, fields):
                logger.debug(
                    "Adding field %s to screen %s at x=%d->%d, y=%d",
                    field, screen.ref, left, left + field.width - 1, 1 + lineno,
                )

                self.widgets[field] = field.add_to_screen(screen, left, 1 + lineno)
                self.register_hooks(field)


Instruction:
Can you create a Python 3 function that
registers a field on its target hooks.

Response:
def register_hooks(self, field):
        """Register a field on its target hooks."""
        for hook, subhooks in field.register_hooks():
            self.hooks[hook].append(field)
            self.subhooks[hook] |= set(subhooks)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def hook_changed(self, hook, new_data):
        for field in self.hooks[hook]:
            widget = self.widgets[field]
            field.hook_changed(hook, widget, new_data)

Response: Called whenever the data for a specific hook has changed.


Instruction:
Can you generate the documentation for the following Python 3 function
def parse_line(self, line):
        logger.debug('Parsing line %s', line)

        OUT_FIELD = 0
        IN_FIELD_KIND = 1
        IN_FIELD_OPTION_NAME = 2
        IN_FIELD_OPTION_VALUE = 3

        class ParserState(object):
            """Holds the current state of the parser.

            Attributes:
                quote (str): the current quote character, or None
                escaping (bool): whether the next character should be escaped
                block (char list): the content of the current 'block'
                kind (str): the kind of the current field, or ''
                option_name (str): the name of the current option, or ''
                options (dict(str => str)): maps option name to option value for
                    the current field
                state (int): state of the parser,one of OUT_FIELD/IN_FIELD_*
                fields ((str, dict(str => str)) list): list of fields, as
                    (kind, options) tuples.
            """

            def __init__(self, logger=None):
                self.quote = None
                self.escaping = False
                self.block = []
                self.kind = ''
                self.option_name = ''
                self.options = {}
                self.state = OUT_FIELD
                self.fields = []
                if not logger:
                    logger = logging.getLogger('%s.parser' % __name__)
                self.logger = logger

            def _reset(self):
                """Reset buffered state (quote/escape/block)."""
                self.quote = None
                self.escaping = False
                self.block = []

            def _register_field(self, kind, options):
                """Register a completed field."""
                self.fields.append((kind, dict(options)))

            def debug(self, msg, *args, **kwargs):
                """Print a debug message."""
                self.logger.debug(msg, *args, **kwargs)

            def save_fixed_text(self):
                """Register a completed, fixed text, field."""
                assert self.state == OUT_FIELD
                self._register_field(FIXED_TEXT_FIELD, {'text': ''.join(self.block)})

            def enter_field(self):
                """Enter a new field."""
                self.debug('Entering new field')
                self.state = IN_FIELD_KIND
                self.kind = ''
                self.options = {}
                self.option_name = ''
                self._reset()

            def leave_kind(self):
                """Leave the field kind."""
                self.state = IN_FIELD_OPTION_NAME
                self.kind = ''.join(self.block)
                self.debug("Got widget kind '%s'", self.kind)
                self._reset()

            def leave_option_name(self):
                """Leave an option name."""
                self.state = IN_FIELD_OPTION_VALUE
                self.option_name = ''.join(self.block)
                self.debug("Got option name '%s' for '%s'", self.option_name, self.kind)
                self._reset()

            def leave_option_value(self):
                """Leave an option value."""
                self.state = IN_FIELD_OPTION_NAME
                option_value = ''.join(self.block)
                self.options[self.option_name] = option_value
                self.debug("Got option '%s=%s' for '%s'", self.option_name, option_value, self.kind)
                self._reset()

            def leave_field(self):
                """Leave a field definition."""
                self.state = OUT_FIELD
                self._register_field(self.kind, self.options)
                self.debug(
                    "Got widget '%s(%s)'", self.kind,
                    ', '.join('%s=%r' % it for it in self.options.items()),
                )
                self._reset()

        st = ParserState()

        for pos, char in enumerate(line):

            # Escaping
            if st.escaping:
                st.escaping = False
                st.block.append(char)

            elif char == '\\':
                st.escaping = True

            # Quoting
            elif char in ['"', "'"]:
                if st.state == IN_FIELD_OPTION_VALUE:
                    if st.quote:  # Already in a quoted block
                        if char == st.quote:
                            st.leave_option_value()
                        else:
                            st.block.append(char)

                    elif not st.block:  # First char of the block
                        st.quote = char
                        continue

                    else:
                        raise FormatError("Unexpected '%s' at %d in %s" % (char, pos, line))

                elif st.state == OUT_FIELD:
                    st.block.append(char)

                else:
                    raise FormatError("Unexpected '%s' at %d in %s" % (char, pos, line))

            # Entering a field
            elif char == '{':
                if st.state == OUT_FIELD:
                    if st.block:
                        st.save_fixed_text()
                    st.enter_field()

                elif st.state == IN_FIELD_OPTION_VALUE and st.quote:
                    st.block.append(char)

                else:
                    raise FormatError("Unexpected '{' at %d in %s" % (pos, line))

            # Leaving a field
            elif char == '}':
                if st.state == IN_FIELD_KIND:
                    st.leave_kind()
                    st.leave_field()

                elif st.state == IN_FIELD_OPTION_NAME:
                    raise FormatError("Missing option value for %s at %d in %s" % (''.join(st.block), pos, line))

                elif st.state == IN_FIELD_OPTION_VALUE:
                    if st.quote:
                        st.block.append(char)
                    else:
                        st.leave_option_value()
                        st.leave_field()

                elif st.state == OUT_FIELD:
                    raise FormatError("Unexpected '}' at %d in %s" % (pos, line))

            # Between kind and option name
            elif char == ' ':
                if st.state == IN_FIELD_KIND:
                    if not st.block:
                        raise FormatError("Missing field kind at %s in %s" % (pos, line))

                    st.leave_kind()

                elif st.state == IN_FIELD_OPTION_VALUE and st.quote:
                    st.block.append(char)

                elif st.state == OUT_FIELD:
                    st.block.append(char)

                else:
                    raise FormatError("Unexpected ' ' at %d in %s" % (pos, line))

            # Between options
            elif char == ',':
                if st.state == IN_FIELD_OPTION_NAME:
                    if st.block:
                        raise FormatError("Missing option value for %s at %d in %s" % (''.join(st.block), pos, line))
                    else:
                        # At the beginning of a new option
                        continue

                elif st.state == IN_FIELD_KIND:
                    raise FormatError("Unexpected ',' in field definition %s at %d in %s" % (st.kind, pos, line))

                elif st.state == IN_FIELD_OPTION_VALUE:
                    if st.quote:
                        st.block.append(char)
                    elif st.block:
                        st.leave_option_value()
                    else:
                        raise FormatError("Missing option value for %s at %d in %s" % (st.option_name, pos, line))

                else:  # OUT_FIELD
                    st.block.append(char)

            # Between option name and option value
            elif char == '=':
                if st.state == IN_FIELD_OPTION_NAME:
                    if st.block:
                        st.leave_option_name()

                    else:
                        raise FormatError("Missing option name at %d in %s" % (pos, line))

                elif st.state == OUT_FIELD:
                    st.block.append(char)

                elif st.state == IN_FIELD_OPTION_VALUE:
                    if st.quote:
                        st.block.append(char)

                    elif not st.block:
                        # At the beginning of an option
                        continue

                    else:
                        raise FormatError(
                            "Unexpected '=' in option value for %s at %d in %s"
                            % (st.option_name, pos, line))

                else:
                    raise FormatError("Unexpected '=' at %d in %s" % (pos, line))

            # Everything else
            else:
                st.block.append(char)

        # All input parsed
        if st.state != OUT_FIELD:
            raise FormatError("Unclosed field at %d in '%s'; block: '%s'" % (pos, line, ''.join(st.block)))

        if st.block:
            st.save_fixed_text()

        return st.fields

Response: Parse a line of text into a patternLine object.


Instruction:
Make a summary of the following Python 3 code
def add(self, pattern_txt):
        self.patterns[len(pattern_txt)] = pattern_txt

        low = 0
        high = len(pattern_txt) - 1

        while not pattern_txt[low]:
            low += 1

        while not pattern_txt[high]:
            high -= 1

        min_pattern = pattern_txt[low:high + 1]
        self.min_patterns[len(min_pattern)] = min_pattern

Response: Adds a pattern to the list.


Instruction:
Write a Python 3 function that can
convert x y coordinates to w x y z Quaternion parameters

Response:
def _arcball(xy, wh):
    """Convert x,y coordinates to w,x,y,z Quaternion parameters

    Adapted from:

    linalg library

    Copyright (c) 2010-2015, Renaud Blanch <rndblnch at gmail dot com>
    Licence at your convenience:
    GPLv3 or higher <http://www.gnu.org/licenses/gpl.html>
    BSD new <http://opensource.org/licenses/BSD-3-Clause>
    """
    x, y = xy
    w, h = wh
    r = (w + h) / 2.
    x, y = -(2. * x - w) / r, (2. * y - h) / r
    h = np.sqrt(x*x + y*y)
    return (0., x/h, y/h, 0.) if h > 1. else (0., x, y, np.sqrt(1. - h*h))


Instruction:
Can you generate the documentation for the following Python 3 function
def _update_rotation(self, event):
        p2 = event.mouse_event.pos
        if self._event_value is None:
            self._event_value = p2
        wh = self._viewbox.size
        self._quaternion = (Quaternion(*_arcball(p2, wh)) *
                            Quaternion(*_arcball(self._event_value, wh)) *
                            self._quaternion)
        self._event_value = p2
        self.view_changed()

Response: Update rotation parmeters based on mouse movement


Instruction:
Implement a function in Python 3 to
rotate the transformation matrix based on camera parameters

Response:
def _rotate_tr(self):
        """Rotate the transformation matrix based on camera parameters"""
        rot, x, y, z = self._quaternion.get_axis_angle()
        up, forward, right = self._get_dim_vectors()
        self.transform.rotate(180 * rot / np.pi, (x, z, y))


Instruction:
Create a Python 3 function to
convert mouse x y movement into x y z translations

Response:
def _dist_to_trans(self, dist):
        """Convert mouse x, y movement into x, y, z translations"""
        rot, x, y, z = self._quaternion.get_axis_angle()
        tr = MatrixTransform()
        tr.rotate(180 * rot / np.pi, (x, y, z))
        dx, dz, dy = np.dot(tr.matrix[:3, :3], (dist[0], dist[1], 0.))
        return dx, dy, dz


Instruction:
Can you generate the documentation for the following Python 3 function
def as_vec4(obj, default=(0, 0, 0, 1)):
    obj = np.atleast_2d(obj)
    # For multiple vectors, reshape to (..., 4)
    if obj.shape[-1] < 4:
        new = np.empty(obj.shape[:-1] + (4,), dtype=obj.dtype)
        new[:] = default
        new[..., :obj.shape[-1]] = obj
        obj = new
    elif obj.shape[-1] > 4:
        raise TypeError("Array shape %s cannot be converted to vec4"
                        % obj.shape)
    return obj

Response: Convert obj to 4 - element vector.


Instruction:
Make a summary of the following Python 3 code
def arg_to_vec4(func, self_, arg, *args, **kwargs):
    if isinstance(arg, (tuple, list, np.ndarray)):
        arg = np.array(arg)
        flatten = arg.ndim == 1
        arg = as_vec4(arg)

        ret = func(self_, arg, *args, **kwargs)
        if flatten and ret is not None:
            return ret.flatten()
        return ret
    elif hasattr(arg, '_transform_in'):
        arr = arg._transform_in()
        ret = func(self_, arr, *args, **kwargs)
        return arg._transform_out(ret)
    else:
        raise TypeError("Cannot convert argument to 4D vector: %s" % arg)

Response: Decorator for converting an argument to vec4 format suitable for 4x4 matrix multiplication.


Instruction:
Make a summary of the following Python 3 code
def get(self, path):
        key = tuple(map(id, path))
        item = self._cache.get(key, None)
        if item is None:
            logger.debug("Transform cache miss: %s", key)
            item = [0, self._create(path)]
            self._cache[key] = item
        item[0] = 0  # reset age for this item

        # make sure the chain is up to date
        #tr = item[1]
        #for i, node in enumerate(path[1:]):
        #    if tr.transforms[i] is not node.transform:
        #        tr[i] = node.transform

        return item[1]

Response:
Get a transform from the cache that maps along path which must
        be a list of Transforms to apply in reverse order.


Instruction:
Can you implement a function in Python 3 that
rolls the cache by 1. Items whose age is greater than self. max_age will be removed from the cache.

Response:
def roll(self):
        """ Increase the age of all items in the cache by 1. Items whose age
        is greater than self.max_age will be removed from the cache.
        """
        rem = []
        for key, item in self._cache.items():
            if item[0] > self.max_age:
                rem.append(key)
            item[0] += 1

        for key in rem:
            logger.debug("TransformCache remove: %s", key)
            del self._cache[key]


Instruction:
Write a Python 3 function that can
calculate and show a histogram of data.

Response:
def histogram(self, data, bins=10, color='w', orientation='h'):
        """Calculate and show a histogram of data

        Parameters
        ----------
        data : array-like
            Data to histogram. Currently only 1D data is supported.
        bins : int | array-like
            Number of bins, or bin edges.
        color : instance of Color
            Color of the histogram.
        orientation : {'h', 'v'}
            Orientation of the histogram.

        Returns
        -------
        hist : instance of Polygon
            The histogram polygon.
        """
        self._configure_2d()
        hist = scene.Histogram(data, bins, color, orientation)
        self.view.add(hist)
        self.view.camera.set_range()
        return hist


Instruction:
Can you generate the documentation for the following Python 3 function
def image(self, data, cmap='cubehelix', clim='auto', fg_color=None):
        self._configure_2d(fg_color)
        image = scene.Image(data, cmap=cmap, clim=clim)
        self.view.add(image)
        self.view.camera.aspect = 1
        self.view.camera.set_range()

        return image

Response: Show an image in the view.


Instruction:
Given the following Python 3 function, write the documentation
def mesh(self, vertices=None, faces=None, vertex_colors=None,
             face_colors=None, color=(0.5, 0.5, 1.), fname=None,
             meshdata=None):
        """Show a 3D mesh

        Parameters
        ----------
        vertices : array
            Vertices.
        faces : array | None
            Face definitions.
        vertex_colors : array | None
            Vertex colors.
        face_colors : array | None
            Face colors.
        color : instance of Color
            Color to use.
        fname : str | None
            Filename to load. If not None, then vertices, faces, and meshdata
            must be None.
        meshdata : MeshData | None
            Meshdata to use. If not None, then vertices, faces, and fname
            must be None.

        Returns
        -------
        mesh : instance of Mesh
            The mesh.
        """
        self._configure_3d()
        if fname is not None:
            if not all(x is None for x in (vertices, faces, meshdata)):
                raise ValueError('vertices, faces, and meshdata must be None '
                                 'if fname is not None')
            vertices, faces = read_mesh(fname)[:2]
        if meshdata is not None:
            if not all(x is None for x in (vertices, faces, fname)):
                raise ValueError('vertices, faces, and fname must be None if '
                                 'fname is not None')
        else:
            meshdata = MeshData(vertices, faces)
        mesh = scene.Mesh(meshdata=meshdata, vertex_colors=vertex_colors,
                          face_colors=face_colors, color=color,
                          shading='smooth')
        self.view.add(mesh)
        self.view.camera.set_range()
        return mesh

Response: Show a 3D mesh.


Instruction:
Write a Python 3 function for
plotting a series of data using lines and markers.

Response:
def plot(self, data, color='k', symbol=None, line_kind='-', width=1.,
             marker_size=10., edge_color='k', face_color='b', edge_width=1.,
             title=None, xlabel=None, ylabel=None):
        """Plot a series of data using lines and markers

        Parameters
        ----------
        data : array | two arrays
            Arguments can be passed as ``(Y,)``, ``(X, Y)`` or
            ``np.array((X, Y))``.
        color : instance of Color
            Color of the line.
        symbol : str
            Marker symbol to use.
        line_kind : str
            Kind of line to draw. For now, only solid lines (``'-'``)
            are supported.
        width : float
            Line width.
        marker_size : float
            Marker size. If `size == 0` markers will not be shown.
        edge_color : instance of Color
            Color of the marker edge.
        face_color : instance of Color
            Color of the marker face.
        edge_width : float
            Edge width of the marker.
        title : str | None
            The title string to be displayed above the plot
        xlabel : str | None
            The label to display along the bottom axis
        ylabel : str | None
            The label to display along the left axis.

        Returns
        -------
        line : instance of LinePlot
            The line plot.

        See also
        --------
        marker_types, LinePlot
        """
        self._configure_2d()
        line = scene.LinePlot(data, connect='strip', color=color,
                              symbol=symbol, line_kind=line_kind,
                              width=width, marker_size=marker_size,
                              edge_color=edge_color,
                              face_color=face_color,
                              edge_width=edge_width)
        self.view.add(line)
        self.view.camera.set_range()
        self.visuals.append(line)

        if title is not None:
            self.title.text = title
        if xlabel is not None:
            self.xlabel.text = xlabel
        if ylabel is not None:
            self.ylabel.text = ylabel

        return line


Instruction:
Create a Python 3 function for
calculating and show a spectrogram of the specified data.

Response:
def spectrogram(self, x, n_fft=256, step=None, fs=1., window='hann',
                    color_scale='log', cmap='cubehelix', clim='auto'):
        """Calculate and show a spectrogram

        Parameters
        ----------
        x : array-like
            1D signal to operate on. ``If len(x) < n_fft``, x will be
            zero-padded to length ``n_fft``.
        n_fft : int
            Number of FFT points. Much faster for powers of two.
        step : int | None
            Step size between calculations. If None, ``n_fft // 2``
            will be used.
        fs : float
            The sample rate of the data.
        window : str | None
            Window function to use. Can be ``'hann'`` for Hann window, or None
            for no windowing.
        color_scale : {'linear', 'log'}
            Scale to apply to the result of the STFT.
            ``'log'`` will use ``10 * log10(power)``.
        cmap : str
            Colormap name.
        clim : str | tuple
            Colormap limits. Should be ``'auto'`` or a two-element tuple of
            min and max values.

        Returns
        -------
        spec : instance of Spectrogram
            The spectrogram.

        See also
        --------
        Image
        """
        self._configure_2d()
        # XXX once we have axes, we should use "fft_freqs", too
        spec = scene.Spectrogram(x, n_fft, step, fs, window,
                                 color_scale, cmap, clim)
        self.view.add(spec)
        self.view.camera.set_range()
        return spec


Instruction:
Implement a function in Python 3 to
show a 3D volume

Response:
def volume(self, vol, clim=None, method='mip', threshold=None,
               cmap='grays'):
        """Show a 3D volume

        Parameters
        ----------
        vol : ndarray
            Volume to render.
        clim : tuple of two floats | None
            The contrast limits. The values in the volume are mapped to
            black and white corresponding to these values. Default maps
            between min and max.
        method : {'mip', 'iso', 'translucent', 'additive'}
            The render style to use. See corresponding docs for details.
            Default 'mip'.
        threshold : float
            The threshold to use for the isosurafce render style. By default
            the mean of the given volume is used.
        cmap : str
            The colormap to use.

        Returns
        -------
        volume : instance of Volume
            The volume visualization.

        See also
        --------
        Volume
        """
        self._configure_3d()
        volume = scene.Volume(vol, clim, method, threshold, cmap=cmap)
        self.view.add(volume)
        self.view.camera.set_range()
        return volume


Instruction:
Explain what the following Python 3 code does
def surface(self, zdata, **kwargs):
        self._configure_3d()
        surf = scene.SurfacePlot(z=zdata, **kwargs)
        self.view.add(surf)
        self.view.camera.set_range()
        return surf

Response: Show a 3D surface plot.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def colorbar(self, cmap, position="right",
                 label="", clim=("", ""),
                 border_width=0.0, border_color="black",
                 **kwargs):
        """Show a ColorBar

        Parameters
        ----------
        cmap : str | vispy.color.ColorMap
            Either the name of the ColorMap to be used from the standard
            set of names (refer to `vispy.color.get_colormap`),
            or a custom ColorMap object.
            The ColorMap is used to apply a gradient on the colorbar.
        position : {'left', 'right', 'top', 'bottom'}
            The position of the colorbar with respect to the plot.
            'top' and 'bottom' are placed horizontally, while
            'left' and 'right' are placed vertically
        label : str
            The label that is to be drawn with the colorbar
            that provides information about the colorbar.
        clim : tuple (min, max)
            the minimum and maximum values of the data that
            is given to the colorbar. This is used to draw the scale
            on the side of the colorbar.
        border_width : float (in px)
            The width of the border the colormap should have. This measurement
            is given in pixels
        border_color : str | vispy.color.Color
            The color of the border of the colormap. This can either be a
            str as the color's name or an actual instace of a vipy.color.Color

        Returns
        -------
        colorbar : instance of ColorBarWidget

        See also
        --------
        ColorBarWidget
        """

        self._configure_2d()

        cbar = scene.ColorBarWidget(orientation=position,
                                    label_str=label,
                                    cmap=cmap,
                                    clim=clim,
                                    border_width=border_width,
                                    border_color=border_color,
                                    **kwargs)

        CBAR_LONG_DIM = 50

        if cbar.orientation == "bottom":
            self.grid.remove_widget(self.cbar_bottom)
            self.cbar_bottom = self.grid.add_widget(cbar, row=5, col=4)
            self.cbar_bottom.height_max = \
                self.cbar_bottom.height_max = CBAR_LONG_DIM

        elif cbar.orientation == "top":
            self.grid.remove_widget(self.cbar_top)
            self.cbar_top = self.grid.add_widget(cbar, row=1, col=4)
            self.cbar_top.height_max = self.cbar_top.height_max = CBAR_LONG_DIM

        elif cbar.orientation == "left":
            self.grid.remove_widget(self.cbar_left)
            self.cbar_left = self.grid.add_widget(cbar, row=2, col=1)
            self.cbar_left.width_max = self.cbar_left.width_min = CBAR_LONG_DIM

        else:  # cbar.orientation == "right"
            self.grid.remove_widget(self.cbar_right)
            self.cbar_right = self.grid.add_widget(cbar, row=2, col=5)
            self.cbar_right.width_max = \
                self.cbar_right.width_min = CBAR_LONG_DIM

        return cbar

Response: Show a ColorBarWidget for the specified ColorMap and position.


Instruction:
How would you implement a function in Python 3 that
redraws the Vispy canvas

Response:
def redraw(self):
        """
        Redraw the Vispy canvas
        """
        if self._multiscat is not None:
            self._multiscat._update()
        self.vispy_widget.canvas.update()


Instruction:
Create a Python 3 function for
removing the layer artist from the visualization

Response:
def remove(self):
        """
        Remove the layer artist from the visualization
        """

        if self._multiscat is None:
            return

        self._multiscat.deallocate(self.id)
        self._multiscat = None

        self._viewer_state.remove_global_callback(self._update_scatter)
        self.state.remove_global_callback(self._update_scatter)


Instruction:
Here you have a function in Python 3, explain what it does
def _check_valid(key, val, valid):
    if val not in valid:
        raise ValueError('%s must be one of %s, not "%s"'
                         % (key, valid, val))

Response: Helper to check if a key value is in the valid options


Instruction:
Can you write a function in Python 3 where it
converts to args representation

Response:
def _to_args(x):
    """Convert to args representation"""
    if not isinstance(x, (list, tuple, np.ndarray)):
        x = [x]
    return x


Instruction:
Can you tell what is the following Python 3 function doing
def _check_conversion(key, valid_dict):
    if key not in valid_dict and key not in valid_dict.values():
        # Only show users the nice string values
        keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]
        raise ValueError('value must be one of %s, not %s' % (keys, key))
    return valid_dict[key] if key in valid_dict else key

Response: Check for existence of key in dict return value or raise error