def Func(arg_0, arg_1, arg_2=1):
        """Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.

        This is used to extract and visualize only the region of an image that is used in an analysis.

        Parameters
        ----------
        mask : mask.Mask
            The mask around which the scaled array is extracted.
        buffer : int
            The buffer of pixels around the extraction.
        """
        return arg_0.new_with_array(array=array_util.extracted_array_2d_from_array_2d_and_coordinates(
            array_2d=arg_0,  y0=arg_1.zoom_region[0]-arg_2, y1=arg_1.zoom_region[1]+arg_2,
            x0=arg_1.zoom_region[2]-arg_2, x1=arg_1.zoom_region[3]+arg_2))


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """resized the array to a new shape and at a new origin.

        Parameters
        -----------
        new_shape : (int, int)
            The new two-dimensional shape of the array.
        """
        if arg_2 is None and arg_3 is None:
            arg_4 = (-1, -1)  # In Numba, the input origin must be the same image type as the origin, thus we cannot
            # pass 'None' and instead use the tuple (-1, -1).
        elif arg_2 is not None and arg_3 is None:
            arg_4 = arg_2
        elif arg_2 is None and arg_3 is not None:
            arg_4 = arg_0.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=arg_3)
        else:
            raise exc.DataException('You have supplied two centres (pixels and arc-seconds) to the resize scaled'
                                       'array function')

        return arg_0.new_with_array(array=array_util.resized_array_2d_from_array_2d_and_resized_shape(
            array_2d=arg_0, resized_shape=arg_1, origin=arg_4))


def Func(arg_0, arg_1, arg_2):
    """Fit lens data with a normal tracer and sensitivity tracer, to determine our sensitivity to a selection of \
    galaxy components. This factory automatically determines the type of fit based on the properties of the galaxies \
    in the tracers.

    Parameters
    -----------
    lens_data : lens_data.LensData or lens_data.LensDataHyper
        The lens-images that is fitted.
    tracer_normal : ray_tracing.AbstractTracer
        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \
        lens data that we are fitting.
    tracer_sensitive : ray_tracing.AbstractTracerNonStack
        A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \
        lens data that we are fitting, but also addition components (e.g. mass clumps) which we measure \
        how sensitive we are too.
    """

    if (arg_1.has_light_profile and arg_2.has_light_profile) and \
            (not arg_1.has_pixelization and not arg_2.has_pixelization):
        return SensitivityProfileFit(arg_0=arg_0, arg_1=arg_1,
                                     arg_2=arg_2)

    elif (not arg_1.has_light_profile and not arg_2.has_light_profile) and \
            (arg_1.has_pixelization and arg_2.has_pixelization):
        return SensitivityInversionFit(arg_0=arg_0, arg_1=arg_1,
                                     arg_2=arg_2)
    else:

        raise exc.FittingException('The sensitivity_fit routine did not call a SensitivityFit class - check the '
                                   'properties of the tracers')


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=(0., 0.), arg_5=False):
        """Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.

        Parameters
        ----------
        shape: (int, int)
            The (y,x) shape of the mask in units of pixels.
        pixel_scale: float
            The arc-second to pixel conversion factor of each pixel.
        radius_arcsec : float
            The radius (in arc seconds) of the circle within which pixels unmasked.
        centre: (float, float)
            The centre of the circle used to mask pixels.
        """
        arg_6 = mask_util.mask_Func_from_shape_pixel_scale_and_radius(arg_1, arg_2, arg_3,
                                                                         arg_4)
        if arg_5: arg_6 = np.invert(arg_6)
        return arg_0(array=arg_6.astype('bool'), arg_2=arg_2)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=(0., 0.),
                         arg_6=False):
        """Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \
         centre.

        Parameters
        ----------
        shape : (int, int)
            The (y,x) shape of the mask in units of pixels.
        pixel_scale: float
            The arc-second to pixel conversion factor of each pixel.
        inner_radius_arcsec : float
            The radius (in arc seconds) of the inner circle outside of which pixels are unmasked.
        outer_radius_arcsec : float
            The radius (in arc seconds) of the outer circle within which pixels are unmasked.
        centre: (float, float)
            The centre of the annulus used to mask pixels.
        """
        arg_7 = mask_util.mask_Func_from_shape_pixel_scale_and_radii(arg_1, arg_2, arg_3,
                                                                                arg_4, arg_5)
        if arg_6: arg_7 = np.invert(arg_7)
        return arg_0(array=arg_7.astype('bool'), arg_2=arg_2)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6=(0., 0.),
                   arg_7=False):
        """ Setup a mask where unmasked pixels are within an ellipse of an input arc second major-axis and centre.

        Parameters
        ----------
        shape: (int, int)
            The (y,x) shape of the mask in units of pixels.
        pixel_scale: float
            The arc-second to pixel conversion factor of each pixel.
        major_axis_radius_arcsec : float
            The major-axis (in arc seconds) of the ellipse within which pixels are unmasked.
        axis_ratio : float
            The axis-ratio of the ellipse within which pixels are unmasked.
        phi : float
            The rotation angle of the ellipse within which pixels are unmasked, (counter-clockwise from the positive \
             x-axis).
        centre: (float, float)
            The centre of the ellipse used to mask pixels.
        """
        arg_8 = mask_util.mask_Func_from_shape_pixel_scale_and_radius(arg_1, arg_2, arg_3,
                                                                          arg_4, arg_5, arg_6)
        if arg_7: arg_8 = np.invert(arg_8)
        return arg_0(array=arg_8.astype('bool'), arg_2=arg_2)


def Func(arg_0, arg_1, arg_2,arg_3, arg_4, arg_5,
                           arg_6, arg_7, arg_8, arg_9=(0.0, 0.0),
                           arg_10=False):
        """Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second \
        major-axis and centre.

        Parameters
        ----------
        shape: (int, int)
            The (y,x) shape of the mask in units of pixels.
        pixel_scale: float
            The arc-second to pixel conversion factor of each pixel.
        inner_major_axis_radius_arcsec : float
            The major-axis (in arc seconds) of the inner ellipse within which pixels are masked.
        inner_axis_ratio : float
            The axis-ratio of the inner ellipse within which pixels are masked.
        inner_phi : float
            The rotation angle of the inner ellipse within which pixels are masked, (counter-clockwise from the \
            positive x-axis).
        outer_major_axis_radius_arcsec : float
            The major-axis (in arc seconds) of the outer ellipse within which pixels are unmasked.
        outer_axis_ratio : float
            The axis-ratio of the outer ellipse within which pixels are unmasked.
        outer_phi : float
            The rotation angle of the outer ellipse within which pixels are unmasked, (counter-clockwise from the \
            positive x-axis).
        centre: (float, float)
            The centre of the elliptical annuli used to mask pixels.
        """
        arg_11 = mask_util.mask_Func_from_shape_pixel_scale_and_radius(arg_1, arg_2,
                           arg_3, arg_4, arg_5,
                           arg_6, arg_7, arg_8, arg_9)
        if arg_10: arg_11 = np.invert(arg_11)
        return arg_0(array=arg_11.astype('bool'), arg_2=arg_2)


def Func(arg_0):
        """The zoomed rectangular region corresponding to the square encompassing all unmasked values.

        This is used to zoom in on the region of an image that is used in an analysis for visualization."""

        # Have to convert mask to bool for invert function to work.
        arg_1 = np.array(np.where(np.invert(arg_0.astype('bool'))))
        arg_2, arg_3 = np.amin(arg_1, axis=1)
        arg_4, arg_5 = np.amax(arg_1, axis=1)
        return [arg_2, arg_4+1, arg_3, arg_5+1]


def Func(arg_0, arg_1):
        """
        Create an instance of the associated class for a set of arguments

        Parameters
        ----------
        arguments: {Prior: value}
            Dictionary mapping_matrix priors to attribute analysis_path and value pairs

        Returns
        -------
            An instance of the class
        """
        arg_2 = {**{key: value.Func(arg_1)
                       for key, value
                       in arg_0.profile_prior_model_dict.items()}, **arg_0.constant_profile_dict}

        try:
            arg_3 = arg_0.redshift.Func(arg_1)
        except AttributeError:
            arg_3 = arg_0.redshift
        arg_4 = arg_0.pixelization.Func(arg_1) \
            if isinstance(arg_0.pixelization, pm.PriorModel) \
            else arg_0.pixelization
        arg_5 = arg_0.regularization.Func(arg_1) \
            if isinstance(arg_0.regularization, pm.PriorModel) \
            else arg_0.regularization
        arg_6 = arg_0.hyper_galaxy.Func(arg_1) \
            if isinstance(arg_0.hyper_galaxy, pm.PriorModel) \
            else arg_0.hyper_galaxy

        return galaxy.Galaxy(arg_3=arg_3, arg_4=arg_4, arg_5=arg_5,
                             arg_6=arg_6, **arg_2)


def Func(arg_0, arg_1):
        """
        Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
        models with new arguments.

        Parameters
        ----------
        arguments: dict
            A dictionary mapping_matrix between old priors and their replacements.

        Returns
        -------
        new_model: GalaxyModel
            A model with some or all priors replaced.
        """
        arg_2 = copy.deepcopy(arg_0)

        for arg_3, arg_4 in filter(lambda t: isinstance(t[1], pm.PriorModel), arg_0.__dict__.items()):
            setattr(arg_2, arg_3, arg_4.Func(arg_1))

        return arg_2


def Func(
        arg_0, arg_1=True, arg_2=None, arg_3=False, arg_4=False,
        arg_5=False, arg_6=None, arg_7=False,
        arg_8='arcsec', arg_9=None, arg_10=(7, 7), arg_11='square',
        arg_12='jet', arg_13='linear', arg_14=None, arg_15=None, arg_16=0.05, arg_17=0.01,
        arg_18=10, arg_19=0.047, arg_20=0.01, arg_21=None, arg_22=None,
        arg_23='Image', arg_24=16, arg_25=16, arg_26=16, arg_27=16,
        arg_28=10, arg_29=30, arg_30=1,
        arg_31=None, arg_32='show', arg_33='image'):
    """Plot the observed image of the ccd data.

    Set *autolens.data.array.plotters.array_plotters* for a description of all input parameters not described below.

    Parameters
    -----------
    image : ScaledSquarePixelArray
        The image of the data.
    plot_origin : True
        If true, the origin of the data's coordinate system is plotted as a 'x'.
    image_plane_pix_grid : ndarray or data.array.grid_stacks.PixGrid
        If an adaptive pixelization whose pixels are formed by tracing pixels from the data, this plots those pixels \
        over the immage.
    """
    arg_34 = get_origin(array=arg_0, arg_1=arg_1)

    array_plotters.plot_array(
        array=arg_0, arg_34=arg_34, arg_2=arg_2, arg_3=arg_3,
        arg_4=arg_4,
        arg_5=arg_5, arg_6=arg_6, arg_7=arg_7,
        arg_8=arg_8, arg_9=arg_9, arg_10=arg_10, arg_11=arg_11,
        arg_12=arg_12, arg_13=arg_13, arg_14=arg_14, arg_15=arg_15, arg_16=arg_16, arg_17=arg_17,
        arg_18=arg_18, arg_19=arg_19, arg_20=arg_20,
        arg_21=arg_21, arg_22=arg_22,
        arg_23=arg_23, arg_24=arg_24, arg_25=arg_25, arg_26=arg_26, arg_27=arg_27,
        arg_28=arg_28, arg_29=arg_29, arg_30=arg_30,
        arg_31=arg_31, arg_32=arg_32, arg_33=arg_33)


def Func(arg_0, arg_1, arg_2):
        """Write `data` to file record `n`; records are indexed from 1."""
        arg_0.file.seek(arg_1 * K - K)
        return arg_0.file.write(arg_2)


def Func(arg_0, arg_1, arg_2):
        """Return a memory-map of the elements `start` through `end`.

        The memory map will offer the 8-byte double-precision floats
        ("elements") in the file from index `start` through to the index
        `end`, inclusive, both counting the first float as element 1.
        Memory maps must begin on a page boundary, so `skip` returns the
        number of extra bytes at the beginning of the return value.

        """
        arg_3, arg_4 = 8 * arg_1 - 8, 8 * arg_2
        try:
            arg_5 = arg_0.file.fileno()
        except (AttributeError, io.UnsupportedOperation):
            arg_5 = None
        if arg_5 is None:
            arg_6 = 0
            arg_0.file.seek(arg_3)
            arg_7 = arg_0.file.read(arg_4 - arg_3)
        else:
            arg_6 = arg_3 % mmap.ALLOCATIONGRANULARITY
            arg_8 = mmap.ACCESS_READ
            arg_7 = mmap.mmap(arg_5, length=arg_4-arg_3+arg_6, access=arg_8, offset=arg_3-arg_6)
        if sys.version_info > (3,):
            arg_7 = memoryview(arg_7)  # so further slicing can return views
        return arg_7, arg_6


def Func(arg_0):
        """Return the text inside the comment area of the file."""
        arg_1 = range(2, arg_0.fward)
        if not arg_1:
            return ''
        arg_2 = b''.join(arg_0.read_record(n)[0:1000] for n in arg_1)
        try:
            return arg_2[:arg_2.find(b'\4')].decode('ascii').replace('\0', '\n')
        except IndexError:
            raise ValueError('DAF file comment area is missing its EOT byte')
        except UnicodeDecodeError:
            raise ValueError('DAF file comment area is not ASCII text')


def Func(arg_0, arg_1, arg_2=0.0):
        """Compute the component values for the time `tdb` plus `tdb2`."""
        for arg_3 in arg_0.generate(arg_1, arg_2):
            return arg_3


def Func(arg_0):
        """Close this file."""
        arg_0.daf.file.Func()
        for arg_1 in arg_0.segments:
            if hasattr(arg_1, '_data'):
                del arg_1._data


def Func(arg_0):
        """Map the coefficients into memory using a NumPy array.

        """
        if arg_0.data_type == 2:
            arg_1 = 3
        else:
            raise ValueError('only binary PCK data type 2 is supported')

        arg_2, arg_3, arg_4, arg_5 = arg_0.daf.read_array(arg_0.end_i - 3, arg_0.end_i)
        arg_6 = jd(arg_2)
        arg_7 = arg_3 / S_PER_DAY
        arg_8 = int(arg_4 - 2) // arg_1
        arg_9 = arg_0.daf.map_array(arg_0.start_i, arg_0.end_i - 4)

        arg_9.shape = (int(arg_5), int(arg_4))
        arg_9 = arg_9[:,2:]  # ignore MID and RADIUS elements
        arg_9.shape = (int(arg_5), arg_1, arg_8)
        arg_9 = rollaxis(arg_9, 1)
        return arg_6, arg_7, arg_9


def Func(arg_0, arg_1, arg_2, arg_3=True):
        """Generate angles and derivatives for time `tdb` plus `tdb2`.

        If ``derivative`` is true, return a tuple containing both the
        angle and its derivative; otherwise simply return the angles.

        """
        arg_4 = not getattr(arg_1, 'shape', 0) and not getattr(arg_2, 'shape', 0)
        if arg_4:
            arg_1 = array((arg_1,))

        arg_5 = arg_0._data
        if arg_5 is None:
            arg_0._data = arg_5 = arg_0._load()

        arg_7, arg_8, arg_9 = arg_5
        arg_10, arg_11, arg_12 = arg_9.shape

        # Subtracting tdb before adding tdb2 affords greater precision.
        arg_13, arg_14 = divmod((arg_1 - arg_7) + arg_2, arg_8)
        arg_13 = arg_13.astype(int)

        if (arg_13 < 0).any() or (arg_13 > arg_11).any():
            arg_15 = arg_7 + arg_8 * arg_11
            raise ValueError('segment only covers dates %.1f through %.1f'
                            % (arg_7, arg_15))

        arg_16 = (arg_13 == arg_11)
        arg_13[arg_16] -= 1
        arg_14[arg_16] += arg_8

        arg_9 = arg_9[:,arg_13]

        # Chebyshev polynomial.

        arg_17 = empty((arg_12, len(arg_13)))
        arg_17[0] = 1.0
        arg_17[1] = t1 = 2.0 * arg_14 / arg_8 - 1.0
        arg_18 = t1 + t1
        for arg_19 in range(2, arg_12):
            arg_17[arg_19] = arg_18 * arg_17[arg_19-1] - arg_17[arg_19-2]

        arg_20 = (arg_17.T * arg_9).sum(axis=2)
        if arg_4:
            arg_20 = arg_20[:,0]

        if not arg_3:
            return arg_20

        # Chebyshev differentiation.

        arg_21 = empty_like(arg_17)
        arg_21[0] = 0.0
        arg_21[1] = 1.0
        if arg_12 > 2:
            arg_21[2] = arg_18 + arg_18
            for arg_19 in range(3, arg_12):
                arg_21[arg_19] = arg_18 * arg_21[arg_19-1] - arg_21[arg_19-2] + arg_17[arg_19-1] + arg_17[arg_19-1]
        arg_21 *= 2.0
        arg_21 /= arg_8

        arg_22 = (arg_21.T * arg_9).sum(axis=2)
        if arg_4:
            arg_22 = arg_22[:,0]

        return arg_20, arg_22


def Func(arg_0, arg_1):
    """Normalise and check a backend path.

    Ensure that the requested backend path is specified as a relative path,
    and resolves to a location under the given source tree.

    Return an absolute version of the requested path.
    """
    if os.path.isabs(arg_1):
        raise ValueError("paths must be relative")

    arg_2 = os.path.abspath(arg_0)
    arg_3 = os.path.normpath(os.path.join(arg_2, arg_1))
    # We have to use commonprefix for Python 2.7 compatibility. So we
    # normalise case to avoid problems because commonprefix is a character
    # based comparison :-(
    arg_4 = os.path.normcase(arg_2)
    arg_5 = os.path.normcase(arg_3)
    if os.path.commonprefix([arg_4, arg_5]) != arg_4:
        raise ValueError("paths must be inside source tree")

    return arg_3


def Func(arg_0, arg_1):
        """
        Visit a function call.

        We expect every logging statement and string format to be a function call.

        """
        # CASE 1: We're in a logging statement
        if arg_0.within_logging_statement():
            if arg_0.within_logging_argument() and arg_0.is_format_call(arg_1):
                arg_0.violations.append((arg_1, STRING_FORMAT_VIOLATION))
                super(LoggingVisitor, arg_0).generic_visit(arg_1)
                return

        arg_2 = arg_0.detect_logging_level(arg_1)

        if arg_2 and arg_0.current_logging_level is None:
            arg_0.current_logging_level = arg_2

        # CASE 2: We're in some other statement
        if arg_2 is None:
            super(LoggingVisitor, arg_0).generic_visit(arg_1)
            return

        # CASE 3: We're entering a new logging statement
        arg_0.current_logging_call = arg_1

        if arg_2 == "warn":
            arg_0.violations.append((arg_1, WARN_VIOLATION))

        arg_0.check_exc_info(arg_1)

        for arg_5, arg_6 in enumerate(iter_child_nodes(arg_1)):
            if arg_5 == 1:
                arg_0.current_logging_argument = arg_6
            if arg_5 >= 1:
                arg_0.check_exception_arg(arg_6)
            if arg_5 > 1 and isinstance(arg_6, keyword) and arg_6.arg == "extra":
                arg_0.current_extra_keyword = arg_6

            super(LoggingVisitor, arg_0).visit(arg_6)

            arg_0.current_logging_argument = None
            arg_0.current_extra_keyword = None

        arg_0.current_logging_call = None
        arg_0.current_logging_level = None


def Func(arg_0, arg_1):
        """
        Process binary operations while processing the first logging argument.

        """
        if arg_0.within_logging_statement() and arg_0.within_logging_argument():
            # handle percent format
            if isinstance(arg_1.op, Mod):
                arg_0.violations.append((arg_1, PERCENT_FORMAT_VIOLATION))
            # handle string concat
            if isinstance(arg_1.op, Add):
                arg_0.violations.append((arg_1, STRING_CONCAT_VIOLATION))
        super(LoggingVisitor, arg_0).generic_visit(arg_1)


def Func(arg_0, arg_1):
        """
        Process keyword arguments.

        """
        if arg_0.should_check_whitelist(arg_1):
            if arg_1.arg not in arg_0.whitelist and not arg_1.arg.startswith("debug_"):
                arg_0.violations.append((arg_0.current_logging_call, WHITELIST_VIOLATION.format(arg_1.arg)))

        if arg_0.should_check_extra_exception(arg_1):
            arg_0.check_exception_arg(arg_1.value)

        super(LoggingVisitor, arg_0).generic_visit(arg_1)


def Func(arg_0, arg_1):
        """
        Helper to get the exception name from an ExceptHandler node in both py2 and py3.

        """
        arg_2 = arg_1.name
        if not arg_2:
            return None

        if version_info < (3,):
            return arg_2.id
        return arg_2


def Func(arg_0, arg_1):
        """Check if value has id attribute and return it.

        :param value: The value to get id from.
        :return: The value.id.
        """
        if not hasattr(arg_1, "id") and hasattr(arg_1, "value"):
            arg_1 = arg_1.value
        return arg_1.id


def Func(arg_0, arg_1):
        """
        Checks if the node is a bare exception name from an except block.

        """
        return isinstance(arg_1, Name) and arg_1.id in arg_0.current_except_names


def Func(arg_0, arg_1):
        """
        Reports a violation if exc_info keyword is used with logging.error or logging.exception.

        """
        if arg_0.current_logging_level not in ('error', 'exception'):
            return

        for arg_2 in arg_1.keywords:
            if arg_2.arg == 'exc_info':
                if arg_0.current_logging_level == 'error':
                    arg_3 = ERROR_EXC_INFO_VIOLATION
                else:
                    arg_3 = REDUNDANT_EXC_INFO_VIOLATION
                arg_0.violations.append((arg_1, arg_3))


def Func(arg_0):
        """Get a json dict of the attributes of this object."""
        return {"id": arg_0.id,
                "compile": arg_0.compile,
                "position": arg_0.position,
                "version": arg_0.version}


def Func(arg_0, arg_1, arg_2=1, arg_3=None):
        """
        Convenience method to create a file from a string.

        This file object's metadata will have the id 'inlined_input'.

        Inputs
        ------
        content -- the content of the file (a string).
        position -- (default 1) rank among all files of the model while parsing
            see FileMetadata
        file_id -- (default 'inlined_input') the file_id that will be used by
            kappa.
        """
        if arg_3 is None:
            arg_3 = 'inlined_input'
        return arg_0(FileMetadata(arg_3, arg_2), arg_1)


def Func(arg_0, arg_1, arg_2=1, arg_3=None):
        """
        Convience method to create a kappa file object from a file on disk

        Inputs
        ------
        fpath -- path to the file on disk
        position -- (default 1) rank among all files of the model while parsing
            see FileMetadata
        file_id -- (default = fpath) the file_id that will be used by kappa.
        """
        if arg_3 is None:
            arg_3 = arg_1
        with open(arg_1) as f:
            arg_4 = f.read()
            arg_5 = str(arg_4)
            arg_6 = FileMetadata(arg_3, arg_2)
            return arg_0(arg_6, arg_5)


def Func(arg_0, arg_1, arg_2=1, arg_3=None):
        """Add a kappa model given in a string to the project."""
        if arg_3 is None:
            arg_3 = arg_0.make_unique_id('inlined_input')
        arg_4 = arg_0.file_create(File.from_string(arg_1, arg_2,
                                                     arg_3))
        return arg_4


def Func(arg_0, arg_1, arg_2=1, arg_3=None):
        """Add a kappa model from a file at given path to the project."""
        if arg_3 is None:
            arg_3 = arg_0.make_unique_id('file_input')
        arg_4 = arg_0.file_create(File.from_file(arg_1, arg_2,
                                                   arg_3))
        return arg_4


def Func(arg_0, arg_1):
    """Delete file from database only if needed.

    When editing and the filefield is a new file,
    deletes the previous file (if any) from the database.
    Call this function immediately BEFORE saving the instance.
    """
    if arg_0.pk:
        arg_2 = type(arg_0)

        # Check if there is a file for the instance in the database
        if arg_2.objects.filter(pk=arg_0.pk).exclude(
            **{'%s__isnull' % arg_1: True}
        ).exclude(
            **{'%s__exact' % arg_1: ''}
        ).exists():
            arg_3 = getattr(
                arg_2.objects.only(arg_1).get(pk=arg_0.pk),
                arg_1
            )
        else:
            arg_3 = None

        # If there is a file, delete it if needed
        if arg_3:
            # When editing and NOT changing the file,
            #   old_file.name == getattr(instance, filefield_name)
            #   returns True. In this case, the file must NOT be deleted.
            # If the file IS being changed, the comparison returns False.
            #   In this case, the old file MUST be deleted.
            if (arg_3.name == getattr(arg_0, arg_1)) is False:
                DatabaseFileStorage().delete(arg_3.name)


def Func(arg_0):
    """Edit the download-link inner text."""

    def get_link_display(arg_1):
        arg_2 = unquote(arg_1.split('%2F')[-1])
        if sys.version_info.major == 2:  # python 2
            from django.utils.encoding import force_unicode
            arg_2 = force_unicode(arg_2)
        return escape(arg_2)

    def get_template_substitution_values(arg_3, arg_4):
        # Used by Django < 1.11
        arg_5 = super(arg_0, arg_3).get_template_substitution_values(arg_4)
        arg_5['initial'] = get_link_display(arg_4.url)
        return arg_5
    setattr(arg_0,
            'get_template_substitution_values',
            get_template_substitution_values)

    def get_context(arg_3, arg_6, arg_4, arg_7):
        arg_8 = super(arg_0, arg_3).get_context(arg_6, arg_4, arg_7)
        if arg_4 and hasattr(arg_4, 'url'):
            arg_8['widget']['display'] = get_link_display(arg_4.url)
        return arg_8
    setattr(arg_0, 'get_context', get_context)

    return arg_0


def Func(arg_0):
        """
        Checks the input and output to see if they are valid

        """
        arg_1 = available_devices()
        if not arg_0.in_idx in arg_1:
            raise OSError("Input device is unavailable")
        arg_2 = arg_1[arg_0.in_idx]
        if not arg_0.out_idx in arg_1:
            raise OSError("Output device is unavailable")
        arg_3 = arg_1[arg_0.out_idx]
        if((arg_2['inputs'] == 0) and (arg_3['outputs']==0)):
            raise StandardError('Invalid input and output devices')
        elif(arg_2['inputs'] == 0):
            raise ValueError('Selected input device has no inputs')
        elif(arg_3['outputs'] == 0):
            raise ValueError('Selected output device has no outputs')
        return True


def Func(arg_0,arg_1):
        """
        Append new samples to the data_capture array and increment the sample counter
        If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0
        then new values are not appended to the data_capture array.

        """
        arg_0.capture_sample_count += len(arg_1)
        if arg_0.Tcapture > 0:
            arg_0.data_capture = np.hstack((arg_0.data_capture,arg_1))
            if (arg_0.Tcapture > 0) and (len(arg_0.data_capture) > arg_0.Ncapture):
                arg_0.data_capture = arg_0.data_capture[-arg_0.Ncapture:]


def Func(arg_0,arg_1,arg_2):
        """
        Append new samples to the data_capture_left array and the data_capture_right
        array and increment the sample counter. If length reaches Tcapture, then the
        newest samples will be kept. If Tcapture = 0 then new values are not appended
        to the data_capture array.

        """
        arg_0.capture_sample_count = arg_0.capture_sample_count + len(arg_1) + len(arg_2)
        if arg_0.Tcapture > 0:
            arg_0.data_capture_left = np.hstack((arg_0.data_capture_left,arg_1))
            arg_0.data_capture_right = np.hstack((arg_0.data_capture_right,arg_2))
            if (len(arg_0.data_capture_left) > arg_0.Ncapture):
                arg_0.data_capture_left = arg_0.data_capture_left[-arg_0.Ncapture:]
            if (len(arg_0.data_capture_right) > arg_0.Ncapture):
                arg_0.data_capture_right = arg_0.data_capture_right[-arg_0.Ncapture:]


def Func(arg_0):
        """
        Add new tic time to the DSP_tic list. Will not be called if
        Tcapture = 0.

        """
        if arg_0.Tcapture > 0:
            arg_0.DSP_tic.append(time.time()-arg_0.start_time)


def Func(arg_0):
        """
        Add new toc time to the DSP_toc list. Will not be called if
        Tcapture = 0.

        """
        if arg_0.Tcapture > 0:
            arg_0.DSP_toc.append(time.time()-arg_0.start_time)


def Func(arg_0,arg_1 = 0.001):
    """

    The average of the root values is used when multiplicity
    is greater than one.

    Mark Wickert October 2016
    """
    arg_2 = [arg_0[0]]
    arg_3 = [1]
    for arg_4 in range(1,len(arg_0)):
        arg_5 = len(arg_2)
        for arg_6 in range(arg_5):
            if abs(arg_0[arg_4]-arg_2[arg_6]) <= arg_1:
                arg_3[arg_6] += 1
                arg_2[arg_6] = (arg_2[arg_6]*(arg_3[arg_6]-1) + arg_0[arg_4])/float(arg_3[arg_6])
                break
        arg_2 = np.hstack((arg_2,arg_0[arg_4]))
        arg_3 = np.hstack((arg_3,[1]))
    return np.array(arg_2), np.array(arg_3)


def Func(arg_0,arg_1,arg_2,arg_3,arg_4,arg_5='H'):
    """
    Cruise control with PI controller and hill disturbance.

    This function returns various system function configurations
    for a the cruise control Case Study example found in
    the supplementary article. The plant model is obtained by the
    linearizing the equations of motion and the controller contains a
    proportional and integral gain term set via the closed-loop parameters
    natuarl frequency wn (rad/s) and damping zeta.

    Parameters
    ----------
    wn : closed-loop natural frequency in rad/s, nominally 0.1
    zeta : closed-loop damping factor, nominally 1.0
    T : vehicle time constant, nominally 10 s
    vcruise : cruise velocity set point, nominally 75 mph
    vmax : maximum vehicle velocity, nominally 120 mph
    tf_mode : 'H', 'HE', 'HVW', or 'HED' controls the system function returned by the function
    'H'   : closed-loop system function V(s)/R(s)
    'HE'  : closed-loop system function E(s)/R(s)
    'HVW' : closed-loop system function V(s)/W(s)
    'HED' : closed-loop system function E(s)/D(s), where D is the hill disturbance input

    Returns
    -------
    b : numerator coefficient ndarray
    a : denominator coefficient ndarray

    Examples
    --------
    >>> # return the closed-loop system function output/input velocity
    >>> b,a = Func(wn,zeta,T,vcruise,vmax,tf_mode='H')
    >>> # return the closed-loop system function loop error/hill disturbance
    >>> b,a = Func(wn,zeta,T,vcruise,vmax,tf_mode='HED')
    """
    arg_6 = arg_2/2.*arg_4/arg_3
    arg_7 = 9.8
    arg_7 *= 3*60**2/5280. # m/s to mph conversion
    arg_8 = arg_2*(2*arg_1*arg_0-1/arg_6)/arg_4
    arg_9 = arg_2*arg_0**2./arg_4
    arg_10 = arg_8*arg_4/arg_2
    print('wn = ', np.sqrt(arg_10/(arg_8/arg_9)))
    print('zeta = ', (arg_10 + 1/arg_6)/(2*arg_0))
    arg_11 = np.array([1, 2*arg_1*arg_0, arg_0**2])
    if arg_5 == 'H':
        arg_12 = np.array([arg_10, arg_0**2])
    elif arg_5 == 'HE':
        arg_12 = np.array([1, 2*arg_1*arg_0-arg_10, 0.])
    elif arg_5 == 'HVW':
        arg_12 = np.array([ 1, arg_0**2/arg_10+1/arg_6, arg_0**2/(arg_10*arg_6)])
        arg_12 *= arg_8
    elif arg_5 == 'HED':
        arg_12 = np.array([arg_7, 0])
    else:
        raise ValueError('tf_mode must be: H, HE, HVU, or HED')
    return arg_12, arg_11


def Func(arg_0,arg_1=2.4e6,arg_2='test.wav'):
    """
    Stereo demod from complex baseband at sampling rate fs.
    Assume fs is 2400 ksps

    Mark Wickert July 2017
    """
    arg_3 = 10
    arg_4 = signal.firwin(64,2*200e3/float(arg_1))
    # Filter and decimate (should be polyphase)
    arg_5 = signal.lfilter(arg_4,1,arg_0)
    arg_6 = ss.downsample(arg_5,arg_3)
    # Apply complex baseband discriminator
    arg_7 = discrim(arg_6)
    # Work with the (3) stereo multiplex signals:
    # Begin by designing a lowpass filter for L+R and DSP demoded (L-R)
    # (fc = 12 KHz)
    arg_8 = signal.firwin(128,2*12e3/(float(arg_1)/arg_3))
    # The L + R term is at baseband, we just lowpass filter to remove
    # other terms above 12 kHz.
    arg_9 = signal.lfilter(arg_8,1,arg_7)
    arg_10 = signal.firwin(128,2*1e3*np.array([19-5,19+5])/(float(arg_1)/arg_3),
                        pass_zero=False);
    arg_11 = signal.lfilter(arg_10,1,arg_7)
    # Lock PLL to 19 kHz pilot
    # A type 2 loop with bandwidth Bn = 10 Hz and damping zeta = 0.707
    # The VCO quiescent frequency is set to 19000 Hz.
    arg_12, arg_13 = pilot_PLL(arg_11,19000,arg_1/arg_3,2,10,0.707)
    # Coherently demodulate the L - R subcarrier at 38 kHz.
    # theta is the PLL output phase at 19 kHz, so to double multiply
    # by 2 and wrap with cos() or sin().
    # First bandpass filter
    arg_14 = signal.firwin(128,2*1e3*np.array([38-5,38+5])/(float(arg_1)/arg_3),
                        pass_zero=False);
    arg_15 = signal.lfilter(arg_14,1,arg_7)
    # Coherently demodulate using the PLL output phase
    arg_15 = 2*np.sqrt(2)*np.cos(2*arg_12)*arg_15
    # Lowpass at 12 kHz to recover the desired DSB demod term
    arg_16 = signal.lfilter(arg_8,1,arg_15)
    # Matrix the y_lmr and y_lpr for form right and left channels:
    arg_17 = arg_9 + arg_16
    arg_18 = arg_9 - arg_16

    # Decimate by N2 (nominally 5)
    arg_19 = 5
    arg_20 = float(arg_1)/(arg_3*arg_19) # (nominally 48 ksps)
    arg_21 = ss.downsample(arg_17,arg_19)
    arg_22 = ss.downsample(arg_18,arg_19)
    # Deemphasize with 75 us time constant to 'undo' the preemphasis
    # applied at the transmitter in broadcast FM.
    # A 1-pole digital lowpass works well here.
    arg_23 = np.exp(-2.1*1e3*2*np.pi/arg_20)
    arg_24 = signal.lfilter([1-arg_23],[1, -arg_23],arg_21)
    arg_25 = signal.lfilter([1-arg_23],[1, -arg_23],arg_22)
    # Place left and righ channels as side-by-side columns in a 2D array
    arg_26 = np.hstack((np.array([arg_24]).T,(np.array([arg_25]).T)))

    ss.to_wav(arg_2, 48000, arg_26/2)
    print('Done!')
    #return z_bb, z_out
    return arg_7, arg_12, arg_9, arg_16, arg_26


def Func(arg_0, arg_1):
    """
    Write IIR SOS Header Files
    File format is compatible with CMSIS-DSP IIR
    Directform II Filter Functions

    Mark Wickert March 2015-October 2016
    """
    arg_2, arg_3 = arg_1.shape
    arg_4 = open(arg_0, 'wt')
    arg_4.write('//define a IIR SOS CMSIS-DSP coefficient array\n\n')
    arg_4.write('#include <stdint.h>\n\n')
    arg_4.write('#ifndef STAGES\n')
    arg_4.write('#define STAGES %d\n' % arg_2)
    arg_4.write('#endif\n')
    arg_4.write('/*********************************************************/\n');
    arg_4.write('/*                     IIR SOS Filter Coefficients       */\n');
    arg_4.write('float32_t ba_coeff[%d] = { //b0,b1,b2,a1,a2,... by stage\n' % (5 * arg_2))
    for arg_5 in range(arg_2):
        if (arg_5 < arg_2 - 1):
            arg_4.write('    %+-13e, %+-13e, %+-13e,\n' % \
                    (arg_1[arg_5, 0], arg_1[arg_5, 1], arg_1[arg_5, 2]))
            arg_4.write('    %+-13e, %+-13e,\n' % \
                    (-arg_1[arg_5, 4], -arg_1[arg_5, 5]))
        else:
            arg_4.write('    %+-13e, %+-13e, %+-13e,\n' % \
                    (arg_1[arg_5, 0], arg_1[arg_5, 1], arg_1[arg_5, 2]))
            arg_4.write('    %+-13e, %+-13e\n' % \
                    (-arg_1[arg_5, 4], -arg_1[arg_5, 5]))
    # for k in range(Ns):
    #     if (k < Ns-1):
    #         f.write('    %15.12f, %15.12f, %15.12f,\n' % \
    #                 (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2]))
    #         f.write('    %15.12f, %15.12f,\n' % \
    #                 (-SOS_mat[k,4],-SOS_mat[k,5]))
    #     else:
    #         f.write('    %15.12f, %15.12f, %15.12f,\n' % \
    #                 (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2]))
    #         f.write('    %15.12f, %15.12f\n' % \
    #                 (-SOS_mat[k,4],-SOS_mat[k,5]))
    arg_4.write('};\n')
    arg_4.write('/*********************************************************/\n')
    arg_4.close()


def Func(arg_0,arg_1,arg_2=0):
    """
    Eye pattern plot of a baseband digital communications waveform.

    The signal must be real, but can be multivalued in terms of the underlying
    modulation scheme. Used for BPSK eye plots in the Case Study article.

    Parameters
    ----------
    x : ndarray of the real input data vector/array
    L : display length in samples (usually two symbols)
    S : start index

    Returns
    -------
    None : A plot window opens containing the eye plot

    Notes
    -----
    Increase S to eliminate filter transients.

    Examples
    --------
    1000 bits at 10 samples per bit with 'rc' shaping.

    >>> import matplotlib.pyplot as plt
    >>> from sk_dsp_comm import digitalcom as dc
    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')
    >>> dc.Func(x,20,60)
    >>> plt.show()
    """
    plt.figure(figsize=(6,4))
    arg_3 = np.arange(0,arg_1+1)
    plt.plot(arg_3,arg_0[arg_2:arg_2+arg_1+1],'b')
    arg_4 = int((len(arg_0) - arg_2)/arg_1)-1
    for arg_5 in range(1,arg_4):
         plt.plot(arg_3,arg_0[arg_2+arg_5*arg_1:arg_2+arg_1+1+arg_5*arg_1],'b')
    plt.grid()
    plt.xlabel('Time Index - n')
    plt.ylabel('Amplitude')
    plt.title('Eye Plot')
    return 0


def Func(arg_0,arg_1,arg_2):
    """
    Sample a baseband digital communications waveform at the symbol spacing.

    Parameters
    ----------
    x : ndarray of the input digital comm signal
    Ns : number of samples per symbol (bit)
    start : the array index to start the sampling

    Returns
    -------
    xI : ndarray of the real part of x following sampling
    xQ : ndarray of the imaginary part of x following sampling

    Notes
    -----
    Normally the signal is complex, so the Func plot contains
    clusters at point  in the complex plane. For a binary signal
    such as BPSK, the point centers are nominally +/-1 on the real
    axis. Start is used to eliminate transients from the FIR
    pulse shaping filters from appearing in the Func plot.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from sk_dsp_comm import digitalcom as dc
    >>> x,b, data = dc.NRZ_bits(1000,10,'rc')

    Add some noise so points are now Funced about +/-1.

    >>> y = dc.cpx_AWGN(x,20,10)
    >>> yI,yQ = dc.Func(y,10,60)
    >>> plt.plot(yI,yQ,'.')
    >>> plt.grid()
    >>> plt.xlabel('In-Phase')
    >>> plt.ylabel('Quadrature')
    >>> plt.axis('equal')
    >>> plt.show()
    """
    arg_3 = np.real(arg_0[arg_2::arg_1])
    arg_4 = np.imag(arg_0[arg_2::arg_1])
    return arg_3, arg_4


def Func(arg_0,arg_1,arg_2,arg_3=100,arg_4=125,arg_5=10,arg_6=0,arg_7='src'):
    """
    This function generates
    """
    arg_8 = int(np.round(arg_4/arg_2))
    print('Ns = ', arg_8)
    print('Rs = ', arg_4/float(arg_8))
    print('EsN0 = ', arg_3, 'dB')
    print('phase = ', arg_6, 'degrees')
    print('pulse = ', arg_7)
    arg_9, arg_10, arg_11 = QPSK_bb(arg_1,arg_8,arg_5,arg_7)
    # Add AWGN to x
    arg_9 = cpx_AWGN(arg_9,arg_3,arg_8)
    arg_12 = np.arange(len(arg_9))
    arg_13 = arg_9*np.exp(1j*2*np.pi*arg_0/float(arg_4)*arg_12) * np.exp(1j*arg_6)
    return arg_13, arg_10, arg_11


def Func(arg_0,arg_1,arg_2=6):
    """
    A truncated square root raised cosine pulse used in digital communications.

    The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
    truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.

    Parameters
    ----------
    Ns : number of samples per symbol
    alpha : excess bandwidth factor on (0, 1), e.g., 0.35
    M : equals RC one-sided symbol truncation factor

    Returns
    -------
    b : ndarray containing the pulse shape

    Notes
    -----
    The pulse shape b is typically used as the FIR filter coefficients
    when forming a pulse shaped digital communications waveform. When
    square root raised cosine (SRC) pulse is used to generate Tx signals and
    at the receiver used as a matched filter (receiver FIR filter), the
    received signal is now raised cosine shaped, thus having zero
    intersymbol interference and the optimum removal of additive white
    noise if present at the receiver input.

    Examples
    --------
    Ten samples per symbol and :math:`\\alpha = 0.35`.

    >>> import matplotlib.pyplot as plt
    >>> from numpy import arange
    >>> from sk_dsp_comm.digitalcom import Func
    >>> b = Func(10,0.35)
    >>> n = arange(-10*6,10*6+1)
    >>> plt.stem(n,b)
    >>> plt.show()
    """
    # Design the filter
    arg_3 = np.arange(-arg_2*arg_0,arg_2*arg_0+1)
    arg_4 = np.zeros(len(arg_3))
    arg_0 *= 1.0
    arg_5 = arg_1
    for arg_6 in range(len(arg_3)):
       if abs(1 - 16*arg_5**2*(arg_3[arg_6]/arg_0)**2) <= np.finfo(np.float).eps/2:
           arg_4[arg_6] = 1/2.*((1+arg_5)*np.sin((1+arg_5)*np.pi/(4.*arg_5))-(1-arg_5)*np.cos((1-arg_5)*np.pi/(4.*arg_5))+(4*arg_5)/np.pi*np.sin((1-arg_5)*np.pi/(4.*arg_5)))
       else:
           arg_4[arg_6] = 4*arg_5/(np.pi*(1 - 16*arg_5**2*(arg_3[arg_6]/arg_0)**2))
           arg_4[arg_6] = arg_4[arg_6]*(np.cos((1+arg_5)*np.pi*arg_3[arg_6]/arg_0) + np.sinc((1-arg_5)*arg_3[arg_6]/arg_0)*(1-arg_5)*np.pi/(4.*arg_5))
    return arg_4


def Func(arg_0, arg_1):
    """
    Convert an unsigned integer to a numpy binary array with the first
    element the MSB and the last element the LSB.
    """
    arg_2 = bin(arg_0 & (2**arg_1-1))[2:].zfill(arg_1)
    return [int(arg_3) for arg_3 in tuple(arg_2)]


def Func(arg_0):
    """
    Convert binary array back a nonnegative integer. The array length is
    the bit width. The first input index holds the MSB and the last holds the LSB.
    """
    arg_1 = len(arg_0)
    arg_2 = 2**np.arange(arg_1-1,-1,-1)
    return int(np.dot(arg_0,arg_2))


def Func(arg_0,arg_1):
        """
        Filter the signal
        """
        arg_2 = signal.lFunc(arg_0.b,[1],arg_1)
        return arg_2


def Func(arg_0,arg_1):
        """
        Filter the signal using second-order sections
        """
        arg_2 = signal.sosfilt(arg_0.sos,arg_1)
        return arg_2


def Func(arg_0=None, arg_1=None, arg_2=False):
    """Celery task decorator. Forces the task to have only one running instance at a time.

    Use with binded tasks (@celery.task(bind=True)).

    Modeled after:
    http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
    http://blogs.it.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/

    Written by @Robpol86.

    :raise OtherInstanceError: If another instance is already running.

    :param function func: The function to decorate, must be also decorated by @celery.task.
    :param int lock_timeout: Lock timeout in seconds plus five more seconds, in-case the task crashes and fails to
        release the lock. If not specified, the values of the task's soft/hard limits are used. If all else fails,
        timeout will be 5 minutes.
    :param bool include_args: Include the md5 checksum of the arguments passed to the task in the Redis key. This allows
        the same task to run with different arguments, only stopping a task from running if another instance of it is
        running with the same arguments.
    """
    if arg_0 is None:
        return partial(Func, arg_1=arg_1, arg_2=arg_2)

    @wraps(arg_0)
    def wrapped(arg_3, *arg_4, **arg_5):
        """Wrapped Celery task, for Func()."""
        # Select the manager and get timeout.
        arg_6 = (
            arg_1 or arg_3.soft_time_limit or arg_3.time_limit
            or arg_3.app.conf.get('CELERYD_TASK_SOFT_TIME_LIMIT')
            or arg_3.app.conf.get('CELERYD_TASK_TIME_LIMIT')
            or (60 * 5)
        )
        arg_7 = _select_manager(arg_3.backend.__class__.__name__)
        arg_8 = arg_7(arg_3, arg_6, arg_2, arg_4, arg_5)

        # Lock and execute.
        with arg_8:
            arg_9 = arg_0(*arg_4, **arg_5)
        return arg_9
    return wrapped


def Func(arg_0):
        """Removed the lock regardless of timeout."""
        arg_1 = arg_0.CELERY_LOCK.format(task_id=arg_0.task_identifier)
        arg_0.celery_self.backend.client.delete(arg_1)


def Func(arg_0, arg_1):
    """Iterator used to iterate in chunks over an array of size `num_samples`.
    At each iteration returns `chunksize` except for the last iteration.
    """
    arg_2 = int(np.mod(arg_0, arg_1))
    arg_1 = int(arg_1)
    for arg_3 in range(int(arg_0) // arg_1):
        yield arg_1
    if arg_2 > 0:
        yield arg_2


def Func(arg_0, arg_1):
    """Reduce with `func`, chunk by chunk, the passed pytable `array`.
    """
    arg_2 = []
    for arg_3 in iter_chunk_slice(arg_1.shape[-1], arg_1.chunkshape[-1]):
        arg_2.append(arg_0(arg_1[..., arg_3]))
    return arg_0(arg_2)


def Func(arg_0):
    """Load the array `data` in the .mat file `fname`."""
    if os.path.exists(arg_0) or os.path.exists(arg_0 + '.mat'):
        return loadmat(arg_0)['data']
    else:
        raise IOError("Can't find PSF file '%s'" % arg_0)


def Func(arg_0=None):
    """
    Check whether the git executable is found.
    """
    if arg_0 is None and GIT_PATH is None:
        return False
    if arg_0 is None: arg_0 = GIT_PATH
    try:
        call([arg_0, '--version'])
        return True
    except OSError:
        return False


def Func(arg_0=None):
    """
    Get the Git version.
    """
    if arg_0 is None: arg_0 = GIT_PATH
    arg_1 = check_output([arg_0, "--version"]).split()[2]
    return arg_1


def Func(arg_0=None):
    """
    Returns whether there are uncommitted changes in the working dir.
    """
    arg_1 = get_status(arg_0)
    arg_2 = (len(arg_1.strip()) == 0)
    return arg_2


def Func(arg_0=None):
    """
    Get one-line description of HEAD commit for repository in current dir.
    """
    if arg_0 is None: arg_0 = GIT_PATH
    arg_1 = check_output([arg_0, "log", "--pretty=format:'%ad %h %s'",
                           "--date=short", "-n1"])
    return arg_1.strip()[1:-1]


def Func(arg_0=None):
    """
    Get the HEAD commit SHA1 of repository in current dir.
    """
    if arg_0 is None: arg_0 = GIT_PATH
    arg_1 = Func_line(arg_0)
    arg_2 = arg_1.split()[1]
    return arg_2


def Func(arg_0='Repository', arg_1=None):
    """
    Print the last commit line and eventual uncommitted changes.
    """
    if arg_1 is None: arg_1 = GIT_PATH

    # If git is available, check fretbursts version
    if not git_path_valid():
        print('\n%s revision unknown (git not found).' % arg_0)
    else:
        arg_2 = get_last_commit_line()
        print('\n{} revision:\n {}\n'.format(arg_0, arg_2))
        if not check_clean_status():
            print('\nWARNING -> Uncommitted changes:')
            print(get_status())


def Func(arg_0, arg_1, arg_2):
        """Store parameters in `params` in `h5file.root.parameters`.

        `nparams` (dict)
            A dict as returned by `get_params()` in `ParticlesSimulation()`
            The format is:
            keys:
                used as parameter name
            values: (2-elements tuple)
                first element is the parameter value
                second element is a string used as "title" (description)
        `attr_params` (dict)
            A dict whole items are stored as attributes in '/parameters'
        """
        for arg_3, arg_4 in arg_1.items():
            arg_5 = arg_4[0] if arg_4[0] is not None else 'none'
            arg_0.h5file.create_array('/parameters', arg_3, obj=arg_5,
                                     title=arg_4[1])
        for arg_3, arg_4 in arg_2.items():
            arg_0.h5file.set_node_attr('/parameters', arg_3, arg_4)


def Func(arg_0, arg_1, arg_2):
        """Return pathlib.Path for a data-file with given hash and prefix.
        """
        arg_3 = '%s_%s*.h*' % (arg_1, arg_0)
        arg_4 = list(arg_2.glob(arg_3))
        if len(arg_4) == 0:
            raise NoMatchError('No matches for "%s"' % arg_3)
        if len(arg_4) > 1:
            raise MultipleMatchesError('More than 1 match for "%s"' % arg_3)
        return arg_4[0]


def Func(arg_0, arg_1, arg_2):
        """Return a RandomState, equal to the input unless rs is None.

        When rs is None, try to get the random state from the
        'last_random_state' attribute in `group`. When not available,
        use `seed` to generate a random state. When seed is None the returned
        random state will have a random seed.
        """
        if arg_0 is None:
            arg_0 = np.random.RandomState(arg_1=arg_1)
            # Try to set the random state from the last session to preserve
            # a single random stream when simulating timestamps multiple times
            if 'last_random_state' in arg_2._v_attrs:
                arg_0.set_state(arg_2._v_attrs['last_random_state'])
                print("INFO: Random state set to last saved state in '%s'." %
                      arg_2._v_name)
            else:
                print("INFO: Random state initialized from seed (%d)." % arg_1)
        return arg_0


def Func(arg_0, arg_1=6):
        """Compact representation of all simulation parameters
        """
        # this can be made more robust for ID > 9 (double digit)
        arg_2 = arg_0.Func_core(arg_1, t_max=True)
        arg_2 += "_ID%d-%d" % (arg_0.ID, arg_0.EID)
        return arg_2


def Func(arg_0):
        """A dict containing all the simulation numeric-parameters.

        The values are 2-element tuples: first element is the value and
        second element is a string describing the parameter (metadata).
        """
        arg_1 = dict(
            D = (arg_0.diffusion_coeff.mean(), 'Diffusion coefficient (m^2/s)'),
            np = (arg_0.num_particles, 'Number of simulated particles'),
            t_step = (arg_0.t_step, 'Simulation time-step (s)'),
            t_max = (arg_0.t_max, 'Simulation total time (s)'),
            ID = (arg_0.ID, 'Simulation ID (int)'),
            EID = (arg_0.EID, 'IPython Engine ID (int)'),
            pico_mol = (arg_0.concentration() * 1e12,
                        'Particles concentration (pM)'))
        return arg_1


def Func(arg_0):
        """Print on-disk array sizes required for current set of parameters."""
        arg_1 = 4
        arg_2 = 1024 * 1024
        arg_3 = arg_0.n_samples * arg_1
        arg_4 = arg_3 * arg_0.num_particles / arg_2
        arg_5 = 3 * arg_3 * arg_0.num_particles / arg_2
        print("  Number of particles:", arg_0.num_particles)
        print("  Number of time steps:", arg_0.n_samples)
        print("  Emission array - 1 particle (float32): %.1f MB" % (arg_3 / arg_2))
        print("  Emission array (float32): %.1f MB" % arg_4)
        print("  Position array (float32): %.1f MB " % arg_5)


def Func(arg_0, arg_1=False, arg_2=True,
                           arg_3=False, arg_4=None, arg_5=1, arg_6='./',
                           arg_7=arg_8,
                           arg_9=2**19, arg_10='times', arg_11=True):
        """Simulate Brownian motion trajectories and emission rates.

        This method performs the Brownian motion simulation using the current
        set of parameters. Before running this method you can check the
        disk-space requirements using :method:`print_sizes`.

        Results are stored to disk in HDF5 format and are accessible in
        in `self.emission`, `self.emission_tot` and `self.position` as
        pytables arrays.

        Arguments:
            save_pos (bool): if True, save the particles 3D trajectories
            total_emission (bool): if True, store only the total emission array
                containing the sum of emission of all the particles.
            rs (RandomState object): random state object used as random number
                generator. If None, use a random state initialized from seed.
            seed (uint): when `rs` is None, `seed` is used to initialize the
                random state, otherwise is ignored.
            wrap_func (function): the function used to apply the boundary
                condition (use :func:`wrap_periodic` or :func:`wrap_mirror`).
            path (string): a folder where simulation data is saved.
            verbose (bool): if False, prints no output.
        """
        if arg_4 is None:
            arg_4 = np.random.RandomState(arg_5=arg_5)
        arg_0.open_store_traj(arg_9=arg_9, arg_10=arg_10,
                             arg_3=arg_3, arg_6=arg_6)
        # Save current random state for reproducibility
        arg_0.traj_group._v_attrs['init_random_state'] = arg_4.get_state()

        arg_14 = arg_0.emission_tot if arg_2 else arg_0.emission

        print('- Start trajectories simulation - %s' % ctime(), flush=True)
        if arg_11:
            print('[PID %d] Diffusion time:' % os.getpid(), end='')
        arg_15 = 0
        arg_16 = arg_0.emission.chunkshape[1]
        arg_17 = arg_16 * arg_0.t_step

        arg_18 = arg_0.particles.positions
        arg_19 = 0
        for arg_20 in iter_chunksize(arg_0.n_samples, arg_16):
            if arg_11:
                arg_21 = int(arg_17 * (arg_15 + 1))
                if arg_21 > arg_19:
                    print(' %ds' % arg_21, end='', flush=True)
                    arg_19 = arg_21

            arg_22, arg_23 = arg_0._sim_trajectories(arg_20, arg_18, arg_4,
                                             arg_2=arg_2,
                                             arg_1=arg_1, arg_3=arg_3,
                                             arg_7=arg_7)

            ## Append em to the permanent storage
            # if total_emission, data is just a linear array
            # otherwise is a 2-D array (self.num_particles, c_size)
            arg_14.append(arg_23)
            if arg_1:
                arg_0.position.append(np.vstack(arg_22).astype('float32'))
            arg_15 += 1
            arg_0.store.h5file.flush()

        # Save current random state
        arg_0.traj_group._v_attrs['last_random_state'] = arg_4.get_state()
        arg_0.store.h5file.flush()
        print('\n- End trajectories simulation - %s' % ctime(), flush=True)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5,
                        arg_6=0, arg_7=10, arg_8=True):
        """Simulate timestamps from emission trajectories.

        Uses attributes: `.t_step`.

        Returns:
            A tuple of two arrays: timestamps and particles.
        """
        arg_9 = sim_timetrace_bg(arg_3, arg_1, arg_2,
                                        arg_0.t_step, arg_5=arg_5)
        arg_10 = arg_3.shape[0]
        if arg_2 is not None:
            arg_10 += 1
        assert arg_9.shape == (arg_10, arg_3.shape[1])
        arg_11 = arg_9.max()
        if arg_11 == 0:
            return np.array([], dtype=np.int64), np.array([], dtype=np.int64)

        arg_12 = arg_4 * arg_7
        arg_13 = arg_12 + arg_9.shape[1] * arg_7
        arg_14 = np.arange(arg_12, arg_13, arg_7, dtype='int64')

        # Loop for each particle to compute timestamps
        arg_15 = []
        arg_16 = []
        for arg_17, arg_18 in enumerate(arg_9):
            # Compute timestamps for particle ip for all bins with counts
            arg_19 = []
            for arg_20 in range(1, arg_11 + 1):
                arg_19.append(arg_14[arg_18 >= arg_20])

            # Stack the timestamps from different "counts"
            arg_21 = np.hstack(arg_19)
            # Append current particle
            arg_15.append(arg_21)
            arg_16.append(np.full(arg_21.size, arg_17 + arg_6, dtype='u1'))

        # Merge the arrays of different particles
        arg_22 = np.hstack(arg_15)
        arg_23 = np.hstack(arg_16)

        if arg_8:
            # Sort timestamps inside the merged chunk
            arg_24 = arg_22.argsort(kind='mergesort')
            arg_22 = arg_22[arg_24]
            arg_23 = arg_23[arg_24]

        return arg_22, arg_23


def Func(arg_0, arg_1, arg_2, arg_3,
                                arg_4=None, arg_5=1, arg_6=2**16,
                                arg_7=None, arg_8=False,
                                arg_9=False, arg_10=10,
                                arg_11=None, arg_12=None, arg_13=None):
        """Compute one timestamps array for a mixture of N populations.

        Timestamp data are saved to disk and accessible as pytables arrays in
        `._timestamps` and `._tparticles`.
        The background generated timestamps are assigned a
        conventional particle number (last particle index + 1).

        Arguments:
            max_rates (list): list of the peak max emission rate for each
                population.
            populations (list of slices): slices to `self.particles`
                defining each population.
            bg_rate (float, cps): rate for a Poisson background process
            rs (RandomState object): random state object used as random number
                generator. If None, use a random state initialized from seed.
            seed (uint): when `rs` is None, `seed` is used to initialize the
                random state, otherwise is ignored.
            chunksize (int): chunk size used for the on-disk timestamp array
            comp_filter (tables.Filter or None): compression filter to use
                for the on-disk `timestamps` and `tparticles` arrays.
                If None use default compression.
            overwrite (bool): if True, overwrite any pre-existing timestamps
                array. If False, never overwrite. The outcome of simulating an
                existing array is controlled by `skip_existing` flag.
            skip_existing (bool): if True, skip simulation if the same
                timestamps array is already present.
            scale (int): `self.t_step` is multiplied by `scale` to obtain the
                timestamps units in seconds.
            path (string): folder where to save the data.
            timeslice (float or None): timestamps are simulated until
                `timeslice` seconds. If None, simulate until `self.t_max`.
        """
        arg_0.open_store_timestamp(arg_6=arg_6, arg_11=arg_11)
        arg_4 = arg_0._get_group_randomstate(arg_4, arg_5, arg_0.ts_group)
        if arg_12 is None:
            arg_12 = arg_0.emission.chunkshape[1]
        arg_14 = arg_0.n_samples
        if arg_13 is not None:
            arg_14 = arg_13 // arg_0.t_step

        arg_15 = arg_0._get_ts_name_mix(arg_1, arg_2, arg_3, arg_4=arg_4)
        arg_16 = dict(arg_15=arg_15, clk_p=arg_0.t_step / arg_10,
                  arg_1=arg_1, arg_3=arg_3, arg_2=arg_2,
                  num_particles=arg_0.num_particles,
                  bg_particle=arg_0.num_particles,
                  arg_8=arg_8, arg_6=arg_6)
        if arg_7 is not None:
            arg_16.update(arg_7=arg_7)
        try:
            arg_0._timestamps, arg_0._tparticles = (arg_0.ts_store
                                                  .add_timestamps(**arg_16))
        except ExistingArrayError as e:
            if arg_9:
                print(' - Skipping already present timestamps array.')
                return
            else:
                raise e

        arg_0.ts_group._v_attrs['init_random_state'] = arg_4.get_state()
        arg_0._timestamps.attrs['init_random_state'] = arg_4.get_state()
        arg_0._timestamps.attrs['PyBroMo'] = __version__

        arg_22, arg_23 = [], []
        # Load emission in chunks, and save only the final timestamps
        arg_24 = [None] * (len(arg_1) - 1) + [arg_3]
        arg_25 = 0
        for arg_26, arg_27 in iter_chunk_index(arg_14, arg_12):

            arg_28 = np.around(arg_26 * arg_0.t_step, decimals=0)
            if arg_28 > arg_25:
                print(' %.1fs' % arg_28, end='', flush=True)
                arg_25 = arg_28

            arg_29 = arg_0.emission[:, arg_26:arg_27]

            arg_30, arg_31 = \
                arg_0._sim_timestamps_populations(
                    arg_29, arg_1, arg_2, arg_24, arg_26,
                    arg_4, arg_10)

            # Save sorted timestamps (suffix '_s') and corresponding particles
            arg_22.append(arg_30)
            arg_23.append(arg_31)

        for arg_32, arg_33 in zip(arg_22, arg_23):
            arg_0._timestamps.append(arg_32)
            arg_0._tparticles.append(arg_33)

        # Save current random state so it can be resumed in the next session
        arg_0.ts_group._v_attrs['last_random_state'] = arg_4.get_state()
        arg_0._timestamps.attrs['last_random_state'] = arg_4.get_state()
        arg_0.ts_store.h5file.flush()


def Func(arg_0, arg_1, arg_2, arg_3):
    """Merge donor and acceptor timestamps and particle arrays.

    Parameters:
        ts_d (array): donor timestamp array
        ts_par_d (array): donor particles array
        ts_a (array): acceptor timestamp array
        ts_par_a (array): acceptor particles array

    Returns:
        Arrays: timestamps, acceptor bool mask, timestamp particle
    """
    arg_4 = np.hstack([arg_0, arg_2])
    arg_5 = np.hstack([arg_1, arg_3])
    arg_6 = np.hstack([np.zeros(arg_0.shape[0], dtype=bool),
                      np.ones(arg_2.shape[0], dtype=bool)])
    arg_7 = arg_4.argsort()
    return arg_4[arg_7], arg_6[arg_7], arg_5[arg_7]


def Func(arg_0, arg_1):
    """Diffusion coefficients of the two specified populations.
    """
    arg_2 = arg_0.diffusion_coeff_counts
    if len(arg_2) == 1:
        arg_3 = [arg_6.stop - arg_6.start for arg_6 in arg_1]
        assert arg_2[0][1] >= sum(arg_3)
        arg_2 = [(arg_2[0][0], ps) for ps in arg_3]

    arg_4 = []
    arg_5 = 0  # start index of diffusion-based populations
    for arg_6, (arg_7, arg_8) in zip(arg_1, arg_2):
        arg_4.append(arg_7)
        assert arg_6.start >= arg_5
        assert arg_6.stop <= arg_5 + arg_8
        arg_5 += arg_8
    return arg_4


def Func(arg_0, arg_1):
    """2-tuple of slices for selection of two populations.
    """
    arg_2 = []
    arg_3 = 0
    for arg_4 in arg_1:
        arg_2.append(slice(arg_3, arg_3 + arg_4))
        arg_3 += arg_4
    return arg_2


def Func(arg_0, arg_1):
        """Compute hash of D and A timestamps for single-step D+A case.
        """
        arg_0.hash_d = hash_(arg_1.get_state())[:6]
        arg_0.hash_a = arg_0.hash_d


def Func(arg_0):
        """Merge donor and acceptor timestamps, computes `ts`, `a_ch`, `part`.
        """
        print(' - Merging D and A timestamps', flush=True)
        arg_1, arg_2 = arg_0.S.get_timestamps_part(arg_0.name_timestamps_d)
        arg_3, arg_4 = arg_0.S.get_timestamps_part(arg_0.name_timestamps_a)
        arg_5, arg_6, arg_7 = Func(arg_1, arg_2, arg_3, arg_4)
        assert arg_6.sum() == arg_3.shape[0]
        assert (~arg_6).sum() == arg_1.shape[0]
        assert arg_6.size == arg_3.shape[0] + arg_1.shape[0]
        arg_0.ts, arg_0.a_ch, arg_0.part = arg_5, arg_6, arg_7
        arg_0.clk_p = arg_1.attrs['clk_p']


def Func(arg_0, arg_1=None, arg_2=True, arg_3=None):
        """Create a smFRET Photon-HDF5 file with current timestamps."""
        arg_4 = arg_0.filepath
        if arg_3 is not None:
            arg_4 = Path(arg_3, arg_4.name)
        arg_0.merge_da()
        arg_5 = arg_0._make_photon_hdf5(arg_1=arg_1)
        phc.hdf5.Func(arg_5, h5_fname=str(arg_4),
                                  arg_2=arg_2)


def Func(arg_0, arg_1='/', arg_2='user', arg_3=False):
    """Print the HDF5 attributes for `node_name`.

    Parameters:
        data_file (pytables HDF5 file object): the data file to print
        node_name (string): name of the path inside the file to be printed.
            Can be either a group or a leaf-node. Default: '/', the root node.
        which (string): Valid values are 'user' for user-defined attributes,
            'sys' for pytables-specific attributes and 'all' to print both
            groups of attributes. Default 'user'.
        compress (bool): if True displays at most a line for each attribute.
            Default False.
    """
    arg_4 = arg_0.get_node(arg_1)
    print ('List of attributes for:\n  %s\n' % arg_4)
    for arg_5 in arg_4._v_attrs._f_list():
        print ('\t%s' % arg_5)
        arg_6 = repr(arg_4._v_attrs[arg_5])
        if arg_3:
            arg_6 = arg_6.split('\n')[0]
        print ("\t    %s" % arg_6)


def Func(arg_0, arg_1='/'):
    """Print all the sub-groups in `group` and leaf-nodes children of `group`.

    Parameters:
        data_file (pytables HDF5 file object): the data file to print
        group (string): path name of the group to be printed.
            Default: '/', the root node.
    """
    arg_2 = arg_0.get_node(arg_1)
    print ('Groups in:\n  %s\n' % arg_2)

    for arg_3 in arg_2._f_walk_groups():
        if arg_3 is not arg_2:
            print ('    %s' % arg_3)

    print ('\nLeaf-nodes in %s:' % arg_1)
    for arg_3 in arg_2._v_leaves.itervalues():
        arg_4 = arg_3.shape
        if len(arg_4) == 0:
            arg_4 = arg_3.read()
        print ('\t%s, %s' % (arg_3.name, arg_4))
        if len(arg_3.title) > 0:
            print ('\t    %s' % arg_3.title)


def Func(arg_0, arg_1, arg_2, arg_3=64, arg_4=1, arg_5=arg_6(), arg_7=1, arg_8=None):
        """Train model on given training examples and return the list of costs after each minibatch is processed.

        Args:
          trX (list) -- Inputs
          trY (list) -- Outputs
          batch_size (int, optional) -- number of examples in a minibatch (default 64)
          n_epochs (int, optional)  -- number of epochs to train for (default 1)
          len_filter (object, optional) -- object to filter training example by length (default LenFilter())
          snapshot_freq (int, optional) -- number of epochs between saving model snapshots (default 1)
          path (str, optional) -- prefix of path where model snapshots are saved.
            If None, no snapshots are saved (default None)

        Returns:
          list -- costs of model after processing each minibatch
        """
        if arg_5 is not None:
            arg_1, arg_2 = arg_5.filter(arg_1, arg_2)
        arg_2 = standardize_targets(arg_2, cost=arg_0.cost)

        arg_9 = 0.
        arg_10 = time()
        arg_11 = []
        for arg_12 in range(arg_4):
            arg_13 = []
            for arg_14, arg_15 in arg_0.iterator.iterXY(arg_1, arg_2):
                arg_16 = arg_0._train(arg_14, arg_15)
                arg_13.append(arg_16)
                arg_9 += len(arg_15)
                if arg_0.verbose >= 2:
                    arg_17 = arg_9 / (time() - arg_10)
                    arg_18 = len(arg_2) - arg_9 % len(arg_2)
                    arg_19 = arg_18/arg_17
                    sys.stdout.write("\rEpoch %d Seen %d samples Avg cost %0.4f Time left %d seconds" % (arg_12, arg_9, np.mean(arg_13[-250:]), arg_19))
                    sys.stdout.flush()
            arg_11.extend(arg_13)

            arg_20 = "Epoch %d Seen %d samples Avg cost %0.4f Time elapsed %d seconds" % (arg_12, arg_9, np.mean(arg_13[-250:]), time() - arg_10)
            if arg_0.verbose >= 2:
                sys.stdout.write("\r"+arg_20)
                sys.stdout.flush()
                sys.stdout.write("\n")
            elif arg_0.verbose == 1:
                print(arg_20)
            if arg_8 and arg_12 % arg_7 == 0:
                save(arg_0, "{0}.{1}".format(arg_8, arg_12))
        return arg_11


def Func(arg_0=None, arg_1='MONGODB_', **arg_2):
    """Sets defaults for ``class Meta`` declarations.

    Arguments can either be extracted from a `module` (in that case
    all attributes starting from `prefix` are used):

    >>> import foo
    >>> Func(foo)

    or passed explicictly as keyword arguments:

    >>> Func(database='foo')

    .. warning:: Current implementation is by no means thread-safe --
                 use it wisely.
    """
    if arg_0 is not None and isinstance(arg_0, types.ModuleType):
        # Search module for MONGODB_* attributes and converting them
        # to _Options' values, ex: MONGODB_PORT ==> port.
        arg_3 = ((attr.replace(arg_1, '').lower(), value)
                 for attr, value in vars(arg_0).items()
                 if attr.startswith(arg_1))

        _Options._Func(**dict(arg_3))
    elif arg_2:
        _Options._Func(**arg_2)


def Func(arg_0):
    """Converts a given string from CamelCase to under_score.

    >>> Func('FooBar')
    'foo_bar'
    """
    arg_1 = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', arg_0)
    arg_1 = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', arg_1)
    return arg_1.lower()


def Func(arg_0=(10, 10), arg_1=(10, 10)) -> VAO:
    """
    Generates a plane on the xz axis of a specific size and resolution.
    Normals and texture coordinates are also included.

    Args:
        size: (x, y) tuple
        resolution: (x, y) tuple

    Returns:
        A :py:class:`demosys.opengl.vao.VAO` instance
    """
    arg_2, arg_3 = arg_0
    arg_4, arg_5 = arg_1
    arg_6, arg_7 = arg_2 / arg_4, arg_3 / arg_5  # step
    arg_8, arg_9 = -arg_2 / 2, -arg_3 / 2  # start offset

    def gen_pos():
        for arg_10 in range(arg_5):
            for arg_11 in range(arg_4):
                yield arg_8 + arg_11 * arg_6
                yield 0
                yield arg_9 + arg_10 * arg_7

    def gen_uv():
        for arg_10 in range(arg_5):
            for arg_11 in range(arg_4):
                yield arg_11 / (arg_4 - 1)
                yield 1 - arg_10 / (arg_5 - 1)

    def gen_normal():
        for arg_12 in range(arg_4 * arg_5):
            yield 0.0
            yield 1.0
            yield 0.0

    def gen_index():
        for arg_10 in range(arg_5 - 1):
            for arg_11 in range(arg_4 - 1):
                # quad poly left
                yield arg_10 * arg_5 + arg_11 + 1
                yield arg_10 * arg_5 + arg_11
                yield arg_10 * arg_5 + arg_11 + arg_4
                # quad poly right
                yield arg_10 * arg_5 + arg_11 + 1
                yield arg_10 * arg_5 + arg_11 + arg_4
                yield arg_10 * arg_5 + arg_11 + arg_4 + 1

    arg_13 = numpy.fromiter(gen_pos(), dtype=numpy.float32)
    arg_14 = numpy.fromiter(gen_uv(), dtype=numpy.float32)
    arg_15 = numpy.fromiter(gen_normal(), dtype=numpy.float32)
    arg_16 = numpy.fromiter(gen_index(), dtype=numpy.uint32)

    arg_17 = VAO("Func", mode=moderngl.TRIANGLES)

    arg_17.buffer(arg_13, '3f', ['in_position'])
    arg_17.buffer(arg_14, '2f', ['in_uv'])
    arg_17.buffer(arg_15, '3f', ['in_normal'])

    arg_17.index_buffer(arg_16, index_element_size=4)

    return arg_17


def Func(arg_0):
        """
        Deferred Funcing of the scene

        :param scene: The scene object
        :param file: Resolved path if changed by finder
        """
        arg_0.path = arg_0.find_scene(arg_0.meta.path)
        if not arg_0.path:
            raise ValueError("Scene '{}' not found".format(arg_0.meta.path))

        arg_0.scene = Scene(arg_0.path)

        # Load gltf json file
        if arg_0.path.suffix == '.gltf':
            arg_0.Func_gltf()

        # Load binary gltf file
        if arg_0.path.suffix == '.glb':
            arg_0.Func_glb()

        arg_0.meta.check_version()
        arg_0.meta.check_extensions(arg_0.supported_extensions)
        arg_0.Func_images()
        arg_0.Func_samplers()
        arg_0.Func_textures()
        arg_0.Func_materials()
        arg_0.Func_meshes()
        arg_0.Func_nodes()

        arg_0.scene.calc_scene_bbox()
        arg_0.scene.prepare()

        return arg_0.scene


def Func(arg_0):
        """Loads a binary gltf file"""
        with open(arg_0.path, 'rb') as fd:
            # Check header
            arg_1 = fd.read(4)
            if arg_1 != GLTF_MAGIC_HEADER:
                raise ValueError("{} has incorrect header {} != {}".format(arg_0.path, arg_1, GLTF_MAGIC_HEADER))

            arg_2 = struct.unpack('<I', fd.read(4))[0]
            if arg_2 != 2:
                raise ValueError("{} has unsupported version {}".format(arg_0.path, arg_2))

            # Total file size including headers
            arg_3 = struct.unpack('<I', fd.read(4))[0]  # noqa

            # Chunk 0 - json
            arg_4 = struct.unpack('<I', fd.read(4))[0]
            arg_5 = fd.read(4)
            if arg_5 != b'JSON':
                raise ValueError("Expected JSON chunk, not {} in file {}".format(arg_5, arg_0.path))

            arg_6 = fd.read(arg_4).decode()

            # chunk 1 - binary buffer
            arg_7 = struct.unpack('<I', fd.read(4))[0]
            arg_8 = fd.read(4)
            if arg_8 != b'BIN\x00':
                raise ValueError("Expected BIN chunk, not {} in file {}".format(arg_8, arg_0.path))

            arg_0.meta = GLTFMeta(arg_0.path, json.loads(arg_6), binary_buffer=fd.read(arg_7))


def Func(arg_0, arg_1):
        """Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive"""
        arg_2 = []
        for arg_3, arg_4 in arg_1.attributes.items():
            arg_5 = VBOInfo(*arg_4.info())
            arg_5.attributes.append((arg_3, arg_5.components))

            if arg_2 and arg_2[-1].buffer_view == arg_5.buffer_view:
                if arg_2[-1].interleaves(arg_5):
                    arg_2[-1].merge(arg_5)
                    continue

            arg_2.append(arg_5)

        return arg_2


def Func(arg_0, arg_1):
        """Does the buffer interleave with this one?"""
        return arg_1.byte_offset == arg_0.component_type.size * arg_0.components


def Func(arg_0):
        """Create the VBO"""
        arg_1 = NP_COMPONENT_DTYPE[arg_0.component_type.value]
        arg_2 = numpy.frombuffer(
            arg_0.buffer.read(byte_length=arg_0.byte_length, byte_offset=arg_0.byte_offset),
            count=arg_0.count * arg_0.components,
            arg_1=arg_1,
        )
        return arg_1, arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Set the 3D position of the camera

        :param x: float
        :param y: float
        :param z: float
        """
        arg_0.position = Vector3([arg_1, arg_2, arg_3])


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Look at a specific point

        :param vec: Vector3 position
        :param pos: python list [x, y, x]
        :return: Camera matrix
        """
        if arg_2 is None:
            arg_1 = Vector3(arg_2)

        if arg_1 is None:
            raise ValueError("vector or pos must be set")

        return arg_0._gl_Func(arg_0.position, arg_1, arg_0._up)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        The standard lookAt method

        :param pos: current position
        :param target: target position to look at
        :param up: direction up
        """
        arg_4 = vector.normalise(arg_1 - arg_2)
        arg_5 = vector.normalise(vector3.cross(vector.normalise(arg_3), arg_4))
        arg_6 = vector3.cross(arg_4, arg_5)

        arg_7 = matrix44.create_identity()
        arg_7[3][0] = -arg_1.x
        arg_7[3][1] = -arg_1.y
        arg_7[3][2] = -arg_1.z

        arg_8 = matrix44.create_identity()
        arg_8[0][0] = arg_5[0]  # -- X
        arg_8[1][0] = arg_5[1]
        arg_8[2][0] = arg_5[2]
        arg_8[0][1] = arg_6[0]  # -- Y
        arg_8[1][1] = arg_6[1]
        arg_8[2][1] = arg_6[2]
        arg_8[0][2] = arg_4[0]  # -- Z
        arg_8[1][2] = arg_4[1]
        arg_8[2][2] = arg_4[2]

        return matrix44.multiply(arg_7, arg_8)


def Func(arg_0, arg_1, arg_2):
        """
        Set the camera position move state

        :param direction: What direction to update
        :param activate: Start or stop moving in the direction
        """
        if arg_1 == RIGHT:
            arg_0._xdir = POSITIVE if arg_2 else STILL
        elif arg_1 == LEFT:
            arg_0._xdir = NEGATIVE if arg_2 else STILL
        elif arg_1 == FORWARD:
            arg_0._zdir = NEGATIVE if arg_2 else STILL
        elif arg_1 == BACKWARD:
            arg_0._zdir = POSITIVE if arg_2 else STILL
        elif arg_1 == UP:
            arg_0._ydir = POSITIVE if arg_2 else STILL
        elif arg_1 == DOWN:
            arg_0._ydir = NEGATIVE if arg_2 else STILL


def Func(arg_0, arg_1, arg_2):
        """Translate string into character texture positions"""
        for arg_3, arg_4 in enumerate(arg_1):
            if arg_3 == arg_2:
                break

            yield arg_0._meta.characters - 1 - arg_0._ct[arg_4]


def Func(arg_0=None, arg_1=None, arg_2=None):
    """
    Initialize, load and run

    :param manager: The effect manager to use
    """
    from demosys.effects.registry import Effect
    from demosys.scene import camera

    arg_0.timeline = arg_2

    # Inject attributes into the base Effect class
    setattr(Effect, '_window', arg_0)
    setattr(Effect, '_ctx', arg_0.ctx)
    setattr(Effect, '_project', arg_1)

    # Set up the default system camera
    arg_0.sys_camera = camera.SystemCamera(aspect=arg_0.aspect_ratio, fov=60.0, near=1, far=1000)
    setattr(Effect, '_sys_camera', arg_0.sys_camera)

    print("Loading started at", time.time())
    arg_1.load()

    # Initialize timer
    arg_4 = import_string(settings.TIMER)
    arg_0.timer = arg_4()
    arg_0.timer.start()


def Func(arg_0, arg_1=None, arg_2=None, arg_3=True):
        """Draw scene and mesh bounding boxes"""
        arg_1 = arg_1.astype('f4').tobytes()
        arg_2 = arg_2.astype('f4').tobytes()

        # Scene bounding box
        arg_0.bbox_program["m_proj"].write(arg_1)
        arg_0.bbox_program["m_view"].write(arg_0._view_matrix.astype('f4').tobytes())
        arg_0.bbox_program["m_cam"].write(arg_2)
        arg_0.bbox_program["bb_min"].write(arg_0.bbox_min.astype('f4').tobytes())
        arg_0.bbox_program["bb_max"].write(arg_0.bbox_max.astype('f4').tobytes())
        arg_0.bbox_program["color"].value = (1.0, 0.0, 0.0)
        arg_0.bbox_vao.render(arg_0.bbox_program)

        if not arg_3:
            return

        # Draw bounding box for children
        for arg_6 in arg_0.root_nodes:
            arg_6.Func(arg_1, arg_2, arg_0.bbox_program, arg_0.bbox_vao)


def Func(arg_0, arg_1=None):
        """Applies mesh programs to meshes"""
        if not arg_1:
            arg_1 = [ColorProgram(), TextureProgram(), FallbackProgram()]

        for arg_2 in arg_0.meshes:
            for arg_3 in arg_1:
                arg_4 = arg_3.apply(arg_2)
                if arg_4 is not None:
                    if isinstance(arg_4, MeshProgram):
                        arg_2.mesh_program = arg_3
                        break
                    else:
                        raise ValueError("apply() must return a MeshProgram instance, not {}".format(type(arg_4)))

            if not arg_2.mesh_program:
                print("WARING: No mesh program applied to '{}'".format(arg_2.name))


def Func(arg_0):
        """Calculate scene bbox"""
        arg_1, arg_2 = None, None
        for arg_3 in arg_0.root_nodes:
            arg_1, arg_2 = arg_3.calc_global_bbox(
                matrix44.create_identity(),
                arg_1,
                arg_2
            )

        arg_0.bbox_min = arg_1
        arg_0.bbox_max = arg_2

        arg_0.diagonal_size = vector3.length(arg_0.bbox_max - arg_0.bbox_min)


def Func(arg_0, arg_1=(-10.0, 10.0), arg_2=(-10.0, 10.0), arg_3=(-10.0, 10.0), arg_4=None) -> VAO:
    """
    Generates random positions inside a confied box.

    Args:
        count (int): Number of points to generate

    Keyword Args:
        range_x (tuple): min-max range for x axis: Example (-10.0. 10.0)
        range_y (tuple): min-max range for y axis: Example (-10.0. 10.0)
        range_z (tuple): min-max range for z axis: Example (-10.0. 10.0)
        seed (int): The random seed

    Returns:
        A :py:class:`demosys.opengl.vao.VAO` instance
    """
    random.seed(arg_4)

    def gen():
        for arg_5 in range(arg_0):
            yield random.uniform(*arg_1)
            yield random.uniform(*arg_2)
            yield random.uniform(*arg_3)

    arg_6 = numpy.fromiter(gen(), arg_0=arg_0 * 3, dtype=numpy.float32)

    arg_7 = VAO("geometry:Func", mode=moderngl.POINTS)
    arg_7.buffer(arg_6, '3f', ['in_position'])

    return arg_7


def Func(arg_0):
        """Play the music"""
        if arg_0.initialized:
            mixer.music.unpause()
        else:
            mixer.music.play()
            # FIXME: Calling play twice to ensure the music is actually playing
            mixer.music.play()
            arg_0.initialized = True
        arg_0.paused = False


def Func(arg_0, arg_1, arg_2):
        """
        Draw framebuffers for debug purposes.
        We need to supply near and far plane so the depth buffer can be linearized when visualizing.

        :param near: Projection near value
        :param far: Projection far value
        """
        arg_0.ctx.disable(moderngl.DEPTH_TEST)

        helper.draw(arg_0.gbuffer.color_attachments[0], pos=(0.0, 0.0), scale=(0.25, 0.25))
        helper.draw(arg_0.gbuffer.color_attachments[1], pos=(0.5, 0.0), scale=(0.25, 0.25))
        helper.draw_depth(arg_0.gbuffer.depth_attachment, arg_1, arg_2, pos=(1.0, 0.0), scale=(0.25, 0.25))
        helper.draw(arg_0.lightbuffer.color_attachments[0], pos=(1.5, 0.0), scale=(0.25, 0.25))


def Func(arg_0, arg_1, arg_2):
        """Render light volumes"""
        # Draw light volumes from the inside
        arg_0.ctx.front_face = 'cw'
        arg_0.ctx.blend_func = moderngl.ONE, moderngl.ONE

        helper._depth_sampler.use(location=1)
        with arg_0.lightbuffer_scope:
            for arg_6 in arg_0.point_lights:
                # Calc light properties
                arg_7 = arg_6.radius
                arg_8 = matrix44.multiply(arg_6.matrix, arg_1)
                # Draw the light volume
                arg_0.point_light_shader["m_proj"].write(arg_2.tobytes())
                arg_0.point_light_shader["m_light"].write(arg_8.astype('f4').tobytes())
                arg_0.gbuffer.color_attachments[1].use(location=0)
                arg_0.point_light_shader["g_normal"].value = 0
                arg_0.gbuffer.depth_attachment.use(location=1)
                arg_0.point_light_shader["g_depth"].value = 1
                arg_0.point_light_shader["screensize"].value = (arg_0.width, arg_0.height)
                arg_0.point_light_shader["proj_const"].value = arg_2.projection_constants
                arg_0.point_light_shader["radius"].value = arg_7
                arg_0.unit_cube.render(arg_0.point_light_shader)

        helper._depth_sampler.clear(location=1)


def Func(arg_0, arg_1, arg_2):
        """Render outlines of light volumes"""
        arg_0.ctx.enable(moderngl.BLEND)
        arg_0.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA

        for arg_5 in arg_0.point_lights:
            arg_6 = matrix44.multiply(arg_5.matrix, arg_1)
            arg_7 = arg_5.radius
            arg_0.debug_shader["m_proj"].write(arg_2.tobytes())
            arg_0.debug_shader["m_mv"].write(arg_6.astype('f4').tobytes())
            arg_0.debug_shader["size"].value = arg_7
            arg_0.unit_cube.render(arg_0.debug_shader, mode=moderngl.LINE_STRIP)

        arg_0.ctx.disable(moderngl.BLEND)


def Func(arg_0, arg_1: arg_2, arg_3: arg_2):
        """Load a single shader"""
        if arg_3:
            arg_4 = arg_0.find_program(arg_3)
            if not arg_4:
                raise ValueError("Cannot find {} shader '{}'".format(arg_1, arg_3))

            print("Loading:", arg_3)

            with open(arg_4, 'r') as fd:
                return fd.read()


def Func(arg_0):
        """Load a texture array"""
        arg_0._open_image()

        arg_1, arg_2, arg_3 = arg_0.image.size[0], arg_0.image.size[1] // arg_0.layers, arg_0.layers
        arg_4, arg_5 = image_data(arg_0.image)

        arg_6 = arg_0.ctx.texture_array(
            (arg_1, arg_2, arg_3),
            arg_4,
            arg_5,
        )
        arg_6.extra = {'meta': arg_0.meta}

        if arg_0.meta.mipmap:
            arg_6.build_mipmaps()

        arg_0._close_image()

        return arg_6


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=0):
        """
        Draw the mesh using the assigned mesh program

        :param projection_matrix: projection_matrix (bytes)
        :param view_matrix: view_matrix (bytes)
        :param camera_matrix: camera_matrix (bytes)
        """
        if arg_0.mesh_program:
            arg_0.mesh_program.Func(
                arg_0,
                arg_1=arg_1,
                arg_2=arg_2,
                arg_3=arg_3,
                arg_4=arg_4
            )


def Func(arg_0, arg_1: arg_2):
        """
        Set the current time jumping in the timeline.

        Args:
            value (float): The new time
        """
        if arg_1 < 0:
            arg_1 = 0

        arg_0.controller.row = arg_0.rps * arg_1


def Func(arg_0, arg_1: arg_2, arg_3: arg_2, arg_4: arg_5.Framebuffer):
        """
        Draw function called by the system every frame when the effect is active.
        This method raises ``NotImplementedError`` unless implemented.

        Args:
            time (float): The current time in seconds.
            frametime (float): The time the previous frame used to render in seconds.
            target (``moderngl.Framebuffer``): The target FBO for the effect.
        """
        raise NotImplementedError("Func() is not implemented")


def Func(arg_0, arg_1: arg_2) -> moderngl.Program:
        """
        Get a program by its label

        Args:
            label (str): The label for the program

        Returns: py:class:`moderngl.Program` instance
        """
        return arg_0._project.Func(arg_1)


def Func(arg_0, arg_1: arg_2 = 75.0, arg_3: arg_2 = 1.0, arg_4: arg_2 = 100.0, arg_5: arg_2 = None):
        """
        Create a projection matrix with the following parameters.
        When ``aspect_ratio`` is not provided the configured aspect
        ratio for the window will be used.

        Args:
            fov (float): Field of view (float)
            near (float): Camera near value
            far (float): Camrea far value

        Keyword Args:
            aspect_ratio (float): Aspect ratio of the viewport

        Returns:
            The projection matrix as a float32 :py:class:`numpy.array`
        """
        return matrix44.create_perspective_projection_matrix(
            arg_1,
            arg_5 or arg_0.window.aspect_ratio,
            arg_3,
            arg_4,
            dtype='f4',
        )


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Creates a transformation matrix woth rotations and translation.

        Args:
            rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`
            translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`

        Returns:
            A 4x4 matrix as a :py:class:`numpy.array`
        """
        arg_3 = None
        if arg_1 is not None:
            arg_3 = Matrix44.from_eulers(Vector3(arg_1))

        if arg_2 is not None:
            arg_4 = matrix44.create_from_translation(Vector3(arg_2))
            if arg_3 is None:
                arg_3 = arg_4
            else:
                arg_3 = matrix44.multiply(arg_3, arg_4)

        return arg_3


def Func(arg_0, arg_1):
        """
        Creates a normal matrix from modelview matrix

        Args:
            modelview: The modelview matrix

        Returns:
            A 3x3 Normal matrix as a :py:class:`numpy.array`
        """
        arg_2 = Matrix33.from_matrix44(arg_1)
        arg_2 = arg_2.inverse
        arg_2 = arg_2.transpose()
        return arg_2


def Func(arg_0):
    """Scan for available templates in effect_templates"""
    arg_1 = list_templates()

    if arg_0 not in arg_1:
        raise ArgumentTypeError("Effect template '{}' does not exist.\n Available templates: {} ".format(
            arg_0, ", ".join(arg_1)))

    return arg_0


def Func():
    """Get the absolute path to the root of the demosys package"""
    arg_0 = os.path.dirname(globals()['__file__'])
    return os.path.dirname(os.path.dirname(arg_0))


def Func(arg_0):
        """Load a file in text mode"""
        arg_0.meta.resolved_path = arg_0.find_data(arg_0.meta.path)

        if not arg_0.meta.resolved_path:
            raise ImproperlyConfigured("Data file '{}' not found".format(arg_0.meta.path))

        print("Loading:", arg_0.meta.path)

        with open(arg_0.meta.resolved_path, 'r') as fd:
            return fd.read()


def Func(arg_0):
    """
    Get a finder class from an import path.
    Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.
    This function uses an lru cache.

    :param import_path: string representing an import path
    :return: An instance of the finder
    """
    arg_1 = import_string(arg_0)
    if not issubclass(arg_1, BaseFileSystemFinder):
        raise ImproperlyConfigured('Finder {} is not a subclass of core.finders.FileSystemFinder'.format(arg_0))
    return arg_1()


def Func(arg_0, arg_1: arg_2):
        """
        Find a file in the path. The file may exist in multiple
        paths. The last found file will be returned.

        :param path: The path to Func
        :return: The absolute path to the file or None if not found
        """
        # Update paths from settings to make them editable runtime
        # This is only possible for FileSystemFinders
        if getattr(arg_0, 'settings_attr', None):
            arg_0.paths = getattr(settings, arg_0.settings_attr)

        arg_4 = None

        for arg_5 in arg_0.paths:
            arg_6 = arg_5 / arg_1
            if arg_6.exists():
                arg_4 = arg_6

        return arg_4


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None):
        """
        Update the internal projection matrix based on current values
        or values passed in if specified.

        :param aspect_ratio: New aspect ratio
        :param fov: New field of view
        :param near: New near value
        :param far: New far value
        """
        arg_0.aspect_ratio = arg_1 or arg_0.aspect_ratio
        arg_0.fov = arg_2 or arg_0.fov
        arg_0.near = arg_3 or arg_0.near
        arg_0.far = arg_4 or arg_0.far

        arg_0.matrix = Matrix44.perspective_projection(arg_0.fov, arg_0.aspect_ratio, arg_0.near, arg_0.far)


def Func(arg_0):
        """
        Swaps buffers, incement the framecounter and pull events.
        """
        arg_0.frames += 1
        glfw.Func(arg_0.window)
        arg_0.poll_events()


def Func(arg_0):
        """
        Ensure glfw library  version is compatible
        """
        print("glfw version: {} (python wrapper version {})".format(glfw.get_version(), glfw.__version__))
        if glfw.get_version() < arg_0.min_glfw_version:
            raise ValueError("Please update glfw binaries to version {} or later".format(arg_0.min_glfw_version))


def Func(arg_0):
    """Translate the buffer format"""
    arg_1 = []
    arg_2 = []
    arg_3 = []

    if "T2F" in arg_0:
        arg_1.append("2f")
        arg_2.append("in_uv")
        arg_3.append(("TEXCOORD_0", "in_uv", 2))

    if "C3F" in arg_0:
        arg_1.append("3f")
        arg_2.append("in_color")
        arg_3.append(("NORMAL", "in_color", 3))

    if "N3F" in arg_0:
        arg_1.append("3f")
        arg_2.append("in_normal")
        arg_3.append(("NORMAL", "in_normal", 3))

    arg_1.append("3f")
    arg_2.append("in_position")
    arg_3.append(("POSITION", "in_position", 3))

    return " ".join(arg_1), arg_2, arg_3


def Func(arg_0, arg_1: arg_2):
        """
        Set the current time. This can be used to jump in the timeline.

        Args:
            value (float): The new time
        """
        if arg_1 < 0:
            arg_1 = 0

        arg_0.offset += arg_0.get_time() - arg_1


def Func(arg_0, arg_1: arg_2):
        """
        Resolve scene loader based on file extension
        """
        for arg_3 in arg_0._loaders:
            if arg_3.supports_file(arg_1):
                arg_1.loader_cls = arg_3
                break
        else:
            raise ImproperlyConfigured(
                "Scene {} has no loader class registered. Check settings.SCENE_LOADERS".format(arg_1.path))


def Func(arg_0, arg_1, arg_2):
        """
        Pyglet specific callback for window resize events.
        """
        arg_0.width, arg_0.height = arg_1, arg_2
        arg_0.buffer_width, arg_0.buffer_height = arg_1, arg_2
        arg_0.resize(arg_1, arg_2)


def Func(arg_0):
        """
        Swap buffers, increment frame counter and pull events
        """
        if not arg_0.window.context:
            return

        arg_0.frames += 1
        arg_0.window.flip()
        arg_0.window.dispatch_events()


def Func(arg_0=0.5, arg_1=32, arg_2=16) -> VAO:
    """
    Creates a Func.

    Keyword Args:
        radius (float): Radius or the Func
        rings (int): number or horizontal rings
        sectors (int): number of vertical segments

    Returns:
        A :py:class:`demosys.opengl.vao.VAO` instance
    """
    arg_3 = 1.0 / (arg_2 - 1)
    arg_4 = 1.0 / (arg_1 - 1)

    arg_5 = [0] * (arg_2 * arg_1 * 3)
    arg_6 = [0] * (arg_2 * arg_1 * 3)
    arg_7 = [0] * (arg_2 * arg_1 * 2)

    arg_8, arg_9, arg_10 = 0, 0, 0
    for arg_11 in range(arg_2):
        for arg_12 in range(arg_1):
            arg_13 = math.sin(-math.pi / 2 + math.pi * arg_11 * arg_3)
            arg_14 = math.cos(2 * math.pi * arg_12 * arg_4) * math.sin(math.pi * arg_11 * arg_3)
            arg_15 = math.sin(2 * math.pi * arg_12 * arg_4) * math.sin(math.pi * arg_11 * arg_3)

            arg_7[arg_10] = arg_12 * arg_4
            arg_7[arg_10 + 1] = arg_11 * arg_3

            arg_5[arg_8] = arg_14 * arg_0
            arg_5[arg_8 + 1] = arg_13 * arg_0
            arg_5[arg_8 + 2] = arg_15 * arg_0

            arg_6[arg_9] = arg_14
            arg_6[arg_9 + 1] = arg_13
            arg_6[arg_9 + 2] = arg_15

            arg_10 += 2
            arg_8 += 3
            arg_9 += 3

    arg_16 = [0] * arg_2 * arg_1 * 6
    arg_17 = 0
    for arg_11 in range(arg_2 - 1):
        for arg_12 in range(arg_1 - 1):
            arg_16[arg_17] = arg_11 * arg_1 + arg_12
            arg_16[arg_17 + 1] = (arg_11 + 1) * arg_1 + (arg_12 + 1)
            arg_16[arg_17 + 2] = arg_11 * arg_1 + (arg_12 + 1)

            arg_16[arg_17 + 3] = arg_11 * arg_1 + arg_12
            arg_16[arg_17 + 4] = (arg_11 + 1) * arg_1 + arg_12
            arg_16[arg_17 + 5] = (arg_11 + 1) * arg_1 + (arg_12 + 1)
            arg_17 += 6

    arg_18 = numpy.array(arg_5, dtype=numpy.float32)
    arg_19 = numpy.array(arg_6, dtype=numpy.float32)
    arg_20 = numpy.array(arg_7, dtype=numpy.float32)
    arg_21 = numpy.array(arg_16, dtype=numpy.uint32)

    arg_22 = VAO("Func", mode=mlg.TRIANGLES)
    # VBOs
    arg_22.buffer(arg_18, '3f', ['in_position'])
    arg_22.buffer(arg_19, '3f', ['in_normal'])
    arg_22.buffer(arg_20, '2f', ['in_uv'])
    arg_22.index_buffer(arg_21, index_element_size=4)

    return arg_22


def Func(arg_0, arg_1: arg_2):
        """
        Attempts to assign a loader class to a resource description

        :param meta: The resource description instance
        """
        arg_1.loader_cls = arg_0.get_loader(arg_1, raise_on_error=True)


def Func(arg_0, arg_1: arg_2, arg_3=False) -> BaseLoader:
        """
        Attempts to get a loader

        :param meta: The resource description instance
        :param raise_on_error: Raise ImproperlyConfigured if the loader cannot be resolved
        :returns: The requested loader class
        """
        for arg_4 in arg_0._loaders:
            if arg_4.name == arg_1.loader:
                return arg_4

        if arg_3:
            raise ImproperlyConfigured(
                "Resource has invalid loader '{}': {}\nAvailiable loaders: {}".format(
                    arg_1.loader, arg_1, [arg_4.name for arg_4 in arg_0._loaders]))


def Func(arg_0, arg_1, arg_2):
        """
        Pyqt specific Func callback.
        """
        if not arg_0.fbo:
            return

        # pyqt reports sizes in actual buffer size
        arg_0.width = arg_1 // arg_0.widget.devicePixelRatio()
        arg_0.height = arg_2 // arg_0.widget.devicePixelRatio()
        arg_0.buffer_width = arg_1
        arg_0.buffer_height = arg_2

        super().Func(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Draws a frame. Internally it calls the
        configured timeline's Func method.

        Args:
            current_time (float): The current time (preferrably always from the configured timer class)
            frame_time (float): The duration of the previous frame in seconds
        """
        arg_0.set_default_viewport()
        arg_0.timeline.Func(arg_1, arg_2, arg_0.fbo)


def Func(arg_0, arg_1=0.0, arg_2=0.0, arg_3=0.0, arg_4=0.0, arg_5=1.0):
        """
        Sets the clear values for the window buffer.

        Args:
            red (float): red compoent
            green (float): green compoent
            blue (float): blue compoent
            alpha (float): alpha compoent
            depth (float): depth value
        """
        arg_0.clear_color = (arg_1, arg_2, arg_3, arg_4)
        arg_0.clear_depth = arg_5