Instruction:
Can you generate a brief explanation for the following Python 3 code
def image_set_clim(zmin=None, zmax=None, axes="gca"):
    if axes=="gca": axes=_pylab.gca()

    image = axes.images[0]

    if zmin=='auto': zmin = _n.min(image.get_array())
    if zmax=='auto': zmax = _n.max(image.get_array())

    if zmin==None: zmin = image.get_clim()[0]
    if zmax==None: zmax = image.get_clim()[1]

    image.set_clim(zmin, zmax)

    _pylab.draw()

Response: This function will set the clim of the colorbar.


Instruction:
Here you have a function in Python 3, explain what it does
def manipulate_shown_data(f, input_axes="gca", output_axes=None, fxname=1, fyname=1, clear=1, pause=False, **kwargs):

    # get the axes
    if input_axes == "gca": a1 = _pylab.gca()
    else:                   a1 = input_axes

    # get the xlimits
    xmin, xmax = a1.get_xlim()

    # get the name to stick on the x and y labels
    if fxname==1: fxname = f.__name__
    if fyname==1: fyname = f.__name__

    # get the output axes
    if output_axes == None:
        _pylab.figure(a1.figure.number+1)
        a2 = _pylab.axes()
    else:
        a2 = output_axes

    if clear: a2.clear()

    # loop over the data
    for line in a1.get_lines():

        # if it's a line, do the manipulation
        if isinstance(line, _mpl.lines.Line2D):

            # get the data
            x, y = line.get_data()

            # trim the data according to the current zoom level
            x, y = _fun.trim_data(xmin, xmax, x, y)

            # do the manipulation
            new_x, new_y = f(x,y)

            # plot the new
            _s.plot.xy.data(new_x, new_y, clear=0, label=line.get_label().replace("_", "-"), axes=a2, **kwargs)

            # pause after each curve if we're supposed to
            if pause:
                _pylab.draw()
                input("<enter> ")

    # set the labels and title.
    if fxname in [0,None]:  a2.set_xlabel(a1.get_xlabel())
    else:                   a2.set_xlabel(fxname+"("+a1.get_xlabel()+")")

    if fyname in [0,None]:  a2.set_ylabel(a1.get_ylabel())
    else:                   a2.set_ylabel(fyname+"("+a1.get_ylabel()+")")

    _pylab.draw()

Response: manipulates the shown data on the specified axes and saves the manipulated data on the specified axes.


Instruction:
Make a summary of the following Python 3 code
def manipulate_shown_ydata(fy, fyname=1, **kwargs):
    def f(x,y): return x, fy(y)
    f.__name__ = fy.__name__
    manipulate_shown_data(f, fxname=None, fyname=fyname, **kwargs)

Response: This function is used to manipulate the xdata and fy data.


Instruction:
Make a summary of the following Python 3 code
def _print_figures(figures, arguments='', file_format='pdf', target_width=8.5, target_height=11.0, target_pad=0.5):

    for fig in figures:

        # get the temp path
        temp_path = _os.path.join(_settings.path_home, "temp")

        # make the temp folder
        _settings.MakeDir(temp_path)

        # output the figure to postscript
        path = _os.path.join(temp_path, "graph."+file_format)

        # get the dimensions of the figure in inches
        w=fig.get_figwidth()
        h=fig.get_figheight()

        # we're printing to 8.5 x 11, so aim for 7.5 x 10
        target_height = target_height-2*target_pad
        target_width  = target_width -2*target_pad

        # depending on the aspect we scale by the vertical or horizontal value
        if 1.0*h/w > target_height/target_width:
            # scale down according to the vertical dimension
            new_h = target_height
            new_w = w*target_height/h
        else:
            # scale down according to the hozo dimension
            new_w = target_width
            new_h = h*target_width/w

        fig.set_figwidth(new_w)
        fig.set_figheight(new_h)

        # save it
        fig.savefig(path, bbox_inches=_pylab.matplotlib.transforms.Bbox(
            [[-target_pad, new_h-target_height-target_pad],
             [target_width-target_pad, target_height-target_pad]]))

        # set it back
        fig.set_figheight(h)
        fig.set_figwidth(w)

        if not arguments == '':
            c = _settings['instaprint'] + ' ' + arguments + ' "' + path + '"'
        else:
            c = _settings['instaprint'] + ' "' + path + '"'

        print(c)
        _os.system(c)

Response: Print the given figures to a postscript file.


Instruction:
Here you have a function in Python 3, explain what it does
def instaprint(figure='gcf', arguments='', threaded=False, file_format='pdf'):

    global _settings

    if 'instaprint' not in _settings.keys():
        print("No print command setup. Set the user variable settings['instaprint'].")
        return

    if   figure=='gcf': figure=[_pylab.gcf().number]
    elif figure=='all': figure=_pylab.get_fignums()
    if not getattr(figure,'__iter__',False): figure = [figure]

    print("figure numbers in queue:", figure)

    figures=[]
    for n in figure: figures.append(_pylab.figure(n))

    # now run the ps printing command
    if threaded:
        # store the canvas type of the last figure
        canvas_type = type(figures[-1].canvas)

        # launch the aforementioned function as a separate thread
        _thread.start_new_thread(_print_figures, (figures,arguments,file_format,))

        # wait until the thread is running
        _time.sleep(0.25)

        # wait until the canvas type has returned to normal
        t0 = _time.time()
        while not canvas_type == type(figures[-1].canvas) and _time.time()-t0 < 5.0:
            _time.sleep(0.1)
        if _time.time()-t0 >= 5.0:
            print("WARNING: Timed out waiting for canvas to return to original state!")

        # bring back the figure and command line
        _pylab.draw()

    else:
        _print_figures(figures, arguments, file_format)
        _pylab.draw()

Response: Quick function that saves the specified figure as a postscript and then calls the print command.


Instruction:
Given the following Python 3 function, write the documentation
def raise_figure_window(f=0):
    if _fun.is_a_number(f): f = _pylab.figure(f)
    f.canvas.manager.window.raise_()

Response: Raises the supplied figure window.


Instruction:
Can you write a function in Python 3 where it
sets figure window geometry.

Response:
def set_figure_window_geometry(fig='gcf', position=None, size=None):
    """
    This will currently only work for Qt4Agg and WXAgg backends.

    postion = [x, y]
    size    = [width, height]

    fig can be 'gcf', a number, or a figure object.
    """

    if type(fig)==str:          fig = _pylab.gcf()
    elif _fun.is_a_number(fig): fig = _pylab.figure(fig)

    # Qt4Agg backend. Probably would work for other Qt stuff
    if _pylab.get_backend().find('Qt') >= 0:
        w = fig.canvas.window()

        if not size == None:
            w.resize(size[0],size[1])

        if not position == None:
            w.move(position[0], position[1])

    # WXAgg backend. Probably would work for other Qt stuff.
    elif _pylab.get_backend().find('WX') >= 0:
        w = fig.canvas.Parent

        if not size == None:
            w.SetSize(size)

        if not position == None:
            w.SetPosition(position)


Instruction:
Given the following Python 3 function, write the documentation
def set_yticks(start, step, axes="gca"):
    if axes=="gca": axes = _pylab.gca()

    # first get one of the tick label locations
    xposition = axes.yaxis.get_ticklabels()[0].get_position()[0]

    # get the bounds
    ymin, ymax = axes.get_ylim()

    # get the starting tick
    nstart = int(_pylab.floor((ymin-start)/step))
    nstop  = int(_pylab.ceil((ymax-start)/step))
    ticks = []
    for n in range(nstart,nstop+1): ticks.append(start+n*step)

    axes.set_yticks(ticks)

    # set the x-position
    for t in axes.yaxis.get_ticklabels():
        x, y = t.get_position()
        t.set_position((xposition, y))

    _pylab.draw()

Response: This will generate a tick array and apply said array to the axis


Instruction:
How would you code a function in Python 3 to
coarsen the specified line.

Response:
def coarsen_line(line, level=2, exponential=False, draw=True):
    """
    Coarsens the specified line (see spinmob.coarsen_data() for more information).

    Parameters
    ----------
    line
        Matplotlib line instance.
    level=2
        How strongly to coarsen.
    exponential=False
        If True, use the exponential method (great for log-x plots).
    draw=True
        Redraw when complete.
    """

    # get the actual data values
    xdata = line.get_xdata()
    ydata = line.get_ydata()

    xdata,ydata = _fun.coarsen_data(xdata, ydata, level=level, exponential=exponential)

    # don't do anything if we don't have any data left
    if len(ydata) == 0: print("There's nothing left in "+str(line)+"!")

    # otherwise set the data with the new arrays
    else: line.set_data(xdata, ydata)

    # we refresh in real time for giggles
    if draw: _pylab.draw()


Instruction:
Can you implement a function in Python 3 that
applies function fx to all xdata and fy to all ydata.

Response:
def line_math(fx=None, fy=None, axes='gca'):
    """
    applies function fx to all xdata and fy to all ydata.
    """

    if axes=='gca': axes = _pylab.gca()

    lines = axes.get_lines()

    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            xdata, ydata = line.get_data()
            if not fx==None: xdata = fx(xdata)
            if not fy==None: ydata = fy(ydata)
            line.set_data(xdata,ydata)

    _pylab.draw()


Instruction:
Create a Python 3 function to
export the current figure to a file.

Response:
def export_figure(dpi=200, figure="gcf", path=None):
    """
    Saves the actual postscript data for the figure.
    """
    if figure=="gcf": figure = _pylab.gcf()

    if path==None: path = _s.dialogs.Save("*.*", default_directory="save_plot_default_directory")

    if path=="":
        print("aborted.")
        return

    figure.savefig(path, dpi=dpi)


Instruction:
Can you implement a function in Python 3 that
saves the figure in my own ascii format

Response:
def save_plot(axes="gca", path=None):
    """
    Saves the figure in my own ascii format
    """

    global line_attributes

    # choose a path to save to
    if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory")

    if path=="":
        print("aborted.")
        return

    if not path.split(".")[-1] == "plot": path = path+".plot"

    f = file(path, "w")

    # if no argument was given, get the current axes
    if axes=="gca": axes=_pylab.gca()

    # now loop over the available lines
    f.write("title="  +axes.title.get_text().replace('\n', '\\n')+'\n')
    f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n')
    f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n')

    for l in axes.lines:
        # write the data header
        f.write("trace=new\n")
        f.write("legend="+l.get_label().replace('\n', '\\n')+"\n")

        for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n")

        # get the data
        x = l.get_xdata()
        y = l.get_ydata()

        # loop over the data
        for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n")

    f.close()


Instruction:
Write a Python 3 function that can
save the raw data of the current figure to a file.

Response:
def save_figure_raw_data(figure="gcf", **kwargs):
    """
    This will just output an ascii file for each of the traces in the shown figure.

    **kwargs are sent to dialogs.Save()
    """

    # choose a path to save to
    path = _s.dialogs.Save(**kwargs)
    if path=="": return "aborted."

    # if no argument was given, get the current axes
    if figure=="gcf": figure = _pylab.gcf()

    for n in range(len(figure.axes)):
        a = figure.axes[n]

        for m in range(len(a.lines)):
            l = a.lines[m]

            x = l.get_xdata()
            y = l.get_ydata()

            p = _os.path.split(path)
            p = _os.path.join(p[0], "axes" + str(n) + " line" + str(m) + " " + p[1])
            print(p)

            # loop over the data
            f = open(p, 'w')
            for j in range(0, len(x)):
                f.write(str(x[j]) + "\t" + str(y[j]) + "\n")
            f.close()


Instruction:
Given the following Python 3 function, write the documentation
def get_line_color(self, increment=1):

        i = self.line_colors_index

        self.line_colors_index += increment
        if self.line_colors_index >= len(self.line_colors):
            self.line_colors_index = self.line_colors_index-len(self.line_colors)
            if self.line_colors_index >= len(self.line_colors): self.line_colors_index=0 # to be safe

        return self.line_colors[i]

Response: Returns the current color in the line of the log.


Instruction:
Here you have a function in Python 3, explain what it does
def get_marker(self, increment=1):

        i = self.markers_index

        self.markers_index += increment
        if self.markers_index >= len(self.markers):
            self.markers_index = self.markers_index-len(self.markers)
            if self.markers_index >= len(self.markers): self.markers_index=0 # to be safe

        return self.markers[i]

Response: Returns the current marker in the internal list increments the marker by increment


Instruction:
Can you implement a function in Python 3 that
returns the current marker in the current marker then increments the marker by increment.

Response:
def get_linestyle(self, increment=1):
        """
        Returns the current marker, then increments the marker by what's specified
        """

        i = self.linestyles_index

        self.linestyles_index += increment
        if self.linestyles_index >= len(self.linestyles):
            self.linestyles_index = self.linestyles_index-len(self.linestyles)
            if self.linestyles_index >= len(self.linestyles): self.linestyles_index=0 # to be safe

        return self.linestyles[i]


Instruction:
Write a Python 3 script for
returning the current face color by increment

Response:
def get_face_color(self, increment=1):
        """
        Returns the current face, then increments the face by what's specified
        """

        i = self.face_colors_index

        self.face_colors_index += increment
        if self.face_colors_index >= len(self.face_colors):
            self.face_colors_index = self.face_colors_index-len(self.face_colors)
            if self.face_colors_index >= len(self.face_colors): self.face_colors_index=0 # to be safe

        return self.face_colors[i]


Instruction:
Make a summary of the following Python 3 code
def get_edge_color(self, increment=1):

        i = self.edge_colors_index

        self.edge_colors_index += increment
        if self.edge_colors_index >= len(self.edge_colors):
            self.edge_colors_index = self.edge_colors_index-len(self.edge_colors)
            if self.edge_colors_index >= len(self.edge_colors): self.edge_colors_index=0 # to be safe

        return self.edge_colors[i]

Response: Returns the edge color for the current face then increments the face by increment


Instruction:
Can you write a function in Python 3 where it
applies the style cycle to the lines in the specified axes

Response:
def apply(self, axes="gca"):
        """
        Applies the style cycle to the lines in the axes specified
        """

        if axes == "gca": axes = _pylab.gca()
        self.reset()
        lines = axes.get_lines()

        for l in lines:
            l.set_color(self.get_line_color(1))
            l.set_mfc(self.get_face_color(1))
            l.set_marker(self.get_marker(1))
            l.set_mec(self.get_edge_color(1))
            l.set_linestyle(self.get_linestyle(1))

        _pylab.draw()


Instruction:
Write a Python 3 function that can
send a message to a user.

Response:
def _send_message(session, user_id, message=None, image_files=None):
        """
        https://vk.com/dev/messages.send
        """
        assert any([message, image_files])

        attachment_items = None
        if image_files:
            attachment_items = Photo._upload_messages_photos_for_group(session, user_id, image_files)

        message_id = session.fetch("messages.send", user_id=user_id, message=message, attachment=attachment_items, random_id=random.randint(1, 10**6))
        return message_id


Instruction:
Write a Python 3 function that can
get all the dialogs in the VK.

Response:
def get_dialog(session, unread=False, important=False, unanswered=False):
        """
        https://vk.com/dev/messages.getDialogs
        """
        response = session.fetch("messages.getDialogs", unread=unread, important=important, unanswered=unanswered)
        dialog_json_items = response["items"]
        return (Message.from_json(session, dialog_json["message"]) for dialog_json in dialog_json_items)


Instruction:
Can you implement a function in Python 3 that
gets members of this group.

Response:
def get_members(self, sort='id_asc'):
        """
        :param: sort {id_asc, id_desc, time_asc, time_desc} string
        Docs: https://vk.com/dev/groups.getMembers
        """
        return self._session.fetch_items("groups.getMembers", User.from_json, 1000, group_id=self.id, sort=sort, fields=User.__slots__ + User.USER_FIELDS)


Instruction:
Write a Python 3 function for
getting user s groups.

Response:
def _get_user_groups(session, user_id, filter):
        """
        https://vk.com/dev/groups.get

        :param filter: {admin, editor, moder, groups, publics, events}
        :yield: Groups
        """
        return session.fetch_items('groups.get', Group.from_json, count=1000, user_id=user_id, filter=filter, extended=1, fields=",".join(Group.GROUP_FIELDS))


Instruction:
Can you generate the documentation for the following Python 3 function
def copy_spline_array(a):

    b = spline_array()

    b.x_splines = a.x_splines
    b.y_splines = a.y_splines
    b.max_y_splines = a.max_y_splines
    b.xmin = a.xmin
    b.xmax = a.xmax
    b.ymin = a.ymin
    b.ymax = a.ymax
    b.xlabel = a.xlabel
    b.ylabel = a.ylabel
    b.zlabel = a.zlabel
    b.simple = a.simple

    b.generate_y_values()

    return b

Response: This returns an instance of a new spline_array with all the fixins and the data from a.


Instruction:
Write a Python 3 function that can
function to plot a single spline.

Response:
def splot(axes="gca", smoothing=5000, degree=5, presmoothing=0, plot=True, spline_class=spline_single, interactive=True, show_derivative=1):
    """

    gets the data from the plot and feeds it into splint
    returns an instance of spline_single

    axes="gca"                  which axes to get the data from.
    smoothing=5000              spline_single smoothing parameter
    presmoothing=0              spline_single data presmoothing factor (nearest neighbor)
    plot=True                   should we plot the result?
    spline_class=spline_single  which data class to use?
    interactive=False           should we spline fit interactively or just make a spline_single?

    """

    if   axes=="gca": axes = _pylab.gca()

    xlabel = axes.xaxis.label.get_text()
    ylabel = axes.yaxis.label.get_text()

    xdata = axes.get_lines()[0].get_xdata()
    ydata = axes.get_lines()[0].get_ydata()

    if interactive:
        return splinteractive(xdata, ydata, smoothing, degree, presmoothing, spline_class, xlabel, ylabel)
    else:
        return spline_class(xdata, ydata, smoothing, degree, presmoothing, plot, xlabel, ylabel)


Instruction:
Can you create a Python 3 function that
evaluates the spline data at the given time series x.

Response:
def evaluate(self,       x, derivative=0, smooth=0, simple='auto'):
        """
        smooth=0      is how much to smooth the spline data
        simple='auto' is whether we should just use straight interpolation
                      you may want smooth > 0 for this, when derivative=1
        """
        if simple=='auto': simple = self.simple

        # make it into an array if it isn't one, and remember that we did
        is_array = True
        if not type(x) == type(_pylab.array([])):
            x = _pylab.array([x])
            is_array = False

        if simple:
            # loop over all supplied x data, and come up with a y for each
            y = []
            for n in range(0, len(x)):
                # get a window of data around x
                if smooth:
                    [xtemp, ytemp, etemp] = _fun.trim_data(self.xdata, self.ydata, None, [x[n]-smooth, x[n]+smooth])
                else:
                    i1 = _fun.index_nearest(x[n], self.xdata)

                    # if the nearest data point is lower than x, use the next point to interpolate
                    if self.xdata[i1] <= x[n] or i1 <= 0: i2 = i1+1
                    else:                                 i2 = i1-1

                    # if we're at the max, extrapolate
                    if i2 >= len(self.xdata):
                        print(x[n], "is out of range. extrapolating")
                        i2 = i1-1

                    x1 = self.xdata[i1]
                    y1 = self.ydata[i1]
                    x2 = self.xdata[i2]
                    y2 = self.ydata[i2]
                    slope = (y2-y1)/(x2-x1)

                    xtemp = _numpy.array([x[n]])
                    ytemp = _numpy.array([y1 + (x[n]-x1)*slope])

                # calculate the slope based on xtemp and ytemp (if smoothing)
                # or just use the raw slope if smoothing=0
                if derivative == 1:
                    if smooth:
                        y.append((_numpy.average(xtemp*ytemp)-_numpy.average(xtemp)*_numpy.average(ytemp)) /
                                 (_numpy.average(xtemp*xtemp)-_numpy.average(xtemp)**2))
                    else:
                        y.append(slope)

                # otherwise just average (even with one element)
                elif derivative==0:
                    y.append(_numpy.average(ytemp))

            if is_array: return _numpy.array(y)
            else:        return y[0]

        if smooth:

            y = []
            for n in range(0, len(x)):
                # take 20 data points from x+/-smooth
                xlow = max(self.xmin,x[n]-smooth)
                xhi  = min(self.xmax,x[n]+smooth)
                xdata = _pylab.linspace(xlow, xhi, 20)
                ydata = _interpolate.splev(xdata, self.pfit, derivative)
                y.append(_numpy.average(ydata))

            if is_array: return _numpy.array(y)
            else:        return y[0]

        else:
            return _interpolate.splev(x, self.pfit, derivative)


Instruction:
Can you tell what is the following Python 3 function doing
def evaluate(self,       x, y, x_derivative=0, smooth=0, simple='auto'):

        if simple=='auto': simple = self.simple

        # find which values y is in between
        for n in range(0, len(self.y_values)-1):
            # if it's in between, interpolate!
            if self.y_values[n] <= y and self.y_values[n+1] >= y:
                y1 = self.y_values[n]
                y2 = self.y_values[n+1]
                z1 = self.x_splines[y1].evaluate(x, x_derivative, smooth, simple)
                z2 = self.x_splines[y2].evaluate(x, x_derivative, smooth, simple)
                return z1 + (y-y1)*(z2-z1)/(y2-y1)

        print("YARG! The y value "+str(y)+" is out of interpolation range!")
        if y >= self.y_values[-1]: return self.x_splines[self.y_values[-1]].evaluate(x, x_derivative, smooth, simple)
        else                     : return self.x_splines[self.y_values[0]].evaluate(x, x_derivative, smooth, simple)

Response: Evaluate the 2 - d spline by doing linear interpolation of the curves.


Instruction:
Write a Python 3 function that can
plot the data at fixed x - value so z vs x - value

Response:
def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1):
        """
        plots the data at fixed x-value, so z vs x
        """
        if simple=='auto': simple=self.simple

        # get the min and max
        if ymin=="auto": ymin = self.ymin
        if ymax=="auto": ymax = self.ymax
        if clear: _pylab.gca().clear()

        if not type(x_values) in [type([]), type(_pylab.array([]))]: x_values = [x_values]

        for x in x_values:

            # define a new simple function to plot, then plot it
            def f(y): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, ymin, ymax, steps, 0, False)

            # label it
            a = _pylab.gca()
            a.set_xlabel(self.ylabel)
            if x_derivative: a.set_ylabel(str(x_derivative)+" "+str(self.xlabel)+" derivative of "+self.zlabel)
            else:            a.set_ylabel(self.zlabel)
            a.set_title(self._path+"\nSpline array plot at fixed x = "+self.xlabel)
            a.get_lines()[-1].set_label("x ("+self.xlabel+") = "+str(x))

        if format: _s.format_figure()
        return a


Instruction:
How would you explain what the following Python 3 function does
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1):
        if simple=='auto': simple=self.simple

        # get the min and max
        if xmin=="auto": xmin = self.xmin
        if xmax=="auto": xmax = self.xmax
        if clear: _pylab.gca().clear()

        if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values]

        for y in y_values:
            # define a new simple function to plot, then plot it
            def f(x): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, xmin, xmax, steps, 0, True)

            # label it
            a = _pylab.gca()
            th = "th"
            if x_derivative == 1: th = "st"
            if x_derivative == 2: th = "nd"
            if x_derivative == 3: th = "rd"
            if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline")
            else:            a.set_ylabel(self.zlabel)
            a.set_xlabel(self.xlabel)
            a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel)
            a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y))
        if format: _s.format_figure()
        return a

Response: Plots the data at a fixed y - value so z vs y - values.


Instruction:
How would you code a function in Python 3 to
return the object s parent window. Returns None if no parent window is found.

Response:
def get_window(self):
        """
        Returns the object's parent window. Returns None if no window found.
        """
        x = self
        while not x._parent == None and \
              not isinstance(x._parent, Window):
                  x = x._parent
        return x._parent


Instruction:
Make a summary of the following Python 3 code
def sleep(self, seconds=0.05, dt=0.01):
        t0 = _t.time()
        while _t.time()-t0 < seconds:

            # Pause a bit to avoid heavy CPU
            _t.sleep(dt)

            # process events
            self.process_events()

Response: A smooth version of time. sleep that will pause for the specified amount of time.


Instruction:
Write a Python 3 function that can
prevent the widget from sending events.

Response:
def block_events(self):
        """
        Prevents the widget from sending signals.
        """
        self._widget.blockSignals(True)
        self._widget.setUpdatesEnabled(False)


Instruction:
Implement a Python 3 function for
unblocking the events from being processed.

Response:
def unblock_events(self):
        """
        Allows the widget to send signals.
        """
        self._widget.blockSignals(False)
        self._widget.setUpdatesEnabled(True)


Instruction:
Create a Python 3 function to
print a message to the log.

Response:
def print_message(self, message="heya!"):
        """
        If self.log is defined to be an instance of TextLog, it print the
        message there. Otherwise use the usual "print" to command line.
        """
        if self.log == None: print(message)
        else:                self.log.append_text(message)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def save_gui_settings(self, *a):

        # only if we're supposed to!
        if self._autosettings_path:

            # Get the gui settings directory
            gui_settings_dir = _os.path.join(_cwd, 'egg_settings')

            # make sure the directory exists
            if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)

            # make a path with a sub-directory
            path = _os.path.join(gui_settings_dir, self._autosettings_path)

            # for saving header info
            d = _d.databox()

            # add all the controls settings
            for x in self._autosettings_controls: self._store_gui_setting(d, x)

            # save the file
            d.save_file(path, force_overwrite=True)

Response: Save the current configuration of the controls and header info of the current header of the controls.


Instruction:
Write a Python 3 function for
loading the settings from the main gui and updates the value of the current object.

Response:
def load_gui_settings(self, lazy_only=False):
        """
        Loads the settings (if we're supposed to).

        Parameters
        ----------
        lazy_only=False
            If True, it will only load the settings into self._lazy_load, and
            not try to update the value. Presumably the widget will apply these
            settings later, e.g., when enough tabs exist to set the current
            tab in TabArea.
        """

        # only do this if we're supposed to
        if self._autosettings_path is not None:

            # Get the gui settings directory
            gui_settings_dir = _os.path.join(_cwd, 'egg_settings')

            # assemble the path with a sub-directory
            path = _os.path.join(gui_settings_dir, self._autosettings_path)

            # databox just for loading a cfg file
            d = _d.databox()

            # if the settings path exists
            if _os.path.exists(path):

                # Load the settings
                d.load_file(path, header_only=True, quiet=True)

                # Store the settings in the lazy dictionary
                self._lazy_load.update(d.headers)

                # Loop over the settings we're supposed to change
                # Note without specifying d, this will try to pop
                # the value off of self._lazy_load. If
                #
                if not lazy_only:
                    for x in self._autosettings_controls:
                        self._load_gui_setting(x)


Instruction:
Explain what the following Python 3 code does
def _load_gui_setting(self, key, d=None):
        # Whether we should pop the value from the dictionary when we set it.
        pop_value = False

        # If d is None, assume we're using the lazy load settings.
        if d == None:
            d = self._lazy_load
            pop_value = True

        # If we have a databox, take the header dictionary
        if not type(d) == dict: d = d.headers

        # only do this if the key exists
        if key in d:

            try:
                # Try to set the value
                eval(key).set_value(d[key])

                # If this fails, perhaps the element does not yet exist
                # For example, TabArea may not have all the tabs created
                # and cannot set the active tab until later.
                # If it's here, it worked, so pop if necessary
                if pop_value: d.pop(key)

            except:
                print("ERROR: Could not load gui setting "+repr(key))

Response: Loads the appropriate control - related settings from the GUI.


Instruction:
Here you have a function in Python 3, explain what it does
def _store_gui_setting(self, databox, name):
        try:    databox.insert_header(name, eval(name + ".get_value()"))
        except: print("ERROR: Could not store gui setting "+repr(name))

Response: Store the gui setting in the header of the databox


Instruction:
Can you generate the documentation for the following Python 3 function
def place_object(self, object, column=None, row=None, column_span=1, row_span=1, alignment=1):

        # pick a column
        if column==None:
            column = self._auto_column
            self._auto_column += 1

        # pick a row
        if row==None: row = self._auto_row

        # create the object
        self.objects.append(object)

        # add the widget to the layout
        try:
            object._widget
            widget = object._widget

        # allows the user to specify a standard widget
        except: widget = object

        self._layout.addWidget(widget, row, column,
                               row_span, column_span,
                               _g.Qt.QtCore.Qt.Alignment(alignment))

        # try to store the parent object (self) in the placed object
        try:    object.set_parent(self)
        except: None

        return object

Response: Adds an object to the grid at the specified position.


Instruction:
Can you implement a function in Python 3 that
removes the supplied object from the grid.

Response:
def remove_object(self, object=0, delete=True):
        """
        Removes the supplied object from the grid. If object is an integer,
        it removes the n'th object.
        """
        if type(object) in [int, int]: n = object
        else:                           n = self.objects.index(object)

        # pop it from the list
        object = self.objects.pop(n)

        # remove it from the GUI and delete it
        if hasattr_safe(object, '_widget'):
            self._layout.removeWidget(object._widget)
            object._widget.hide()
            if delete: object._widget.deleteLater()
        else:
            self._layout.removeWidget(object)
            object.hide()
            if delete: object.deleteLater()


Instruction:
Here you have a function in Python 3, explain what it does
def new_autorow(self, row=None):
        if row==None: self._auto_row += 1
        else:         self._auto_row = row

        self._auto_column=0
        return self

Response: Sets the auto - add row and column.


Instruction:
Can you tell what is the following Python 3 function doing
def place_docker(self, docker, area='top'):
        # map of options
        m = dict(top    = _g.QtCore.Qt.TopDockWidgetArea,
                 bottom = _g.QtCore.Qt.BottomDockWidgetArea,
                 left   = _g.QtCore.Qt.LeftDockWidgetArea,
                 right  = _g.QtCore.Qt.RightDockWidgetArea)

        # set the parent
        docker.set_parent(self)

        # events
        docker._window.resizeEvent = self._event_resize
        docker._window.moveEvent   = self._event_move

        # Keep it in the window
        docker._window.setFeatures(docker._window.DockWidgetMovable)

        # set it
        self._window.addDockWidget(m[area], docker._window)

        return docker

Response: Places a Docker instance at the specified area.


Instruction:
Given the following Python 3 function, write the documentation
def _save_settings(self):
        if self._autosettings_path == None: return

        # Get the gui settings directory
        gui_settings_dir = _os.path.join(_cwd, 'egg_settings')

        # make sure the directory exists
        if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)

        # make a path with a sub-directory
        path = _os.path.join(gui_settings_dir, self._autosettings_path)

        # Create a Qt settings object
        settings = _g.QtCore.QSettings(path, _g.QtCore.QSettings.IniFormat)
        settings.clear()

        # Save values
        if hasattr_safe(self._window, "saveState"):
            settings.setValue('State',self._window.saveState())
        settings.setValue('Geometry', self._window.saveGeometry())

Response: Saves all the parameters to a text file.


Instruction:
Can you generate the documentation for the following Python 3 function
def _load_settings(self):
        if self._autosettings_path == None: return

        # Get the gui settings directory
        gui_settings_dir = _os.path.join(_cwd, 'egg_settings')

        # make a path with a sub-directory
        path = _os.path.join(gui_settings_dir, self._autosettings_path)

        # make sure the directory exists
        if not _os.path.exists(path): return

        # Create a Qt settings object
        settings = _g.QtCore.QSettings(path, _g.QtCore.QSettings.IniFormat)

        # Load it up! (Extra steps required for windows command line execution)
        if settings.contains('State') and hasattr_safe(self._window, "restoreState"):
            x = settings.value('State')
            if hasattr(x, "toByteArray"): x = x.toByteArray()
            self._window.restoreState(x)

        if settings.contains('Geometry'):
            x = settings.value('Geometry')
            if hasattr(x, "toByteArray"): x = x.toByteArray()
            self._window.restoreGeometry(x)

Response: Loads all the parameters from a databox text file. If path = None loads all the parameters from self. _autosettings_path. If path = None loads all the parameters from self. _autosettings_path.


Instruction:
Given the following Python 3 function, write the documentation
def show(self, block_command_line=False, block_timing=0.05):

        self._is_open = True
        self._window.show()
        self._window.raise_()

        # start the blocking loop
        if block_command_line:

            # stop when the window closes
            while self._is_open:
                _a.processEvents()
                _t.sleep(block_timing)

            # wait a moment in case there is some shutdown stuff.
            _t.sleep(0.5)

        return self

Response: Shows the window and raises it.


Instruction:
Here you have a function in Python 3, explain what it does
def set_checked(self, value=True, block_events=False):
        if block_events: self._widget.blockSignals(True)
        self._widget.setChecked(value)
        if block_events: self._widget.blockSignals(False)

        return self

Response: Sets the button is checked.


Instruction:
Explain what the following Python 3 code does
def click(self):
        if self.is_checkable():
            if self.is_checked(): self.set_checked(False)
            else:                 self.set_checked(True)
            self.signal_clicked.emit(self.is_checked())
        else:
            self.signal_clicked.emit(True)
        return self

Response: Sends the signal that the user clicked it sending the signal and everything.


Instruction:
Can you write a function in Python 3 where it
sets the style of the label for the given object.

Response:
def set_style(self, *args, **kwargs):
        """
        Provides access to any number of style sheet settings via
        self._widget.SetStyleSheet()

        *args can be any element between semicolons, e.g.
            self.set_stylesheet('text-align: right; padding-left: 5px')

        **kwargs can be any key-value pair, replacing '-' with '_' in the key, e.g.
            self.set_stylesheet(text_align='right', padding_left='5px')

        See QLabel.SetStyleSheet() documentation.
        """
        # assemble the string
        s = "QLabel {"
        for a in args:          s = s+a+"; "
        for k in list(kwargs.keys()): s = s+k.replace("_","-")+": "+kwargs[k]+"; "
        s = s+"}"

        # set it!
        self._widget.setStyleSheet(s)
        return self


Instruction:
Make a summary of the following Python 3 code
def set_value(self, value, block_events=False):
        if block_events: self.block_events()
        self._widget.setValue(value)
        if block_events: self.unblock_events()

Response: Sets the current value of the number box.


Instruction:
Implement a Python 3 function for
setting the step of the number box.

Response:
def set_step(self, value, block_events=False):
        """
        Sets the step of the number box.

        Setting block_events=True will temporarily block the widget from
        sending any signals when setting the value.
        """
        if block_events: self.block_events()
        self._widget.setSingleStep(value)
        if block_events: self.unblock_events()


Instruction:
Create a Python 3 function to
get the text from a given index.

Response:
def get_text(self, index=None):
        """
        Gets text from a given index. If index=None, returns the current value
        self.get_text(self.get_value())
        """
        if index==None:
            return self.get_text(self.get_value())
        else:
            return str(self._widget.itemText(index))


Instruction:
Given the following Python 3 function, write the documentation
def get_all_items(self):
        return [self._widget.itemText(k) for k in range(self._widget.count())]

Response: Returns all items in the combobox dictionary.


Instruction:
Write a Python 3 script for
adding a tab to the area and creates the layout for this tab.

Response:
def add_tab(self, title="Yeah!", block_events=True):
        """
        Adds a tab to the area, and creates the layout for this tab.
        """
        self._widget.blockSignals(block_events)

        # create a widget to go in the tab
        tab = GridLayout()
        self.tabs.append(tab)
        tab.set_parent(self)

        # create and append the tab to the list
        self._widget.addTab(tab._widget, title)

        # try to lazy set the current tab
        if 'self' in self._lazy_load and self.get_tab_count() > self._lazy_load['self']:
            v = self._lazy_load.pop('self')
            self.set_current_tab(v)

        self._widget.blockSignals(False)

        return tab


Instruction:
Make a summary of the following Python 3 code
def remove_tab(self, tab=0):

        # pop it from the list
        t = self.tabs.pop(tab)

        # remove it from the gui
        self._widget.removeTab(tab)

        # return it in case someone cares
        return t

Response: Removes the tab by index.


Instruction:
Create a Python 3 function to
return a the value at column row.

Response:
def get_value(self, column=0, row=0):
        """
        Returns a the value at column, row.
        """
        x = self._widget.item(row, column)

        if x==None: return x
        else:       return str(self._widget.item(row,column).text())


Instruction:
Write a Python 3 script for
setting the value at column row.

Response:
def set_value(self, column=0, row=0, value='', block_events=False):
        """
        Sets the value at column, row. This will create elements dynamically,
        and in a totally stupid while-looping way.

        Setting block_events=True will temporarily block the widget from
        sending any signals when setting the value.
        """

        if block_events: self.block_events()

        # dynamically resize
        while column > self._widget.columnCount()-1: self._widget.insertColumn(self._widget.columnCount())
        while row    > self._widget.rowCount()   -1: self._widget.insertRow(   self._widget.rowCount())

        # set the value
        self._widget.setItem(row, column, _g.Qt.QtGui.QTableWidgetItem(str(value)))

        if block_events: self.unblock_events()

        return self


Instruction:
Can you create a Python 3 function that
sets then'th column width in pixels.

Response:
def set_column_width(self, n=0, width=120):
        """
        Sets the n'th column width in pixels.
        """
        self._widget.setColumnWidth(n, width)
        return self


Instruction:
Explain what the following Python 3 code does
def set_header_visibility(self, column=False, row=False):
        if row:    self._widget.verticalHeader().show()
        else:      self._widget.verticalHeader().hide()

        if column: self._widget.horizontalHeader().show()
        else:      self._widget.horizontalHeader().hide()

        return self

Response: Sets whether we can see the column and row headers.


Instruction:
Implement a function in Python 3 to
set then'th row height in pixels.

Response:
def set_row_height(self, n=0, height=18):
        """
        Sets the n'th row height in pixels.
        """
        self._widget.setRowHeight(n, height)
        return self


Instruction:
Explain what the following Python 3 code does
def _clean_up_key(self, key):
        for n in self.naughty: key = key.replace(n, '_')
        return key

Response: Clean up the key string with no naughty characters.


Instruction:
Can you implement a function in Python 3 that
calls when a cell is changed. Updates the dictionary.

Response:
def _cell_changed(self, *a):
        """
        Called whenever a cell is changed. Updates the dictionary.
        """

        # block all signals during the update (to avoid re-calling this)
        self.block_events()

        # loop over the rows
        for n in range(self.get_row_count()):

            # get the keys and values (as text)
            key   = self.get_value(0,n)
            value = self.get_value(1,n)

            # get rid of the None's
            if key   == None:
                key = ''
                self.set_value(0,n, '')
            if value == None:
                value = ''
                self.set_value(1,n, '')

            # if it's not an empty entry make sure it's valid
            if not key == '':

                # clean up the key
                key = self._clean_up_key(key)

                # now make sure the value is python-able
                try:
                    eval(value)
                    self._widget.item(n,1).setData(_g.QtCore.Qt.BackgroundRole, _g.Qt.QtGui.QColor('white'))
                except:
                    self._widget.item(n,1).setData(_g.QtCore.Qt.BackgroundRole, _g.Qt.QtGui.QColor('pink'))

        # unblock all signals
        self.unblock_events()


Instruction:
Make a summary of the following Python 3 code
def get_item(self, key):
        keys = list(self.keys())

        # make sure it exists
        if not key in keys:
            self.print_message("ERROR: '"+str(key)+"' not found.")
            return None

        try:
            x = eval(self.get_value(1,keys.index(key)))
            return x

        except:
            self.print_message("ERROR: '"+str(self.get_value(1,keys.index(key)))+"' cannot be evaluated.")
            return None

Response: Returns the value associated with the key.


Instruction:
Here you have a function in Python 3, explain what it does
def keys(self):
        keys = list()
        for n in range(len(self)):

            # only append the valid keys
            key = self.get_value()
            if not key in ['', None]: keys.append(key)

        return keys

Response: Returns a sorted list of keys


Instruction:
How would you explain what the following Python 3 function does
def set_item(self, key, value):
        keys = list(self.keys())

        # if it exists, update
        if key in keys:
            self.set_value(1,keys.index(key),str(value))

        # otherwise we have to add an element
        else:
            self.set_value(0,len(self),   str(key))
            self.set_value(1,len(self)-1, str(value))

Response: Sets the item by key and refills the table sorted.


Instruction:
Write a Python 3 function that can
update the dictionary with the values from kwargs.

Response:
def update(self, dictionary=None, **kwargs):
        """
        Adds/overwrites all the keys and values from the dictionary.
        """
        if not dictionary == None: kwargs.update(dictionary)
        for k in list(kwargs.keys()): self[k] = kwargs[k]


Instruction:
How would you explain what the following Python 3 function does
def get_text(self):
        if self._multiline: return str(self._widget.toPlainText())
        else:               return str(self._widget.text())

Response: Returns the current text.


Instruction:
Here you have a function in Python 3, explain what it does
def set_text(self, text="YEAH."):
        # Make sure the text is actually different, so as not to
        # trigger a value changed signal
        s = str(text)
        if not s == self.get_text(): self._widget.setText(str(text))
        return self

Response: Sets the text of the text box.


Instruction:
Create a Python 3 function to
set the colors of the text area.

Response:
def set_colors(self, text='black', background='white'):
        """
        Sets the colors of the text area.
        """
        if self._multiline: self._widget.setStyleSheet("QTextEdit {background-color: "+str(background)+"; color: "+str(text)+"}")
        else:               self._widget.setStyleSheet("QLineEdit {background-color: "+str(background)+"; color: "+str(text)+"}")


Instruction:
Here you have a function in Python 3, explain what it does
def block_events(self):
        # block events in the usual way
        BaseObject.block_events(self)

        # loop over all top level parameters
        for i in range(self._widget.topLevelItemCount()):
            self._widget.topLevelItem(i).param.blockSignals(True)

        return self

Response: Block all tree elements and parameters in the tree.


Instruction:
Write a Python 3 function that can
unblock all events in the tree.

Response:
def unblock_events(self):
        """
        Special version of unblock_events that loops over all tree elements as well.
        """
        # unblock events in the usual way
        BaseObject.unblock_events(self)

        # loop over all top level parameters
        for i in range(self._widget.topLevelItemCount()):
            self._widget.topLevelItem(i).param.blockSignals(False)

        return self


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

        # loop over all top level parameters
        for i in range(self._widget.topLevelItemCount()):

            # make sure there is only one connection!
            try:
                self._widget.topLevelItem(i).param.sigTreeStateChanged.connect(
                                  function, type=_g.QtCore.Qt.UniqueConnection)
            except:
                pass

        return self

Response: Connects the anything changed signal to all of the tree items.


Instruction:
Can you create a Python 3 function that
connects a changed signal from the parameters of the specified name to the supplied function.

Response:
def connect_signal_changed(self, name, function):
        """
        Connects a changed signal from the parameters of the specified name
        to the supplied function.
        """
        x = self._find_parameter(name.split("/"))

        # if it pooped.
        if x==None: return None

        # connect it
        x.sigValueChanged.connect(function)

        # Keep track of the functions
        if name in self._connection_lists: self._connection_lists[name].append(function)
        else:                              self._connection_lists[name] = [function]

        return self


Instruction:
Make a summary of the following Python 3 code
def block_user_signals(self, name, ignore_error=False):
        x = self._find_parameter(name.split("/"), quiet=ignore_error)

        # if it pooped.
        if x==None: return None

        # disconnect it from all its functions
        if name in self._connection_lists:
            for f in self._connection_lists[name]: x.sigValueChanged.disconnect(f)

        return self

Response: Disconnects all user - defined signals for the specified parameter name.


Instruction:
Here you have a function in Python 3, explain what it does
def unblock_user_signals(self, name, ignore_error=False):
        x = self._find_parameter(name.split("/"), quiet=ignore_error)

        # if it pooped.
        if x==None: return None

        # reconnect it to all its functions
        if name in self._connection_lists:
            for f in self._connection_lists[name]: x.sigValueChanged.connect(f)

        return self

Response:
Unblock the user - defined signals for the specified
        parameter name.


Instruction:
Here you have a function in Python 3, explain what it does
def _find_parameter(self, name_list, create_missing=False, quiet=False):
        # make a copy so this isn't destructive to the supplied list
        s = list(name_list)

        # if the length is zero, return the root widget
        if len(s)==0: return self._widget

        # the first name must be treated differently because it is
        # the main widget, not a branch
        r = self._clean_up_name(s.pop(0))

        # search for the root name
        result = self._widget.findItems(r, _g.QtCore.Qt.MatchCaseSensitive | _g.QtCore.Qt.MatchFixedString)

        # if it pooped and we're not supposed to create it, quit
        if len(result) == 0 and not create_missing:
            if not quiet: self.print_message("ERROR: Could not find '"+r+"'")
            return None

        # otherwise use the first value
        elif len(result): x = result[0].param

        # otherwise, if there are more names in the list,
        # create the branch and keep going
        else:
            x = _g.parametertree.Parameter.create(name=r, type='group', children=[])
            self._widget.addParameters(x)

        # loop over the remaining names, and use a different search method
        for n in s:

            # first clean up
            n = self._clean_up_name(n)

            # try to search for the name
            try: x = x.param(n)

            # name doesn't exist
            except:

                # if we're supposed to, create the new branch
                if create_missing: x = x.addChild(_g.parametertree.Parameter.create(name=n, type='group', children=[]))

                # otherwise poop out
                else:
                    if not quiet: self.print_message("ERROR: Could not find '"+n+"' in '"+x.name()+"'")
                    return None

        # return the last one we found / created.
        return x

Response: Tries to find and return the parameter of the specified name.


Instruction:
Can you generate the documentation for the following Python 3 function
def _clean_up_name(self, name):
        for n in self.naughty: name = name.replace(n, '_')
        return name

Response:
Cleans up the name according to the rules specified in this exact
        function.


Instruction:
How would you explain what the following Python 3 function does
def add_button(self, name, checkable=False, checked=False):

        # first clean up the name
        name = self._clean_up_name(name)

        # split into (presumably existing) branches and parameter
        s = name.split('/')

        # make sure it doesn't already exist
        if not self._find_parameter(s, quiet=True) == None:
            self.print_message("Error: '"+name+"' already exists.")
            return None

        # get the leaf name off the list.
        p = s.pop(-1)

        # create / get the branch on which to add the leaf
        b = self._find_parameter(s, create_missing=True)

        # quit out if it pooped
        if b == None: return None

        # create the leaf object
        ap = _g.parametertree.Parameter.create(name=p, type='action')

        # add it to the tree (different methods for root)
        if b == self._widget: b.addParameters(ap)
        else:                 b.addChild(ap)

        # modify the existing class to fit our conventions
        ap.signal_clicked = ap.sigActivated

        # Now set the default value if any
        if name in self._lazy_load:
            v = self._lazy_load.pop(name)
            self._set_value_safe(name, v, True, True)

        # Connect it to autosave (will only create unique connections)
        self.connect_any_signal_changed(self.autosave)

        return Button(name, checkable, checked, list(ap.items.keys())[0].button)

Response: Adds a button at the specified location.


Instruction:
How would you implement a function in Python 3 that
adds a parameter to the tree.

Response:
def add_parameter(self, name='test', value=42.0, **kwargs):
        """
        Adds a parameter "leaf" to the tree.

        Parameters
        ----------
        name='test'
            The name of the leaf. It should be a string of the form
            "branch1/branch2/parametername" and will be nested as indicated.
        value=42.0
            Value of the leaf.

        Common Keyword Arguments
        ------------------------
        type=None
            If set to None, type will be automatically set to type(value).__name__.
            This will not work for all data types, but is
            a nice shortcut for floats, ints, strings, etc.
            If it doesn't work, just specify the type manually (see below).
        values
            Not used by default. Only relevant for 'list' type, and should then
            be a list of possible values.
        step=1
            Step size of incrementing numbers
        dec=False
            Set to True to enable decade increments.
        limits
            Not used by default. Should be a 2-element tuple or list used to
            bound numerical values.
        default
            Not used by default. Used to specify the default numerical value
        siPrefix=False
            Set to True to display units on numbers
        suffix
            Not used by default. Used to add unit labels to elements.

        See pyqtgraph ParameterTree for more options. Particularly useful is the
        tip='insert your text' option, which supplies a tooltip!
        """

        # update the default kwargs
        other_kwargs = dict(type=None)
        other_kwargs.update(kwargs)

        # Auto typing
        if other_kwargs['type'] == None: other_kwargs['type'] = type(value).__name__

        # Fix 'values' for list objects to be only strings
        if other_kwargs['type'] == 'list':
            for n in range(len(other_kwargs['values'])):
                other_kwargs['values'][n] = str(other_kwargs['values'][n])

        # split into (presumably existing) branches and parameter
        s = name.split('/')

        # make sure it doesn't already exist
        if not self._find_parameter(s, quiet=True) == None:
            self.print_message("Error: '"+name+"' already exists.")
            return self

        # get the leaf name off the list.
        p = s.pop(-1)

        # create / get the branch on which to add the leaf
        b = self._find_parameter(s, create_missing=True)

        # quit out if it pooped
        if b == None: return self

        # create the leaf object
        leaf = _g.parametertree.Parameter.create(name=p, value=value, **other_kwargs)

        # add it to the tree (different methods for root)
        if b == self._widget: b.addParameters(leaf)
        else:                 b.addChild(leaf)

        # Now set the default value if any
        if name in self._lazy_load:
            v = self._lazy_load.pop(name)
            self._set_value_safe(name, v, True, True)

        # Connect it to autosave (will only create unique connections)
        self.connect_any_signal_changed(self.autosave)
        return self


Instruction:
Can you tell what is the following Python 3 function doing
def _get_parameter_dictionary(self, base_name, dictionary, sorted_keys, parameter):

        # assemble the key for this parameter
        k = base_name + "/" + parameter.name()

        # first add this parameter (if it has a value)
        if not parameter.value()==None:
            sorted_keys.append(k[1:])
            dictionary[sorted_keys[-1]] = parameter.value()

        # now loop over the children
        for p in parameter.children():
            self._get_parameter_dictionary(k, dictionary, sorted_keys, p)

Response: Recursively loops over the parameter s children adding the base_name and values to the supplied dictionary.


Instruction:
Here you have a function in Python 3, explain what it does
def send_to_databox_header(self, destination_databox):
        k, d = self.get_dictionary()
        destination_databox.update_headers(d,k)

Response: Sends all the information currently in the tree to the supplied databox s header in alphabetical order.


Instruction:
Write a Python 3 script for
returning the list of parameters and a dictionary of values

Response:
def get_dictionary(self):
        """
        Returns the list of parameters and a dictionary of values
        (good for writing to a databox header!)

        Return format is sorted_keys, dictionary
        """

        # output
        k = list()
        d = dict()

        # loop over the root items
        for i in range(self._widget.topLevelItemCount()):

            # grab the parameter item, and start building the name
            x = self._widget.topLevelItem(i).param

            # now start the recursive loop
            self._get_parameter_dictionary('', d, k, x)

        return k, d


Instruction:
Can you create a Python 3 function that
returns the value of the parameter with the specified name.

Response:
def get_value(self, name):
        """
        Returns the value of the parameter with the specified name.
        """
        # first clean up the name
        name = self._clean_up_name(name)

        # now get the parameter object
        x = self._find_parameter(name.split('/'))

        # quit if it pooped.
        if x == None: return None

        # get the value and test the bounds
        value  = x.value()

        # handles the two versions of pyqtgraph
        bounds = None

        # For lists, just make sure it's a valid value
        if x.opts['type'] == 'list':

            # If it's not one from the master list, choose
            # and return the default value.
            if not value in x.opts['values']:

                # Only choose a default if there exists one
                if len(x.opts('values')):
                    self.set_value(name, x.opts['values'][0])
                    return x.opts['values'][0]

                # Otherwise, just return None and do nothing
                else: return None

        # For strings, make sure the returned value is always a string.
        elif x.opts['type'] in ['str']: return str(value)

        # Otherwise assume it is a value with bounds or limits (depending on
        # the version of pyqtgraph)
        else:
            if   'limits' in x.opts: bounds = x.opts['limits']
            elif 'bounds' in x.opts: bounds = x.opts['bounds']
            if not bounds == None:
                if not bounds[1]==None and value > bounds[1]: value = bounds[1]
                if not bounds[0]==None and value < bounds[0]: value = bounds[0]

        # return it
        return value


Instruction:
Explain what the following Python 3 code does
def get_list_values(self, name):
        # Make sure it's a list
        if not self.get_type(name) in ['list']:
            self.print_message('ERROR: "'+name+'" is not a list.')
            return

        # Return a copy of the list values
        return list(self.get_widget(name).opts['values'])

Response: Returns the list values for a list item of the specified name.


Instruction:
Given the following Python 3 function, write the documentation
def set_value(self, name, value, ignore_error=False, block_user_signals=False):
        # first clean up the name
        name = self._clean_up_name(name)

        # If we're supposed to, block the user signals for this parameter
        if block_user_signals: self.block_user_signals(name, ignore_error)

        # now get the parameter object
        x = self._find_parameter(name.split('/'), quiet=ignore_error)

        # quit if it pooped.
        if x == None: return None

        # for lists, make sure the value exists!!
        if x.type() in ['list']:

            # Make sure it exists before trying to set it
            if str(value) in list(x.forward.keys()): x.setValue(str(value))

            # Otherwise default to the first key
            else: x.setValue(list(x.forward.keys())[0])

        # Bail to a hopeful set method for other types
        else: x.setValue(eval(x.opts['type'])(value))

        # If we're supposed to unblock the user signals for this parameter
        if block_user_signals: self.unblock_user_signals(name, ignore_error)

        return self

Response: Sets the value of the supplied parameter name to the supplied value.


Instruction:
Can you generate the documentation for the following Python 3 function
def save(self, path=None):
        if path==None:

            if self._autosettings_path == None: return self

            # Get the gui settings directory
            gui_settings_dir = _os.path.join(_cwd, 'egg_settings')

            # make sure the directory exists
            if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)

            # Assemble the path
            path = _os.path.join(gui_settings_dir, self._autosettings_path)

        # make the databox object
        d = _d.databox()

        # get the keys and dictionary
        keys, dictionary = self.get_dictionary()

        # loop over the keys and add them to the databox header
        for k in keys:
            d.insert_header(k, dictionary[k])

        # save it
        try:
            d.save_file(path, force_overwrite=True, header_only=True)
        except:
            print('Warning: could not save '+path.__repr__()+' once. Could be that this is being called too rapidly.')

        return self

Response:
Saves all the parameters to a text file using the databox
            functionality.


Instruction:
Given the following Python 3 function, write the documentation
def _set_value_safe(self, k, v, ignore_errors=False, block_user_signals=False):
        # for safety: by default assume it's a repr() with python code
        try:
            self.set_value(k, v, ignore_error       = ignore_errors,
                                 block_user_signals = block_user_signals)

        except:
            print("TreeDictionary ERROR: Could not set '"+k+"' to '"+v+"'")

Response: Set the value of a key to a value.


Instruction:
Implement a function in Python 3 to
call when the button is clicked.

Response:
def _button_autosave_clicked(self, checked):
        """
        Called whenever the button is clicked.
        """
        if checked:
            # get the path from the user
            path = _spinmob.dialogs.save(filters=self.file_type)

            # abort if necessary
            if not path:
                self.button_autosave.set_checked(False)
                return

            # otherwise, save the info!
            self._autosave_directory, filename = _os.path.split(path)
            self._label_path.set_text(filename)

        self.save_gui_settings()


Instruction:
Here you have a function in Python 3, explain what it does
def save_file(self, path=None, force_overwrite=False, just_settings=False, **kwargs):
        # Update the binary mode
        if not 'binary' in kwargs: kwargs['binary'] = self.combo_binary.get_text()

        # if it's just the settings file, make a new databox
        if just_settings: d = _d.databox()

        # otherwise use the internal databox
        else: d = self

        # add all the controls settings to the header
        for x in self._autosettings_controls: self._store_gui_setting(d, x)

        # save the file using the skeleton function, so as not to recursively
        # call this one again!
        _d.databox.save_file(d, path, self.file_type, self.file_type, force_overwrite, **kwargs)

Response: Save the data in the databox to a file.


Instruction:
Given the following Python 3 function, write the documentation
def load_file(self, path=None, just_settings=False):
        # if it's just the settings file, make a new databox
        if just_settings:
            d = _d.databox()
            header_only = True

        # otherwise use the internal databox
        else:
            d = self
            header_only = False

        # import the settings if they exist in the header
        if not None == _d.databox.load_file(d, path, filters=self.file_type, header_only=header_only, quiet=just_settings):

            # loop over the autosettings and update the gui
            for x in self._autosettings_controls: self._load_gui_setting(x,d)

        # always sync the internal data
        self._synchronize_controls()

        # plot the data if this isn't just a settings load
        if not just_settings:
            self.plot()
            self.after_load_file()

Response: Loads a data file and updates the internal data and the GUI.


Instruction:
Write a Python 3 function for
generating a python script for plotting the current object.

Response:
def _autoscript(self):
        """
        Automatically generates a python script for plotting.
        """
        # This should never happen unless I screwed up.
        if self.combo_autoscript.get_index() == 0: return "ERROR: Ask Jack."

        # if there is no data, leave it blank
        if   len(self)==0: return "x = []; y = []; xlabels=[]; ylabels=[]"

        # if there is one column, make up a one-column script
        elif len(self)==1: return "x = [None]\ny = [ d[0] ]\n\nxlabels=[ 'Data Point' ]\nylabels=[ 'd[0]' ]"

        # Shared x-axis (column 0)
        elif self.combo_autoscript.get_index() == 1:

            # hard code the first columns
            sx = "x = [ d[0]"
            sy = "y = [ d[1]"

            # hard code the first labels
            sxlabels = "xlabels = '" +self.ckeys[0]+"'"
            sylabels = "ylabels = [ '"+self.ckeys[1]+"'"

            # loop over any remaining columns and append.
            for n in range(2,len(self)):
                sy += ", d["+str(n)+"]"
                sylabels += ", '"+self.ckeys[n]+"'"

            return sx+" ]\n"+sy+" ]\n\n"+sxlabels+"\n"+sylabels+" ]\n"

        # Column pairs
        elif self.combo_autoscript.get_index() == 2:

            # hard code the first columns
            sx = "x = [ d[0]"
            sy = "y = [ d[1]"

            # hard code the first labels
            sxlabels = "xlabels = [ '"+self.ckeys[0]+"'"
            sylabels = "ylabels = [ '"+self.ckeys[1]+"'"

            # Loop over the remaining columns and append
            for n in range(1,int(len(self)/2)):
                sx += ", d["+str(2*n  )+"]"
                sy += ", d["+str(2*n+1)+"]"
                sxlabels += ", '"+self.ckeys[2*n  ]+"'"
                sylabels += ", '"+self.ckeys[2*n+1]+"'"

            return sx+" ]\n"+sy+" ]\n\n"+sxlabels+" ]\n"+sylabels+" ]\n"
            print("test")

        # Column triples
        elif self.combo_autoscript.get_index() == 3:

            # hard code the first columns
            sx = "x = [ d[0], d[0]"
            sy = "y = [ d[1], d[2]"

            # hard code the first labels
            sxlabels = "xlabels = [ '"+self.ckeys[0]+"', '"+self.ckeys[0]+"'"
            sylabels = "ylabels = [ '"+self.ckeys[1]+"', '"+self.ckeys[2]+"'"

            # Loop over the remaining columns and append
            for n in range(1,int(len(self)/3)):
                sx += ", d["+str(3*n  )+"], d["+str(3*n  )+"]"
                sy += ", d["+str(3*n+1)+"], d["+str(3*n+2)+"]"

                sxlabels += ", '"+self.ckeys[3*n  ]+"', '"+self.ckeys[3*n  ]+"'"
                sylabels += ", '"+self.ckeys[3*n+1]+"', '"+self.ckeys[3*n+2]+"'"

            return sx+" ]\n"+sy+" ]\n\n"+sxlabels+" ]\n"+sylabels+" ]\n"

        else: return self.autoscript_custom()


Instruction:
Can you write a function in Python 3 where it
plots the internal databox.

Response:
def plot(self):
        """
        Sets the internal databox to the supplied value and plots it.
        If databox=None, this will plot the internal databox.
        """

        # if we're disabled or have no data columns, clear everything!
        if not self.button_enabled.is_checked() or len(self) == 0:
            self._set_number_of_plots(0)
            return self

        # if there is no script, create a default
        if not self.combo_autoscript.get_index()==0:
            self.script.set_text(self._autoscript())

        ##### Try the script and make the curves / plots match

        try:
            # get globals for sin, cos etc
            g = _n.__dict__
            g.update(dict(d=self))
            g.update(dict(xlabels='x', ylabels='y'))

            # run the script.
            exec(self.script.get_text(), g)

            # x & y should now be data arrays, lists of data arrays or Nones
            x = g['x']
            y = g['y']

            # make it the right shape
            if x == None: x = [None]
            if y == None: y = [None]
            if not _spinmob.fun.is_iterable(x[0]) and not x[0] == None: x = [x]
            if not _spinmob.fun.is_iterable(y[0]) and not y[0] == None: y = [y]
            if len(x) == 1 and not len(y) == 1: x = x*len(y)
            if len(y) == 1 and not len(x) == 1: y = y*len(x)

            # xlabels and ylabels should be strings or lists of strings
            xlabels = g['xlabels']
            ylabels = g['ylabels']

            # make sure we have exactly the right number of plots
            self._set_number_of_plots(len(x))
            self._update_linked_axes()

            # return if there is nothing.
            if len(x) == 0: return

            # now plot everything
            for n in range(max(len(x),len(y))-1,-1,-1):

                # Create data for "None" cases.
                if x[n] is None: x[n] = list(range(len(y[n])))
                if y[n] is None: y[n] = list(range(len(x[n])))
                self._curves[n].setData(x[n],y[n])

                # get the labels for the curves

                # if it's a string, use the same label for all axes
                if type(xlabels) in [str,type(None)]: xlabel = xlabels
                elif n < len(xlabels):                xlabel = xlabels[n]
                else:                                 xlabel = ''

                if type(ylabels) in [str,type(None)]: ylabel = ylabels
                elif n < len(ylabels):                ylabel = ylabels[n]
                else:                                 ylabel = ''

                # set the labels
                i = min(n, len(self.plot_widgets)-1)
                self.plot_widgets[i].setLabel('left',   ylabel)
                self.plot_widgets[i].setLabel('bottom', xlabel)

                # special case: hide if None
                if xlabel == None: self.plot_widgets[i].getAxis('bottom').showLabel(False)
                if ylabel == None: self.plot_widgets[i].getAxis('left')  .showLabel(False)

            # unpink the script, since it seems to have worked
            self.script.set_colors('black','white')

        # otherwise, look angry and don't autosave
        except: self.script.set_colors('black','pink')

        return self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def autosave(self):
        # make sure we're suppoed to
        if self.button_autosave.is_checked():

            # save the file
            self.save_file(_os.path.join(self._autosave_directory, "%04d " % (self.number_file.get_value()) + self._label_path.get_text()))

            # increment the counter
            self.number_file.increment()

Response: Autosaves the currently stored data but only if autosave is checked!


Instruction:
Write a Python 3 script to
synchronize the control based on button configs.

Response:
def _synchronize_controls(self):
        """
        Updates the gui based on button configs.
        """

        # whether the script is visible
        self.grid_script._widget.setVisible(self.button_script.get_value())

        # whether we should be able to edit it.
        if not self.combo_autoscript.get_index()==0: self.script.disable()
        else:                                        self.script.enable()


Instruction:
Can you implement a function in Python 3 that
adjusts the number of plots and curves to the desired value the gui.

Response:
def _set_number_of_plots(self, n):
        """
        Adjusts number of plots & curves to the desired value the gui.
        """

        # multi plot, right number of plots and curves = great!
        if self.button_multi.is_checked()               \
        and len(self._curves) == len(self.plot_widgets) \
        and len(self._curves) == n: return

        # single plot, right number of curves = great!
        if not self.button_multi.is_checked() \
        and len(self.plot_widgets) == 1       \
        and len(self._curves) == n: return

        # time to rebuild!

        # don't show the plots as they are built
        self.grid_plot.block_events()

        # make sure the number of curves is on target
        while len(self._curves) > n: self._curves.pop(-1)
        while len(self._curves) < n: self._curves.append(_g.PlotCurveItem(pen = (len(self._curves), n)))

        # figure out the target number of plots
        if self.button_multi.is_checked(): n_plots = n
        else:                              n_plots = min(n,1)

        # clear the plots
        while len(self.plot_widgets):

            # pop the last plot widget and remove all items
            p = self.plot_widgets.pop(-1)
            p.clear()

            # remove it from the grid
            self.grid_plot.remove_object(p)

        # add new plots
        for i in range(n_plots):
            self.plot_widgets.append(self.grid_plot.place_object(_g.PlotWidget(), 0, i, alignment=0))

        # loop over the curves and add them to the plots
        for i in range(n):
            self.plot_widgets[min(i,len(self.plot_widgets)-1)].addItem(self._curves[i])

        # loop over the ROI's and add them
        if self.ROIs is not None:

            for i in range(len(self.ROIs)):

                # get the ROIs for this plot
                ROIs = self.ROIs[i]

                if not _spinmob.fun.is_iterable(ROIs): ROIs = [ROIs]

                # loop over the ROIs for this plot
                for ROI in ROIs:

                    # determine which plot to add the ROI to
                    m = min(i, len(self.plot_widgets)-1)

                    # add the ROI to the appropriate plot
                    if m>=0: self.plot_widgets[m].addItem(ROI)

        # show the plots
        self.grid_plot.unblock_events()


Instruction:
Implement a function in Python 3 to
update the linked axes of the current plot item.

Response:
def _update_linked_axes(self):
        """
        Loops over the axes and links / unlinks them.
        """
        # no axes to link!
        if len(self.plot_widgets) <= 1: return

        # get the first plotItem
        a = self.plot_widgets[0].plotItem.getViewBox()

        # now loop through all the axes and link / unlink the axes
        for n in range(1,len(self.plot_widgets)):

            # Get one of the others
            b = self.plot_widgets[n].plotItem.getViewBox()

            # link the axis, but only if it isn't already
            if self.button_link_x.is_checked() and b.linkedView(b.XAxis) == None:
                b.linkView(b.XAxis, a)

            # Otherwise, unlink the guy, but only if it's linked to begin with
            elif not self.button_link_x.is_checked() and not b.linkedView(b.XAxis) == None:
                b.linkView(b.XAxis, None)


Instruction:
Implement a function in Python 3 to
find and links the ConstSpec with the given name.

Response:
def resolve_const_spec(self, name, lineno):
        """Finds and links the ConstSpec with the given name."""

        if name in self.const_specs:
            return self.const_specs[name].link(self)

        if '.' in name:
            include_name, component = name.split('.', 1)
            if include_name in self.included_scopes:
                return self.included_scopes[include_name].resolve_const_spec(
                    component, lineno
                )

        raise ThriftCompilerError(
            'Unknown constant "%s" referenced at line %d%s' % (
                name, lineno, self.__in_path()
            )
        )


Instruction:
Can you tell what is the following Python 3 function doing
def resolve_type_spec(self, name, lineno):

        if name in self.type_specs:
            return self.type_specs[name].link(self)

        if '.' in name:
            include_name, component = name.split('.', 1)
            if include_name in self.included_scopes:
                return self.included_scopes[include_name].resolve_type_spec(
                    component, lineno
                )

        raise ThriftCompilerError(
            'Unknown type "%s" referenced at line %d%s' % (
                name, lineno, self.__in_path()
            )
        )

Response: Finds and links the TypeSpec with the given name.


Instruction:
Can you implement a function in Python 3 that
finds and links the ServiceSpec with the given name.

Response:
def resolve_service_spec(self, name, lineno):
        """Finds and links the ServiceSpec with the given name."""

        if name in self.service_specs:
            return self.service_specs[name].link(self)

        if '.' in name:
            include_name, component = name.split('.', 2)
            if include_name in self.included_scopes:
                return self.included_scopes[
                    include_name
                ].resolve_service_spec(component, lineno)

        raise ThriftCompilerError(
            'Unknown service "%s" referenced at line %d%s' % (
                name, lineno, self.__in_path()
            )
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def add_include(self, name, included_scope, module):
        # The compiler already ensures this. If we still get here with a
        # conflict, that's a bug.
        assert name not in self.included_scopes

        self.included_scopes[name] = included_scope
        self.add_surface(name, module)

Response: Register an imported module into this scope.


Instruction:
Write a Python 3 function that can
add the given ServiceSpec into the scope.

Response:
def add_service_spec(self, service_spec):
        """Registers the given ``ServiceSpec`` into the scope.

        Raises ``ThriftCompilerError`` if the name has already been used.
        """
        assert service_spec is not None

        if service_spec.name in self.service_specs:
            raise ThriftCompilerError(
                'Cannot define service "%s". That name is already taken.'
                % service_spec.name
            )
        self.service_specs[service_spec.name] = service_spec


Instruction:
Explain what the following Python 3 code does
def add_const_spec(self, const_spec):
        if const_spec.name in self.const_specs:
            raise ThriftCompilerError(
                'Cannot define constant "%s". That name is already taken.'
                % const_spec.name
            )
        self.const_specs[const_spec.name] = const_spec

Response: Adds a ConstSpec to the compliation scope.


Instruction:
Write a Python 3 script to
add a top - level attribute with the given name to the module.

Response:
def add_surface(self, name, surface):
        """Adds a top-level attribute with the given name to the module."""
        assert surface is not None

        if hasattr(self.module, name):
            raise ThriftCompilerError(
                'Cannot define "%s". The name has already been used.' % name
            )

        setattr(self.module, name, surface)


Instruction:
Can you create a Python 3 function that
adds the given type to the scope.

Response:
def add_type_spec(self, name, spec, lineno):
        """Adds the given type to the scope.

        :param str name:
            Name of the new type
        :param spec:
            ``TypeSpec`` object containing information on the type, or a
            ``TypeReference`` if this is meant to be resolved during the
            ``link`` stage.
        :param lineno:
            Line number on which this type is defined.
        """
        assert type is not None

        if name in self.type_specs:
            raise ThriftCompilerError(
                'Cannot define type "%s" at line %d. '
                'Another type with that name already exists.'
                % (name, lineno)
            )

        self.type_specs[name] = spec


Instruction:
Here you have a function in Python 3, explain what it does
def coarsen_array(a, level=2, method='mean'):
    if a is None: return None

    # make sure it's a numpy array
    a = _n.array(a)

    # quickest option
    if level in [0,1,False]: return a

    # otherwise assemble the python code to execute
    code = 'a.reshape(-1, level).'+method+'(axis=1)'

    # execute, making sure the array can be reshaped!
    try: return eval(code, dict(a=a[0:int(len(a)/level)*level], level=level))
    except:
        print("ERROR: Could not coarsen array with method "+repr(method))
        return a

Response: Coarsen an array of data.


Instruction:
Can you implement a function in Python 3 that
coarsens the supplied data set and returns a list of arrays along with the specified quadrature - coarsened arrays of x y uncertainties and ex uncertainties.

Response:
def coarsen_data(x, y, ey=None, ex=None, level=2, exponential=False):
    """
    Coarsens the supplied data set. Returns coarsened arrays of x, y, along with
    quadrature-coarsened arrays of ey and ex if specified.

    Parameters
    ----------
    x, y
        Data arrays. Can be lists (will convert to numpy arrays).
        These are coarsened by taking an average.
    ey=None, ex=None
        y and x uncertainties. Accepts arrays, lists, or numbers.
        These are coarsened by averaging in quadrature.
    level=2
        For linear coarsening (default, see below), every n=level points will
        be averaged together (in quadrature for errors). For exponential
        coarsening, bins will be spaced by the specified scaling=level factor;
        for example, level=1.4 will group points within 40% of each other's x
        values. This is a great option for log-x plots, as the outcome will be
        evenly spaced.
    exponential=False
        If False, coarsen using linear spacing. If True, the bins will be
        exponentially spaced by the specified level.
    """

    # Normal coarsening
    if not exponential:

        # Coarsen the data
        xc  = coarsen_array(x, level, 'mean')
        yc  = coarsen_array(y, level, 'mean')

        # Coarsen the y error in quadrature
        if not ey is None:
            if not is_iterable(ey): ey = [ey]*len(y)
            eyc = _n.sqrt(coarsen_array(_n.power(ey,2)/level, level, 'mean'))

        # Coarsen the x error in quadrature
        if not ex is None:
            if not is_iterable(ey): ex = [ex]*len(x)
            exc = _n.sqrt(coarsen_array(_n.power(ex,2)/level, level, 'mean'))

    # Exponential coarsen
    else:
        # Make sure the data are arrays
        x = _n.array(x)
        y = _n.array(y)

        # Create the new arrays to fill
        xc = []
        yc = []
        if not ey is None:
            if not is_iterable(ey): ey = _n.array([ey]*len(y))
            eyc = []
        if not ex is None:
            if not is_iterable(ex): ex = _n.array([ex]*len(x))
            exc = []

        # Find the first element that is greater than zero
        x0 = x[x>0][0]

        # Now loop over the exponential bins
        n  = 0
        while x0*level**n < x[-1]:

            # Get all the points between x[n] and x[n]*r
            mask = _n.logical_and(x0*level**n <= x, x < x0*level**(n+1))

            # Only do something if points exist from this range!
            if len(x[mask]):

                # Take the average x value
                xc.append(_n.average(x[mask]))
                yc.append(_n.average(y[mask]))

                # do the errors in quadrature
                if not ey is None: eyc.append(_n.sqrt(_n.average((ey**2)[mask])/len(ey[mask])))
                if not ex is None: exc.append(_n.sqrt(_n.average((ex**2)[mask])/len(ex[mask])))

            # Increment the counter
            n += 1

        # Done exponential loop

    # Done coarsening
    # Return depending on situation
    if   ey is None and ex is None: return _n.array(xc), _n.array(yc)
    elif ex is None               : return _n.array(xc), _n.array(yc), _n.array(eyc)
    elif ey is None               : return _n.array(xc), _n.array(yc), _n.array(exc)
    else                          : return _n.array(xc), _n.array(yc), _n.array(eyc), _n.array(exc)


Instruction:
Make a summary of the following Python 3 code
def coarsen_matrix(Z, xlevel=0, ylevel=0, method='average'):

    # coarsen x
    if not ylevel:
        Z_coarsened = Z
    else:
        temp = []
        for z in Z: temp.append(coarsen_array(z, ylevel, method))
        Z_coarsened = _n.array(temp)

    # coarsen y
    if xlevel:
        Z_coarsened = Z_coarsened.transpose()
        temp = []
        for z in Z_coarsened: temp.append(coarsen_array(z, xlevel, method))
        Z_coarsened = _n.array(temp).transpose()

    return Z_coarsened

    # first coarsen the columns (if necessary)
    if ylevel:
        Z_ycoarsened = []
        for c in Z: Z_ycoarsened.append(coarsen_array(c, ylevel, method))
        Z_ycoarsened = _n.array(Z_ycoarsened)

    # now coarsen the rows
    if xlevel: return coarsen_array(Z_ycoarsened, xlevel, method)
    else:      return _n.array(Z_ycoarsened)

Response: This returns a numpy matrix that coarsenes the columns and rows of the tree Z.


Instruction:
Write a Python 3 function that can
return a numpy array over the specified range taking geometric steps.

Response:
def erange(start, end, steps):
    """
    Returns a numpy array over the specified range taking geometric steps.

    See also numpy.logspace()
    """
    if start == 0:
        print("Nothing you multiply zero by gives you anything but zero. Try picking something small.")
        return None
    if end == 0:
        print("It takes an infinite number of steps to get to zero. Try a small number?")
        return None

    # figure out our multiplication scale
    x = (1.0*end/start)**(1.0/(steps-1))

    # now generate the array
    ns = _n.array(list(range(0,steps)))
    a =  start*_n.power(x,ns)

    # tidy up the last element (there's often roundoff error)
    a[-1] = end

    return a


Instruction:
Create a Python 3 function for
returning True if the object s value is a number False otherwise.

Response:
def is_a_number(s):
    """
    This takes an object and determines whether it's a number or a string
    representing a number.
    """
    if _s.fun.is_iterable(s) and not type(s) == str: return False

    try:
        float(s)
        return 1
    except:
        try:
            complex(s)
            return 2
        except:
            try:
                complex(s.replace('(','').replace(')','').replace('i','j'))
                return 2
            except:
                return False


Instruction:
Create a Python 3 function for
assembling the covariance matrix from an error vector and a correlation matrix.

Response:
def assemble_covariance(error, correlation):
    """
    This takes an error vector and a correlation matrix and assembles the covariance
    """

    covariance = []
    for n in range(0, len(error)):
        covariance.append([])
        for m in range(0, len(error)):
            covariance[n].append(correlation[n][m]*error[n]*error[m])
    return _n.array(covariance)


Instruction:
Implement a Python 3 function for
returning the combined dictionary a and b.

Response:
def combine_dictionaries(a, b):
    """
    returns the combined dictionary.  a's values preferentially chosen
    """

    c = {}
    for key in list(b.keys()): c[key]=b[key]
    for key in list(a.keys()): c[key]=a[key]
    return c


Instruction:
Make a summary of the following Python 3 code
def decompose_covariance(c):

    # make it a kickass copy of the original
    c = _n.array(c)

    # first get the error vector
    e = []
    for n in range(0, len(c[0])): e.append(_n.sqrt(c[n][n]))

    # now cycle through the matrix, dividing by e[1]*e[2]
    for n in range(0, len(c[0])):
        for m in range(0, len(c[0])):
            c[n][m] = c[n][m] / (e[n]*e[m])

    return [_n.array(e), _n.array(c)]

Response: This decomposes a covariance matrix into an error vector and a correlation matrix.


Instruction:
How would you code a function in Python 3 to
return the derivative of the data with nearest - neighbor slopes.

Response:
def derivative(xdata, ydata):
    """
    performs d(ydata)/d(xdata) with nearest-neighbor slopes
    must be well-ordered, returns new arrays [xdata, dydx_data]

    neighbors:
    """
    D_ydata = []
    D_xdata = []
    for n in range(1, len(xdata)-1):
        D_xdata.append(xdata[n])
        D_ydata.append((ydata[n+1]-ydata[n-1])/(xdata[n+1]-xdata[n-1]))

    return [D_xdata, D_ydata]


Instruction:
Write a Python 3 function for
performing a least - squares linear fit of the data points at each point. Returns an array of x - values and slopes.

Response:
def derivative_fit(xdata, ydata, neighbors=1):
    """
    loops over the data points, performing a least-squares linear fit of the
    nearest neighbors at each point. Returns an array of x-values and slopes.

    xdata should probably be well-ordered.

    neighbors   How many data point on the left and right to include.
    """

    x    = []
    dydx = []
    nmax = len(xdata)-1

    for n in range(nmax+1):
        # get the indices of the data to fit
        i1 = max(0, n-neighbors)
        i2 = min(nmax, n+neighbors)

        # get the sub data to fit
        xmini = _n.array(xdata[i1:i2+1])
        ymini = _n.array(ydata[i1:i2+1])

        slope, intercept = fit_linear(xmini, ymini)

        # make x the average of the xmini
        x.append(float(sum(xmini))/len(xmini))
        dydx.append(slope)

    return _n.array(x), _n.array(dydx)


Instruction:
Implement a Python 3 function for
applying a distortion (remapping) to the matrix Z (and x-values X) using function f. returns new_Z, new_X f is an INVERSE function old_x(new_x) Z is a matrix. X is an array where X[n] is the x-value associated with the array Z[n]. new_xmin, new_xmax is the possible range of the distorted x-variable for generating Z points is how many elements the stretched Z should have. "auto" means use the same number of bins

Response:
def distort_matrix_X(Z, X, f, new_xmin, new_xmax, subsample=3):
    """
    Applies a distortion (remapping) to the matrix Z (and x-values X) using function f.
    returns new_Z, new_X

    f is an INVERSE function old_x(new_x)

    Z is a matrix. X is an array where X[n] is the x-value associated with the array Z[n].

    new_xmin, new_xmax is the possible range of the distorted x-variable for generating Z

    points is how many elements the stretched Z should have. "auto" means use the same number of bins
    """

    Z = _n.array(Z)
    X = _n.array(X)
    points = len(Z)*subsample

    # define a function for searching
    def zero_me(new_x): return f(new_x)-target_old_x

    # do a simple search to find the new_x that gives old_x = min(X)
    target_old_x = min(X)
    new_xmin = find_zero_bisect(zero_me, new_xmin, new_xmax, _n.abs(new_xmax-new_xmin)*0.0001)
    target_old_x = max(X)
    new_xmax = find_zero_bisect(zero_me, new_xmin, new_xmax, _n.abs(new_xmax-new_xmin)*0.0001)

    # now loop over all the new x values
    new_X = []
    new_Z = []
    bin_width = float(new_xmax-new_xmin)/(points)
    for new_x in frange(new_xmin, new_xmax, bin_width):

        # make sure we're in the range of X
        if f(new_x) <= max(X) and f(new_x) >= min(X):

            # add this guy to the array
            new_X.append(new_x)

            # get the interpolated column
            new_Z.append( interpolate(X,Z,f(new_x)) )

    return _n.array(new_Z), _n.array(new_X)


Instruction:
Here you have a function in Python 3, explain what it does
def distort_matrix_Y(Z, Y, f, new_ymin, new_ymax, subsample=3):

    # just use the same methodology as before by transposing, distorting X, then
    # transposing back
    new_Z, new_Y = distort_matrix_X(Z.transpose(), Y, f, new_ymin, new_ymax, subsample)
    return new_Z.transpose(), new_Y

Response: Applies a distortion to the matrix Z and y - values Y using function f.


Instruction:
Can you generate the documentation for the following Python 3 function
def dumbguy_minimize(f, xmin, xmax, xstep):

    prev = f(xmin)
    this = f(xmin+xstep)
    for x in frange(xmin+xstep,xmax,xstep):
        next = f(x+xstep)

        # see if we're on top
        if this < prev and this < next: return x, this

        prev = this
        this = next

    return x, this

Response:
This just steps x and looks for a peak
    returns x and f


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

    # empty case
    if len(array) == 0: return 0

    output_value = 1
    for x in array:

        # test it and die if it's not a number
        test = is_a_number(x)
        if not test: return False

        # mention if it's complex
        output_value = max(output_value,test)

    return output_value

Response: Tests whether the elements of the supplied array are numbers.


Instruction:
Given the following Python 3 function, write the documentation
def equalize_list_lengths(a,b):
    if not _s.fun.is_iterable(a): a = [a]
    a = list(a)
    while len(a)>len(b): a.pop(-1)
    while len(a)<len(b): a.append(a[-1])
    return a

Response: Modifies the length of list a to match b. Returns a.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fit_linear(xdata, ydata):
    x = _n.array(xdata)
    y = _n.array(ydata)

    ax  = _n.average(x)
    ay  = _n.average(y)
    axx = _n.average(x*x)
    ayx = _n.average(y*x)

    slope     = (ayx - ay*ax) / (axx - ax*ax)
    intercept = ay - slope*ax

    return slope, intercept

Response: Linear fit of the best fit.


Instruction:
Make a summary of the following Python 3 code
def frange(start, end, inc=1.0):

    start = 1.0*start
    end   = 1.0*end
    inc   = 1.0*inc

    # if we got a dumb increment
    if not inc: return _n.array([start,end])

    # if the increment is going the wrong direction
    if 1.0*(end-start)/inc < 0.0:
        inc = -inc

    # get the integer steps
    ns = _n.array(list(range(0, int(1.0*(end-start)/inc)+1)))

    return start + ns*inc

Response: A range function that accepts float increments and reversed direction.