text:
..
   Programmer(s): Daniel R. Reynolds @ SMU
   ----------------------------------------------------------------
   Copyright (c) 2013, Southern Methodist University.
   All rights reserved.
   For details, see the LICENSE file.
   ----------------------------------------------------------------

:tocdepth: 3

.. _CInterface.UserSupplied:

User-supplied functions
=============================

The user-supplied functions for ARKode consist of:

* at least one function defining the ODE (required),

* a function that handles error and warning messages (optional),

* a function that provides the error weight vector (optional),

* a function that provides the residual weight vector (optional),

* a function that handles adaptive time step error control (optional),

* a function that handles explicit time step stability (optional),

* a function that defines the root-finding problem(s) to solve
  (optional),

* a function that provides Jacobian-related information for the linear
  solver, if a Newton-based nonlinear iteration is chosen (optional),

* one or two functions that define the preconditioner for use in any
  of the Krylov iterative algorithms, if a Newton-based nonlinear
  iteration and iterative linear solver are chosen (optional), and

* if the problem involves a non-identity mass matrix :math:`M\ne I`:

  * a function that provides mass-matrix-related information for the
    linear and mass matrix solvers (required),

  * one or two functions that define the mass matrix preconditioner
    for use in an iterative mass matrix solver is chosen (optional), and

* a function that handles vector resizing operations, if the
  underlying vector structure supports resizing (as opposed to
  deletion/recreation), and if the user plans to call
  :c:func:`ARKodeResize()` (optional).

.. _CInterface.ODERHS:

ODE right-hand side
-----------------------------

The user must supply at least one function of type :c:func:`ARKRhsFn()` to
specify the explicit and/or implicit portions of the ODE system:

.. c:function:: typedef int (*ARKRhsFn)(realtype t, N_Vector y, N_Vector ydot, void* user_data)

   These functions compute the ODE right-hand side for a given
   value of the independent variable :math:`t` and state vector :math:`y`.

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of teh dependent variable vector, :math:`y(t)`.
      * *ydot* -- the output vector that forms a portion of the ODE RHS :math:`f_E(t,y) + f_I(t,y)`.
      * *user_data* -- the `user_data` pointer that was passed to :c:func:`ARKodeSetUserData()`.

   **Return value:**
   An *ARKRhsFn* should return 0 if successful, a positive value if a
   recoverable error occurred (in which case ARKode will attempt to
   correct), or a negative value if it failed unrecoverably (in which
   case the integration is halted and *ARK_RHSFUNC_FAIL* is returned).

   **Notes:** Allocation of memory for `ydot` is handled within
   ARKode.  A recoverable failure error return from the *ARKRhsFn* is
   typically used to flag a value of the dependent variable :math:`y`
   that is "illegal" in some way (e.g., negative where only a
   nonnegative value is physically meaningful).  If such a return is
   made, ARKode will attempt to recover (possibly repeating the
   nonlinear iteration, or reducing the step size) in order to avoid
   this recoverable error return.  There are some situations in which
   recovery is not possible even if the right-hand side function
   returns a recoverable error flag.  One is when this occurs at the
   very first call to the *ARKRhsFn* (in which case
   ARKode returns *ARK_FIRST_RHSFUNC_ERR*).  Another is when a
   recoverable error is reported by *ARKRhsFn* after the integrator
   completes a successful stage, in which case ARKode returns
   *ARK_UNREC_RHSFUNC_ERR*).

.. _CInterface.ErrorHandler:

Error message handler function
--------------------------------------

As an alternative to the default behavior of directing error and
warning messages to the file pointed to by `errfp` (see
:c:func:`ARKodeSetErrFile()`), the user may provide a function of type
:c:func:`ARKErrHandlerFn()` to process any such messages.

.. c:function:: typedef void (*ARKErrHandlerFn)(int error_code, const char* module, const char* function, char* msg, void* user_data)

   This function processes error and warning messages from
   ARKode and is sub-modules.

   **Arguments:**
      * *error_code* -- the error code.
      * *module* -- the name of the ARKode module reporting the error.
      * *function* -- the name of the function in which the error occurred.
      * *msg* -- the error message.
      * *user_data* -- a pointer to user data, the same as the
        *eh_data* parameter that was passed to :c:func:`ARKodeSetErrHandlerFn()`.

   **Return value:**
   An *ARKErrHandlerFn* function has no return value.

   **Notes:** *error_code* is negative for errors and positive
   (*ARK_WARNING*) for warnings.  If a function that returns a
   pointer to memory encounters an error, it sets *error_code* to
   0.

.. _CInterface.ErrorWeight:

Error weight function
--------------------------------------

As an alternative to providing the relative and absolute tolerances,
the user may provide a function of type :c:func:`ARKEwtFn()` to compute a
vector *ewt* containing the weights in the WRMS norm
:math:`\|v\|_{WRMS} = \left(\frac{1}{n} \sum_{i=1}^n \left(ewt_i\; v_i\right)^2
\right)^{1/2}`.  These weights will be used in place of those defined
in the section :ref:`Mathematics.Error.Norm`.

.. c:function:: typedef int (*ARKEwtFn)(N_Vector y, N_Vector ewt, void* user_data)

   This function computes the WRMS error weights for the vector
   :math:`y`.

   **Arguments:**
      * *y* -- the dependent variable vector at which the
        weight vector is to be computed.
      * *ewt* -- the output vector containing the error weights.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.

   **Return value:**
   An *ARKEwtFn* function must return 0 if it
   successfully set the error weights, and -1 otherwise.

   **Notes:** Allocation of memory for *ewt* is handled within ARKode.

   The error weight vector must have all components positive.  It is
   the user's responsibility to perform this test and return -1 if it
   is not satisfied.

.. _CInterface.ResidualWeight:

Residual weight function
--------------------------------------

As an alternative to providing the scalar or vector absolute residual
tolerances (when the IVP units differ from the solution units), the
user may provide a function of type :c:func:`ARKRwtFn()` to compute a
vector *rwt* containing the weights in the WRMS norm
:math:`\|v\|_{WRMS} = \left(\frac{1}{n} \sum_{i=1}^n \left(rwt_i\; v_i\right)^2
\right)^{1/2}`.  These weights will be used in place of those defined
in the section :ref:`Mathematics.Error.Norm`.

.. c:function:: typedef int (*ARKRwtFn)(N_Vector y, N_Vector rwt, void* user_data)

   This function computes the WRMS residual weights for the vector
   :math:`y`.

   **Arguments:**
      * *y* -- the dependent variable vector at which the
        weight vector is to be computed.
      * *rwt* -- the output vector containing the residual weights.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.

   **Return value:**
   An *ARKRwtFn* function must return 0 if it
   successfully set the residual weights, and -1 otherwise.

   **Notes:** Allocation of memory for *rwt* is handled within ARKode.

   The residual weight vector must have all components positive.  It is
   the user's responsibility to perform this test and return -1 if it
   is not satisfied.

.. _CInterface.AdaptivityFn:

Time step adaptivity function
--------------------------------------

As an alternative to using one of the built-in time step adaptivity
methods for controlling solution error, the user may provide a
function of type :c:func:`ARKAdaptFn()` to compute a target step size
:math:`h` for the next integration step.  These steps should be chosen
as the maximum value such that the error estimates remain below 1.

.. c:function:: typedef int (*ARKAdaptFn)(N_Vector y, realtype t, realtype h1, realtype h2, realtype h3, realtype e1, realtype e2, realtype e3, int q, int p, realtype* hnew, void* user_data)

   This function implements a time step adaptivity algorithm
   that chooses :math:`h` satisfying the error tolerances.

   **Arguments:**
      * *y* -- the current value of the dependent variable vector, :math:`y(t)`.
      * *t* -- the current value of the independent variable.
      * *h1* -- the current step size, :math:`t_m - t_{m-1}`.
      * *h2* -- the previous step size, :math:`t_{m-1} - t_{m-2}`.
      * *h3* -- the step size :math:`t_{m-2}-t_{m-3}`.
      * *e1* -- the error estimate from the current step, :math:`m`.
      * *e2* -- the error estimate from the previous step, :math:`m-1`.
      * *e3* -- the error estimate from the step :math:`m-2`.
      * *q* -- the global order of accuracy for the integration method.
      * *p* -- the global order of accuracy for the embedding.
      * *hnew* -- the output value of the next step size.
      * *user_data* -- a pointer to user data, the same as the
        *h_data* parameter that was passed to :c:func:`ARKodeSetAdaptivityFn()`.

   **Return value:**
   An *ARKAdaptFn* function should return 0 if it
   successfuly set the next step size, and a non-zero value otherwise.

.. _CInterface.StabilityFn:

Explicit stability function
--------------------------------------

A user may supply a function to predict the maximum stable step size
for the explicit portion of the ImEx system, :math:`f_E(t,y)`.  While
the accuracy-based time step adaptivity algorithms may be sufficient
for retaining a stable solution to the ODE system, these may be
inefficient if :math:`f_E(t,y)` contains moderately stiff terms.  In
this scenario, a user may provide a function of type :c:func:`ARKExpStabFn()`
to provide this stability information to ARKode.  This function
must set the scalar step size satisfying the stability restriction for
the upcoming time step.  This value will subsequently be bounded by
the user-supplied values for the minimum and maximum allowed time
step, and the accuracy-based time step.

.. c:function:: typedef int (*ARKExpStabFn)(N_Vector y, realtype t, realtype* hstab, void* user_data)

   This function predicts the maximum stable step size for the
   explicit portions of the ImEx ODE system.

   **Arguments:**
      * *y* -- the current value of the dependent variable vector, :math:`y(t)`.
      * *t* -- the current value of the independent variable
      * *hstab* -- the output value with the absolute value of the
 	maximum stable step size.
      * *user_data* -- a pointer to user data, the same as the
        *estab_data* parameter that was passed to :c:func:`ARKodeSetStabilityFn()`.

   **Return value:**
   An *ARKExpStabFn* function should return 0 if it
   successfully set the upcoming stable step size, and a non-zero
   value otherwise.

   **Notes:**  If this function is not supplied, or if it returns
   *hstab* :math:`\le 0.0`, then ARKode will assume that there is no explicit
   stability restriction on the time step size.

.. _CInterface.RootfindingFn:

Rootfinding function
--------------------------------------

If a rootfinding problem is to be solved during the integration of the
ODE system, the user must supply a function of type :c:func:`ARKRootFn()`.

.. c:function:: typedef int (*ARKRootFn)(realtype t, N_Vector y, realtype* gout, void* user_data)

   This function implements a vector-valued function
   :math:`g(t,y)` such that the roots of the *nrtfn* components
   :math:`g_i(t,y)` are sought.

   **Arguments:**
      * *t* -- the current value of the independent variable
      * *y* -- the current value of the dependent variable vector, :math:`y(t)`.
      * *gout* -- the output array, of length *nrtfn*, with components :math:`g_i(t,y)`.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.

   **Return value:**
   An *ARKRootFn* function should return 0 if successful
   or a non-zero value if an error occurred (in which case the
   integration is halted and ARKode returns *ARK_RTFUNC_FAIL*).

   **Notes:** Allocation of memory for *gout* is handled within ARKode.

.. _CInterface.DenseJacobianFn:

Jacobian information (direct method with dense Jacobian)
--------------------------------------------------------------

If the direct linear solver with dense treatment of the Jacobian is
used (i.e., :c:func:`ARKDense()` or :c:func:`ARKLapackDense()` is
called in Step 8 of the section :ref:`CInterface.Skeleton`), the user
may provide a function of type :c:func:`ARKDlsDenseJacFn()` to provide
the Jacobian approximation.

.. c:function:: typedef int (*ARKDlsDenseJacFn)(long int N, realtype t, N_Vector y, N_Vector fy, DlsMat Jac, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function computes the dense Jacobian :math:`J =
   \frac{\partial f_I}{\partial y}` (or an approximation to it).

   **Arguments:**
      * *N* -- the size of the ODE system.
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector, namely
        the predicted value of :math:`y(t)`.
      * *fy* -- the current value of the vector :math:`f_I(t,y)`.
      * *Jac* -- the output dense Jacobian matrix (of type ``DlsMat``).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used by an
        ARKDlsDenseJacFn as temporary storage or work space.

   **Return value:**
   An *ARKDlsDenseJacFn* function should return 0 if
   successful, a positive value if a recoverable error occurred (in
   which case ARKode will attempt to correct, while ARKDENSE
   sets *last_flag* to *ARKDLS_JACFUNC_RECVR*), or a negative
   value if it failed unrecoverably (in which case the integration is
   halted, :c:func:`ARKode()` returns *ARK_LSETUP_FAIL* and
   ARKDENSE sets *last_flag* to *ARKDLS_JACFUNC_UNRECVR*).

   **Notes:** A user-supplied dense Jacobian function must load the
   *N* by *N* dense matrix *Jac* with an approximation to the Jacobian
   matrix :math:`J(t,y)` at the point :math:`(t,y)`. Only nonzero
   elements need to be loaded into *Jac* because *Jac* is set to
   the zero matrix before the call to the Jacobian function. The type
   of *Jac* is ``DlsMat``.

   The accessor macros ``DENSE_ELEM`` and ``DENSE_COL`` allow the user
   to read and write dense matrix elements without making explicit
   references to the underlying representation of the ``DlsMat``
   type. ``DENSE_ELEM(J,i,j)`` references the ``(i,j)``-th element of
   the dense matrix ``J`` (for ``i``, ``j`` between 0 and
   N-1). This macro is meant for small problems for which
   efficiency of access is not a major concern. Thus, in terms of the
   indices :math:`m` and :math:`n` ranging from 1 to *N*, the
   Jacobian element :math:`J_{m,n}` can be set using the statement
   ``DENSE_ELEM(J, m-1, n-1)`` :math:`= J_{m,n}`. Alternatively,
   ``DENSE_COL(J,j)`` returns a pointer to the first element of the
   ``j``-th column of ``J`` (for ``j`` ranging from 0 to `N`-1),
   and the elements of the ``j``-th column can then be accessed using
   ordinary array indexing. Consequently, :math:`J_{m,n}` can be
   loaded using the statements ``col_n = DENSE_COL(J, n-1);
   col_n[m-1]`` :math:`= J_{m,n}`. For large problems, it is more
   efficient to use ``DENSE_COL`` than to use ``DENSE_ELEM``. Note
   that both of these macros number rows and columns starting from 0.

   The ``DlsMat`` type and accessor macros ``DENSE_ELEM`` and
   ``DENSE_COL`` are documented in the section :ref:`LinearSolvers`.

   If the user's *ARKDlsDenseJacFn* function uses difference quotient
   approximations, then it may need to access quantities not in the
   argument list. These include the current step size, the error
   weights, etc.  To obtain these, use the ARKodeGet* functions
   listed in :ref:`CInterface.OptionalOutputs`. The unit roundoff
   can be accessed as ``UNIT_ROUNDOFF``, which is defined in the
   header file ``sundials_types.h``.

   For the sake of uniformity, the argument *N* is of type ``long int``,
   even in the case that the LAPACK dense solver is to be used.

.. _CInterface.BandJacobianFn:

Jacobian information (direct method with banded Jacobian)
--------------------------------------------------------------

If the direct linear solver with banded treatment of the Jacobian is
used (i.e. :c:func:`ARKBand()` or :c:func:`ARKLapackBand()` is called
in Step 8 of the section :ref:`CInterface.Skeleton`), the user may
provide a function of type :c:func:`ARKDlsBandJacFn()` to provide the
Jacobian approximation.

.. c:function:: typedef int (*ARKDlsBandJacFn)(long int N, long int mupper, long int mlower, realtype t, N_Vector y, N_Vector fy, DlsMat Jac, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function computes the banded Jacobian :math:`J =
   \frac{\partial f_I}{\partial y}` (or an approximation to it).

   **Arguments:**
      * *N* -- the size of the ODE system.
      * *mlower*, *mupper* -- the lower and upper half-bandwidths of
        the Jacobian.
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector, namely
        the predicted value of :math:`y(t)`.
      * *fy* -- the current value of the vector :math:`f_I(t,y)`.
      * *Jac* -- the output dense Jacobian matrix (of type ``DlsMat``).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used by an
        ARKDlsBandJacFn as temporary storage or work space.

   **Return value:**
   An *ARKDlsBandJacFn* function should return 0 if
   successful, a positive value if a recoverable error occurred (in
   which case ARKode will attempt to correct, while ARKBAND
   sets *last_flag* to *ARKDLS_JACFUNC_RECVR*), or a negative
   value if it failed unrecoverably (in which case the integration is
   halted, :c:func:`ARKode()` returns *ARK_LSETUP_FAIL* and
   ARKBAND sets *last_flag* to *ARKDLS_JACFUNC_UNRECVR*).

   **Notes:** A user-supplied banded Jacobian function must load the band
   matrix *Jac* of type ``DlsMat`` with the elements of the Jacobian
   :math:`J(t,y)` at the point :math:`(t,y)`. Only nonzero elements
   need to be loaded into *Jac* because *Jac* is initialized to
   the zero matrix before the call to the Jacobian function.

   The accessor macros ``BAND_ELEM``, ``BAND_COL``, and
   ``BAND_COL_ELEM`` allow the user to read and write band matrix
   elements without making specific references to the underlying
   representation of the ``DlsMat`` type.  ``BAND_ELEM(J, i, j)``
   references the ``(i,j)``-th element of the band matrix ``J``,
   counting from 0. This macro is meant for use in small problems for
   which efficiency of access is not a major concern. Thus, in terms
   of the indices :math:`m` and :math:`n` ranging from 1 to *N* with
   :math:`(m, n)` within the band defined by *mupper* and
   *mlower*, the Jacobian element :math:`J_{m,n}` can be loaded
   using the statement ``BAND_ELEM(J, m-1, n-1)`` :math:`=
   J_{m,n}`. The elements within the band are those with *-mupper*
   :math:`\le m-n \le` *mlower*.  Alternatively, ``BAND_COL(J, j)``
   returns a pointer to the diagonal element of the ``j``-th column of
   ``J``, and if we assign this address to ``realtype *col_j``, then
   the ``i``-th element of the ``j``-th column is given by
   ``BAND_COL_ELEM(col_j, i, j)``, counting from 0. Thus, for
   :math:`(m,n)` within the band, :math:`J_{m,n}` can be loaded by
   setting ``col_n = BAND_COL(J, n-1); BAND_COL_ELEM(col_n, m-1,
   n-1)`` :math:`= J_{m,n}` . The elements of the ``j``-th column can
   also be accessed via ordinary array indexing, but this approach
   requires knowledge of the underlying storage for a band matrix of
   type ``DlsMat``. The array ``col_n`` can be indexed from
   *-mupper* to *mlower*. For large problems, it is more efficient
   to use ``BAND_COL`` and ``BAND_COL_ELEM`` than to use the
   ``BAND_ELEM`` macro. As in the dense case, these macros all number
   rows and columns starting from 0.

   The ``DlsMat`` type and the accessor macros ``BAND_ELEM``,
   ``BAND_COL`` and ``BAND_COL_ELEM`` are documented in the section
   :ref:`LinearSolvers`.

   If the user's *ARKDlsBandJacFn* function uses difference quotient
   approximations, then it may need to access quantities not in the
   argument list.  These include the current step size, the error
   weights, etc.. To obtain these, use the ARKodeGet* functions
   listed in :ref:`CInterface.OptionalOutputs`. The unit roundoff
   can be accessed as ``UNIT_ROUNDOFF`` defined in the header file
   ``sundials_types.h``.

   For the sake of uniformity, the arguments *N*, *mlower*, and
   *mupper* are of type ``long int``, even in the case that the
   LAPACK band solver is to be used.

.. _CInterface.SparseJacobianFn:

Jacobian information (direct method with sparse Jacobian)
--------------------------------------------------------------

If the direct linear solver with sparse treatment of the Jacobian is
used (i.e., :c:func:`ARKKLU()` or :c:func:`ARKSuperLUMT()` is
called in Step 8 of the section :ref:`CInterface.Skeleton`), the user
must provide a function of type :c:func:`ARKSlsSparseJacFn()` to provide
the Jacobian approximation.

.. c:function:: typedef int (*ARKSlsSparseJacFn)(realtype t, N_Vector y, N_Vector fy, SlsMat Jac, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function computes the sparse Jacobian :math:`J =
   \frac{\partial f_I}{\partial y}` (or an approximation to it).

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector, namely
        the predicted value of :math:`y(t)`.
      * *fy* -- the current value of the vector :math:`f_I(t,y)`.
      * *Jac* -- the output sparse Jacobian matrix (of type ``SlsMat``).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used by an
        ARKDlsDenseJacFn as temporary storage or work space.

   **Return value:**
   An *ARKSlsSparseJacFn* function should return 0 if
   successful, a positive value if a recoverable error occurred (in
   which case ARKode will attempt to correct, while ARKKLU or ARKSUPERLUMT
   sets *last_flag* to *ARKSLS_JACFUNC_RECVR*), or a negative
   value if it failed unrecoverably (in which case the integration is
   halted, :c:func:`ARKode()` returns *ARK_LSETUP_FAIL* and
   ARKKLU or ARKSUPERLUMT sets *last_flag* to *ARKSLS_JACFUNC_UNRECVR*).

   **Notes:** A user-supplied sparse Jacobian function must load the
   compressed-sparse-column matrix *Jac* with an approximation to the
   Jacobian matrix :math:`J(t,y)` at the point :math:`(t,y)`.  Storage
   for *Jac* already exists on entry to this function, although the
   user should ensure that sufficient space is allocated in *Jac* to
   hold the nonzero values to be set; if the existing space is
   insufficient the user may reallocate the data and row index arrays
   as needed.  The type of *Jac* is ``SlsMat``, and the amount of
   allocated space is available within the ``SlsMat`` structure as
   ``NNZ``. The ``SlsMat`` type is further documented in the section
   :ref:`LinearSolvers`.

   If the user's *ARKSlsSparseJacFn* function uses difference quotient
   approximations to set the specific matrix entries, then it may need
   to access quantities not in the argument list.  These include the
   current step size, the error weights, etc.  To obtain these, use
   the ARKodeGet* functions listed in
   :ref:`CInterface.OptionalOutputs`. The unit roundoff can be
   accessed as ``UNIT_ROUNDOFF``, which is defined in the header file
   ``sundials_types.h``.

.. _CInterface.JTimesFn:

Jacobian information (matrix-vector product)
--------------------------------------------------------------

If one of the Krylov iterative linear solvers SPGMR, SPBCG, SPTFQMR,
SPFGMR or PCG is selected (i.e. ARKSp* is called in step 8 of the
section :ref:`CInterface.Skeleton`), the user may provide a function
of type :c:func:`ARKSpilsJacTimesVecFn()` in the following form, to
compute matrix-vector products :math:`J*v`. If such a function is not
supplied, the default is a difference quotient approximation to these
products.

.. c:function:: typedef int (*ARKSpilsJacTimesVecFn)(N_Vector v, N_Vector Jv, realtype t, N_Vector y, N_Vector fy, void* user_data, N_Vector tmp)

   This function computes the product :math:`Jv =
   \left(\frac{\partial f_I}{\partial y}\right)v` (or an approximation to it).

   **Arguments:**
      * *v* -- the vector to multiply.
      * *Jv* -- the output vector computed.
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *fy* -- the current value of the vector :math:`f_I(t,y)`.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp* -- pointer to memory allocated to a variable of type
        ``N_Vector`` which can be used as temporary storage or work space.

   **Return value:**
   The value to be returned by the Jacobian-vector product
   function should be 0 if successful. Any other return value will
   result in an unrecoverable error of the SPILS generic solver,
   in which case the integration is halted.

   **Notes:** If the user's *ARKSpilsJacTimesVecFn* function uses
   difference quotient approximations, it may need to access
   quantities not in the argument list.  These include the current
   step size, the error weights, etc..  To obtain these, use the
   ARKodeGet* functions listed in
   :ref:`CInterface.OptionalOutputs`. The unit roundoff can be
   accessed as ``UNIT_ROUNDOFF`` defined in the header file
   ``sundials_types.h``.

.. _CInterface.PrecSolveFn:

Preconditioning (linear system solution)
--------------------------------------------------------------

If one of the Krylov iterative linear solvers SPGMR, SPBCG, SPTFQMR,
SPFGMR or PCG is selected, and preconditioning is used, then the user
must provide a function of type :c:func:`ARKSpilsPrecSolveFn()` to
solve the linear system :math:`Pz=r`, where :math:`P` may be either a
left or right preconditioning matrix.  Here :math:`P` should
approximate (at least crudely) the Newton matrix :math:`A=M-\gamma J`,
where :math:`M` is the mass matrix (typically :math:`M=I` unless
working in a finite-element setting) and :math:`J = \frac{\partial
f_I}{\partial y}`  If preconditioning is done on both sides, the
product of the two preconditioner matrices should approximate
:math:`A`.

.. c:function:: typedef int (*ARKSpilsPrecSolveFn)(realtype t, N_Vector y, N_Vector fy, N_Vector r, N_Vector z, realtype gamma, realtype delta, int lr, void* user_data, N_Vector tmp)

   This function solves the preconditioner system :math:`Pz=r`.

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *fy* -- the current value of the vector :math:`f_I(t,y)`.
      * *r* -- the right-hand side vector of the linear system.
      * *z* -- the computed output solution vector.
      * *gamma* -- the scalar :math:`\gamma` appearing in the Newton
        matrix given by :math:`A=M-\gamma J`.
      * *delta* -- an input tolerance to be used if an iterative method
        is employed in the solution.  In that case, the resdual vector
        :math:`Res = r-Pz` of the system should be made to be less than *delta*
        in the weighted :math:`l_2` norm, i.e. :math:`\left(\sum_{i=1}^n
        \left(Res_i * ewt_i\right)^2 \right)^{1/2} < \delta`, where :math:`\delta =`
        `delta`.  To obtain the ``N_Vector`` *ewt*, call
        :c:func:`ARKodeGetErrWeights()`.
      * *lr* -- an input flag indicating whether the preconditioner
        solve is to use the left preconditioner (*lr* = 1) or the right
        preconditioner (*lr* = 2).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp* -- pointer to memory allocated to a variable of type
        ``N_Vector`` which can be used as temporary storage or work space.

   **Return value:**
   The value to be returned by the preconditioner solve
   function is a flag indicating whether it was successful. This value
   should be 0 if successful, positive for a recoverable error (in
   which case the step will be retried), or negative for an
   unrecoverable error (in which case the integration is halted).

.. _CInterface.PrecSetupFn:

Preconditioning (Jacobian data)
--------------------------------------------------------------

If the user's preconditioner requires that any Jacobian-related data
be preprocessed or evaluated, then these actions need to occur within
a user-supplied function of type :c:func:`ARKSpilsPrecSetupFn()`.

.. c:function:: typedef int (*ARKSpilsPrecSetupFn)(realtype t, N_Vector y, N_Vector fy, booleantype jok, booleantype* jcurPtr, realtype gamma, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function preprocesses and/or evaluates Jacobian-related
   data needed by the preconditioner.

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *fy* -- the current value of the vector :math:`f_I(t,y)`.
      * *jok* -- is an input flag indicating whether the Jacobian-related
        data needs to be updated. The *jok* argument provides for the
        reuse of Jacobian data in the preconditioner solve function. When
        *jok* = ``FALSE``, the Jacobian-related data should be recomputed
        from scratch. When *jok* = ``TRUE`` the Jacobian data, if saved from the
        previous call to this function, can be reused (with the current
        value of *gamma*). A call with *jok* = ``TRUE`` can only occur
        after a call with *jok* = ``FALSE``.
      * *jcurPtr* -- is a pointer to a flag which should be set to
        ``TRUE`` if Jacobian data was recomputed, or set to ``FALSE`` if
        Jacobian data was not recomputed, but saved data was still reused.
      * *gamma* -- the scalar :math:`\gamma` appearing in the Newton
        matrix given by :math:`A=M-\gamma J`.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used as temporary
        storage or work space.

   **Return value:**
   The value to be returned by the preconditioner setup
   function is a flag indicating whether it was successful. This value
   should be 0 if successful, positive for a recoverable error (in
   which case the step will be retried), or negative for an
   unrecoverable error (in which case the integration is halted).

   **Notes:**  The operations performed by this function might include
   forming a crude approximate Jacobian, and performing an LU
   factorization of the resulting approximation to :math:`A = M -
   \gamma J`.

   Each call to the preconditioner setup function is preceded by a
   call to the implicit :c:func:`ARKRhsFn()` user function with the same
   :math:`(t,y)` arguments.  Thus, the preconditioner setup function can
   use any auxiliary data that is computed and saved during the
   evaluation of the ODE right-hand side.

   This function is not called in advance of every call to the
   preconditioner solve function, but rather is called only as often
   as needed to achieve convergence in the Newton iteration.

   If the user's *ARKSpilsPrecSetupFn* function uses difference
   quotient approximations, it may need to access quantities not in
   the call list. These include the current step size, the error
   weights, etc. To obtain these, use the ARKodeGet* functions
   listed in :ref:`CInterface.OptionalOutputs`. The unit roundoff
   can be accessed as ``UNIT_ROUNDOFF`` defined in the header file
   ``sundials_types.h``.

.. _CInterface.DenseMassFn:

Mass matrix information (direct method with dense mass matrix)
---------------------------------------------------------------

If the direct linear solver with dense treatment of the mass matrix is
used (i.e., :c:func:`ARKMassDense()` or :c:func:`ARKMassLapackDense()`
is called in Step 10 of the section :ref:`CInterface.Skeleton`), the
user may provide a function of type :c:func:`ARKDlsDenseMassFn()` to
provide the mass matrix approximation.

.. c:function:: typedef int (*ARKDlsDenseMassFn)(long int N, realtype t, N_Vector y, DlsMat M, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function computes the mass matrix :math:`M` (or an approximation to it).

   **Arguments:**
      * *N* -- the size of the ODE system.
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *M* -- the output dense mass matrix (of type ``DlsMat``).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used by an
        ARKDlsDenseMassFn as temporary storage or work space.

   **Return value:**
   An *ARKDlsDenseMassFn* function should return 0 if
   successful, or a negative value if it failed unrecoverably (in
   which case the integration is halted, :c:func:`ARKode()` returns
   *ARK_MASSSETUP_FAIL* and ARKDENSE sets *last_flag* to
   *ARKDLS_MASSFUNC_UNRECVR*).

   **Notes:** A user-supplied dense mass matrix function must load the
   *N* by *N* dense matrix *M* with an approximation to the mass matrix
   :math:`M(t)`. Only nonzero elements need to be loaded into *M*
   because it is initialized to the zero matrix before the call
   to the mass matrix function. The type of *M* is ``DlsMat``.

   As discussed above in section :ref:`CInterface.DenseJacobianFn`,
   the accessor macros ``DENSE_ELEM`` and ``DENSE_COL`` allow the user
   to read and write dense matrix elements without making explicit
   references to the underlying representation of the ``DlsMat``
   type. Similarly, the ``DlsMat`` type and accessor macros
   ``DENSE_ELEM`` and ``DENSE_COL`` are documented in the section
   :ref:`LinearSolvers`.

   For the sake of uniformity, the argument *N* is of type ``long int``,
   even in the case that the LAPACK dense solver is to be used.

.. _CInterface.BandMassFn:

Mass matrix information (direct method with banded mass matrix)
----------------------------------------------------------------

If the direct linear solver with banded treatment of the mass matrix is
used (i.e. :c:func:`ARKMassBand()` or :c:func:`ARKMassLapackBand()` is
called in Step 10 of the section :ref:`CInterface.Skeleton`), the user
may provide a function of type :c:func:`ARKDlsBandMassFn()` to provide
the mass matrix approximation.

.. c:function:: typedef int (*ARKDlsBandMassFn)(long int N, long int mupper, long int mlower, realtype t, N_Vector y, DlsMat M, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function computes the banded mass matrix :math:`M` (or an approximation to it).

   **Arguments:**
      * *N* -- the size of the ODE system.
      * *mlower*, *mupper* -- the lower and upper half-bandwidths of
        the mass matrix.
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector, namely
        the predicted value of :math:`y(t)`.
      * *M* -- the output dense mass matrix (of type ``DlsMat``).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used by an
        ARKDlsBandMassFn as temporary storage or work space.

   **Return value:**
   An *ARKDlsBandMassFn* function should return 0 if
   successful, or a negative value if it failed unrecoverably (in
   which case the integration is halted, :c:func:`ARKode()` returns
   *ARK_MASSSETUP_FAIL* and ARKBAND sets *last_flag* to
   *ARKDLS_MASSFUNC_UNRECVR*).

   **Notes:** A user-supplied banded mass matrix function must load
   the band matrix *M* of type ``DlsMat`` with the elements of the
   mass matrix :math:`M(t)`. Only nonzero elements need to be loaded
   into *M* because it is initialized to the zero matrix before the
   call to the mass matrix function.

   As discussed above in section :ref:`CInterface.BandJacobianFn`,
   the accessor macros ``BAND_ELEM``, ``BAND_COL``, and
   ``BAND_COL_ELEM`` allow the user to read and write band matrix
   elements without making specific references to the underlying
   representation of the ``DlsMat`` type.  Similarly, the ``DlsMat``
   type and the accessor macros ``BAND_ELEM``, ``BAND_COL`` and
   ``BAND_COL_ELEM`` are documented in the section
   :ref:`LinearSolvers`.

   For the sake of uniformity, the arguments *N*, *mlower*, and
   *mupper* are of type ``long int``, even in the case that the
   LAPACK band solver is to be used.

.. _CInterface.SparseMassFn:

Mass matrix information (direct method with sparse mass matrix)
---------------------------------------------------------------

If the direct linear solver with sparse treatment of the mass matrix
is used (i.e., :c:func:`ARKMassKLU()` or :c:func:`ARKMassSuperLUMT()`
is called in Step 10 of the section :ref:`CInterface.Skeleton`), the
user may provide a function of type :c:func:`ARKSlsSparseMassFn()` to
provide the mass matrix approximation.

.. c:function:: typedef int (*ARKSlsSparseMassFn)(realtype t, SlsMat M, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function computes the mass matrix :math:`M` (or an approximation to it).

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *M* -- the output sparse mass matrix (of type ``SlsMat``).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used by an
        ARKDlsDenseMassFn as temporary storage or work space.

   **Return value:**
   An *ARKSlsSparseMassFn* function should return 0 if
   successful, or a negative value if it failed unrecoverably (in
   which case the integration is halted, :c:func:`ARKode()` returns
   *ARK_MASSSETUP_FAIL* and ARKKLU or ARKSUPERLUMT sets *last_flag* to
   *ARKSLS_MASSFUNC_UNRECVR*).

   **Notes:** A user-supplied sparse mass matrix function must load the
   compressed-sparse-column matrix *M* with an approximation to the
   mass matrix :math:`M(t)`.  Storage for *M* already exists on entry
   to this function, although the user should ensure that sufficient
   space is allocated in *Jac* to hold the nonzero values to be set;
   if the existing space is insufficient the user may reallocate the
   data and row index arrays as needed.  The type of *Jac* is
   ``SlsMat``, and the amount of allocated space is available within
   the ``SlsMat`` structure as ``NNZ``.  The ``SlsMat`` type is
   further documented in the section :ref:`LinearSolvers`.

.. _CInterface.MTimesFn:

Mass matrix information (matrix-vector product)
--------------------------------------------------------------

If one of the Krylov iterative linear solvers SPGMR, SPBCG, SPTFQMR,
SPFGMR or PCG is selected (i.e. ARKMassSp* is called in step 10 of the
section :ref:`CInterface.Skeleton`), the user may provide a function
of type :c:func:`ARKSpilsMassTimesVecFn()` in the following form, to
compute matrix-vector products :math:`M*v`.

.. c:function:: typedef int (*ARKSpilsMassTimesVecFn)(N_Vector v, N_Vector Mv, realtype t, N_Vector y, void* user_data, N_Vector tmp)

   This function computes the product :math:`M*v` (or an approximation to it).

   **Arguments:**
      * *v* -- the vector to multiply.
      * *Mv* -- the output vector computed.
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp* -- pointer to memory allocated to a variable of type
        ``N_Vector`` which can be used as temporary storage or work space.

   **Return value:**
   The value to be returned by the mass-matrix-vector product
   function should be 0 if successful. Any other return value will
   result in an unrecoverable error of the SPILS generic solver,
   in which case the integration is halted.

.. _CInterface.MassPrecSolveFn:

Mass matrix preconditioning (linear system solution)
--------------------------------------------------------------

If one of the Krylov iterative linear solvers SPGMR, SPBCG, SPTFQMR,
SPFGMR or PCG is selected for the mass matrix systems, and
preconditioning is used, then the user must provide a function of type
:c:func:`ARKSpilsMassPrecSolveFn()` to solve the linear system
:math:`Pz=r`, where :math:`P` may be either a left or right
preconditioning matrix.  Here :math:`P` should approximate (at least
crudely) the mass matrix :math:`M`.  If preconditioning is done on
both sides, the product of the two preconditioner matrices should
approximate :math:`M`.

.. c:function:: typedef int (*ARKSpilsMassPrecSolveFn)(realtype t, N_Vector y, N_Vector r, N_Vector z, realtype delta, int lr, void* user_data, N_Vector tmp)

   This function solves the preconditioner system :math:`Pz=r`.

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *r* -- the right-hand side vector of the linear system.
      * *z* -- the computed output solution vector.
      * *delta* -- an input tolerance to be used if an iterative method
        is employed in the solution.  In that case, the resdual vector
        :math:`Res = r-Pz` of the system should be made to be less than *delta*
        in the weighted :math:`l_2` norm, i.e. :math:`\left(\sum_{i=1}^n
        \left(Res_i * ewt_i\right)^2 \right)^{1/2} < \delta`, where :math:`\delta =`
        *delta*.  To obtain the ``N_Vector`` *ewt*, call
        :c:func:`ARKodeGetErrWeights()`.
      * *lr* -- an input flag indicating whether the preconditioner
        solve is to use the left preconditioner (*lr* = 1) or the right
        preconditioner (*lr* = 2).
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp* -- pointer to memory allocated to a variable of type
        ``N_Vector`` which can be used as temporary storage or work space.

   **Return value:**
   The value to be returned by the preconditioner solve
   function is a flag indicating whether it was successful. This value
   should be 0 if successful, positive for a recoverable error (in
   which case the step will be retried), or negative for an
   unrecoverable error (in which case the integration is halted).

.. _CInterface.MasPrecSetupFn:

Mass matrix preconditioning (mass matrix data)
--------------------------------------------------------------

If the user's mass matrix preconditioner requires that any problem
data be preprocessed or evaluated, then these actions need to occur
within a user-supplied function of type
:c:func:`ARKSpilsMassPrecSetupFn()`.

.. c:function:: typedef int (*ARKSpilsMassPrecSetupFn)(realtype t, N_Vector y, void* user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)

   This function preprocesses and/or evaluates mass-matrix-related
   data needed by the preconditioner.

   **Arguments:**
      * *t* -- the current value of the independent variable.
      * *y* -- the current value of the dependent variable vector.
      * *user_data* -- a pointer to user data, the same as the
        *user_data* parameter that was passed to :c:func:`ARKodeSetUserData()`.
      * *tmp1*, *tmp2*, *tmp3* -- pointers to memory allocated to
        variables of type ``N_Vector`` which can be used as temporary
        storage or work space.

   **Return value:**
   The value to be returned by the mass matrix preconditioner setup
   function is a flag indicating whether it was successful. This value
   should be 0 if successful, positive for a recoverable error (in
   which case the step will be retried), or negative for an
   unrecoverable error (in which case the integration is halted).

   **Notes:**  The operations performed by this function might include
   forming a mass matrix and performing an incomplete
   factorization of the result.  Although such operations would
   typically be performed only once at the beginning of a simulation,
   these may be required if the mass matrix can change as a function
   of time.

.. _CInterface.VecResizeFn:

Vector resize function
--------------------------------------

For simulations involving changes to the number of equations and
unknowns in the ODE system (e.g. when using spatial adaptivity in a
PDE simulation), the ARKode integrator may be "resized" between
integration steps, through calls to the :c:func:`ARKodeResize()`
function. Typically, when performing adaptive simulations the solution
is stored in a customized user-supplied data structure, to enable
adaptivity without repeated allocation/deallocation of memory.  In
these scenarios, it is recommended that the user supply a customized
vector kernel to interface between SUNDIALS and their problem-specific
data structure.  If this vector kernel includes a function to resize a
given vector, then this function may be supplied to
:c:func:`ARKodeResize()` so that all internal ARKode vectors may be
resized, instead of deleting and re-creating them at each call.  This
resize function should have the following form:

.. c:function:: typedef int (*ARKVecResizeFn)(N_Vector y, N_Vector ytemplate, void* user_data)

   This function resizes the vector *y* to match the dimensions of the
   supplied vector, *ytemplate*.

   **Arguments:**
      * *y* -- the vector to resize.
      * *ytemplate* -- a vector of the desired size.
      * *user_data* -- a pointer to user data, the same as the
        *resize_data* parameter that was passed to :c:func:`ARKodeResize()`.

   **Return value:**
   An *ARKVecResizeFn* function should return 0 if it successfully
   resizes the vector *y*, and a non-zero value otherwise.

   **Notes:**  If this function is not supplied, then ARKode will
   instead destroy the vector *y* and clone a new vector *y* off of
   *ytemplate*.


text:
import assign from 'object-assign';

/**
 * JSON schema to accept an array of unique strings
 */
export const arraySchema = {
  type: 'array',
  items: {
    type: 'string',
  },
  minItems: 1,
  uniqueItems: true,
  additionalItems: false,
};

/**
 * JSON schema to accept an array of unique strings from an enumerated list.
 */
export const enumArraySchema = (enumeratedList = []) => assign({}, arraySchema, {
  items: {
    type: 'string',
    enum: enumeratedList,
  },
});

/**
 * Factory function to generate an object schema
 * with specified properties object
 */
export const generateObjSchema = (properties = {}) => ({
  type: 'object',
  properties,
});

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * @author: Viskov Sergey
 * @date: 28.04.15
 * @time: 17:55
 */

namespace LTDBeget\apacheConfigurator\exceptions;

class NotAllowedContextException extends \Exception {

}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/wearables/armor/zam/shared_armor_zam_wesell_belt.iff"
	result.attribute_template_id = 0
	result.stfName("wearables_name","armor_zam_wesell_belt")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
{% set page_question = 'Symptoms of low blood sugar (hypoglycaemia)' %}

{% set q_id = 'q_id' %}
{% set q_no = '' %}

{% set go_next = 'hypoglycaemia-episode' %}
{% set current_page = '/diabetes/know-symptoms' %}
{% set replay = 'You have confirmed that you have read and understood what the symptoms of low blood sugar (hypoglycaemia) are' %}

{% extends "layout.html" %}

{% block page_title %}{% if page_title %} {{ page_title | safe }} {% else %} {{ page_question | safe }} {% endif %}{% endblock %}

{% block head %}
    {% include "includes/head.html" %}
    {% include "includes/scripts.html" %}
{% endblock %}

{% block after_header %}
    {{ banner.input() }}
{% endblock %}

{% block content %}

{{ page_question | safe }}

                {% include "includes/forms/form-hint.html" %}

                <form class="form">

As you are a driver with insulin-treated diabetes, you need to know what the symptoms of low blood sugar are. Examples are shown below:

hunger

shakiness

nervousness

sweating

dizziness or light-headedness

sleepiness

confusion

difficulty speaking

anxiety

weakness

Low blood sugar can also happen during sleep. Some signs include:

crying out or having nightmares

finding pyjamas or sheets damp from perspiration

feeling tired, irritable, or confused after waking up

                    {{ button({name: 'UNDERSTOOD', value: 'I have read and understood the above'}) }}
                </form>

            {% include "includes/widgets/need-help.html" %}

{% endblock %}

{% block body_end %}

{% endblock %}


text:
"""Support Peewee ORM for Muffin framework."""

import typing as t

import muffin
from aiopeewee import DatabaseAsync, db_url
from muffin.plugins import BasePlugin
from muffin.typing import Receive, Send
from peewee_migrate import Router

import peewee as pw

from .fields import Choices, JSONField

__version__ = "1.12.1"
__project__ = "muffin-peewee"
__author__ = "Kirill Klenov <horneds@gmail.com>"
__license__ = "MIT"

__all__ = "Plugin", "JSONField", "Choices"

assert JSONField and Choices

class Plugin(BasePlugin):

    """Muffin Peewee Plugin."""

    name = "peewee"
    defaults = {
        # Connection params
        "connection": "sqlite+async:///db.sqlite",
        "connection_params": {},
        # Manage connections automatically
        "manage_connections": True,
        # Setup migration engine
        "migrations_enabled": True,
        "migrations_path": "migrations",
    }
    router: Router

    def __init__(self, app: muffin.Application = None, **options):
        """Initialize the plugin."""
        self.database: pw.Proxy = pw.Proxy()
        self.models: t.Dict[str, pw.Model] = {}
        self.router: Router = None
        self.is_async: bool = False
        super(Plugin, self).__init__(app, **options)

    def setup(self, app: muffin.Application, **options):  # noqa
        """Init the plugin."""
        super().setup(app, **options)
        self.database.initialize(
            db_url.connect(self.cfg.connection, **self.cfg.connection_params)
        )
        if isinstance(self.database.obj, DatabaseAsync):
            self.is_async = True

        #  Hack for sqlite in memory (for tests)
        if self.is_async and self.database.obj.database == ":memory:":
            self.database.obj._state = pw._ConnectionLocal()

        if self.cfg.migrations_enabled:
            self.router = Router(self.database, migrate_dir=self.cfg.migrations_path)

            # Register migration commands
            @app.manage
            def peewee_migrate(name: str = None, fake: bool = False):
                """Run application's migrations.

                :param name: Choose a migration' name
                :param fake: Run as fake. Update migration history and don't touch the database
                """
                self.router.run(name, fake=fake)

            @app.manage
            def peewee_create(name: str = "auto", auto: bool = False):
                """Create a migration.

                :param name: Set name of migration [auto]
                :param auto: Track changes and setup migrations automatically
                """
                self.router.create(name, auto and [m for m in self.models.values()])

            @app.manage
            def peewee_rollback():
                """Rollback a migration.

                :param name: Migration name (actually it always should be a last one)
                """
                self.router.rollback()

            @app.manage
            def peewee_list():
                """List migrations."""
                self.router.logger.info("Migrations are done:")
                self.router.logger.info("\n".join(self.router.done))
                self.router.logger.info("")
                self.router.logger.info("Migrations are undone:")
                self.router.logger.info("\n".join(self.router.diff))

            @app.manage
            def peewee_clear():
                """Clear migrations from DB."""
                self.router.clear()

            @app.manage
            def peewee_merge(name: str = "initial", clear: bool = False):
                """Merge all migrations into one."""
                self.router.merge(name)

        if self.cfg.manage_connections:
            app.middleware(self.__middleware__, insert_first=True)

    def __getattr__(self, name: str) -> t.Any:
        """Proxy attrs to self database."""
        return getattr(self.database.obj, name)

    async def __aenter__(self):
        """Connect and enter the database context."""
        database = self.database
        if self.is_async:
            return await database.obj.__aenter__()

        database.connect(reuse_if_open=True)
        database.__enter__()
        return database.connection()

    async def __aexit__(self, *args):
        """Exit from the database context."""
        database = self.database
        if self.is_async:
            await database.obj.__aexit__(*args)

        else:
            database.__exit__(*args)
            database.close()

    async def __middleware__(
        self, handler: t.Callable, request: muffin.Request, receive: Receive, send: Send
    ):
        """Manage connections for request."""
        async with self as conn:
            try:
                response = await handler(request, receive, send)
                conn.commit()
                return response

            except pw.DatabaseError:
                conn.rollback()
                raise

    async def shutdown(self):
        """Close connections."""
        db = self.database.obj
        if self.is_async:
            await getattr(db, "close_all_async", getattr(db, "close_async"))()
        else:
            getattr(db, "close_all", getattr(db, "close"))()

    def register(self, model: pw.Model):
        """Register a model with the plugin."""
        self.models[model._meta.table_name] = model
        model._meta.database = self.database
        return model

    async def conftest(self):
        """Configure pytest tests."""
        for model in self.models.values():
            model.create_table()


text:
#ifndef __LZMAAPPLECOMMON_H__
#define __LZMAAPPLECOMMON_H__ 1

#if defined(__APPLE__) || defined(TARGET_OS_MAC) || defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR) || defined(TARGET_OS_EMBEDDED)
#ifndef __APPLE__
#define __APPLE__ 1
#endif

#define LZMASDKOBJC_OMIT_UNUSED_CODE 1

#if defined(_UNICODE)
#undef _UNICODE
#endif

#ifndef ENV_HAVE_GCCVISIBILITYPATCH
#define ENV_HAVE_GCCVISIBILITYPATCH 1
#endif

#if ( defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_AMD64_) || defined(_M_AMD64) )
#define __APPLE_64__ 1
#endif

#ifndef __APPLE_64__
#if ( defined(__LP64__) || defined(__ia64__) || defined(_IA64) || defined(__IA64__) || defined(__ia64) || defined(_M_IA64) )
#define __APPLE_64__ 1
#endif
#endif

#ifndef __APPLE_64__
#if ( defined(_WIN64) || defined(__X86_64__) || defined(WIN64) || defined(_LP64) || defined(ppc64) || defined(x86_64) )
#define __APPLE_64__ 1
#endif
#endif

#ifndef __APPLE_64__
#if ( defined(__x86_64__) || defined(__ppc64__) )
#define __APPLE_64__ 1
#endif
#endif

#ifndef __APPLE_64__
#define __APPLE_32__ 1
#endif

#endif

#if !defined(LZMASDKOBJC_EXTERN)
#if defined(__cplusplus) || defined(_cplusplus)
#define LZMASDKOBJC_EXTERN extern "C"
#else
#define LZMASDKOBJC_EXTERN extern
#endif
#endif

#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <pthread.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <string.h>
#include <wchar.h>
#include <assert.h>

typedef void *PVOID, *LPVOID;
typedef PVOID HANDLE;

#ifndef DWORD_SIZE
#define DWORD_SIZE 4
typedef uint32_t DWORD;
#endif

// MyWindows.h - removed prev. definition & MyWindows.cpp - implemented
LZMASDKOBJC_EXTERN DWORD GetLastError(void);

// unused
// void SetLastError(DWORD err) { errno = err; }

#if !defined(__OBJC__)
typedef signed char BOOL;
#endif

#if !defined(__cplusplus) && !defined(_cplusplus)
#define TRUE 1
#define FALSE 0
#endif

#ifndef USE_MIXER_ST
#define USE_MIXER_ST 1
#endif

#ifndef _7ZIP_ST
#define _7ZIP_ST 1
#endif

#endif


text:
package com.duguang.baseanimation.ui.imitate.counter.util;

public enum ButtonType {
	SYNTHETIC_COMMON_APPEND,
	BACKSPACE,
	CLEAR,
	EQUALS,
}


text:
const assert = require('assert');
const async = require('async');
const arsenal = require('arsenal');
const { GCP } = arsenal.storage.data.external;
const { gcpRequestRetry, setBucketClass, genUniqID } =
    require('../../../utils/gcpUtils');
const { getRealAwsConfig } =
    require('../../../../aws-node-sdk/test/support/awsConfig');

const credentialOne = 'gcpbackend';
const bucketNames = {
    main: {
        Name: `somebucket-${genUniqID()}`,
        Type: 'MULTI_REGIONAL',
    },
    mpu: {
        Name: `mpubucket-${genUniqID()}`,
        Type: 'MULTI_REGIONAL',
    },
};

const body = Buffer.from('I am a body', 'utf8');
const bigBody = Buffer.alloc(10485760);
const smallMD5 = 'be747eb4b75517bf6b3cf7c5fbb62f3a';
const bigMD5 = 'a7d414b9133d6483d9a1c4e04e856e3b-2';

describe('GCP: Upload Object', function testSuite() {
    this.timeout(600000);
    let config;
    let gcpClient;

    before(done => {
        config = getRealAwsConfig(credentialOne);
        gcpClient = new GCP(config);
        async.eachSeries(bucketNames,
            (bucket, next) => gcpRequestRetry({
                method: 'PUT',
                bucket: bucket.Name,
                authCredentials: config.credentials,
                requestBody: setBucketClass(bucket.Type),
            }, 0, err => {
                if (err) {
                    process.stdout.write(`err in creating bucket ${err}\n`);
                }
                return next(err);
            }),
        err => done(err));
    });

    after(done => {
        async.eachSeries(bucketNames,
            (bucket, next) => gcpClient.listObjects({
                Bucket: bucket.Name,
            }, (err, res) => {
                assert.equal(err, null,
                    `Expected success, but got error ${err}`);
                async.map(res.Contents, (object, moveOn) => {
                    const deleteParams = {
                        Bucket: bucket.Name,
                        Key: object.Key,
                    };
                    gcpClient.deleteObject(
                        deleteParams, err => moveOn(err));
                }, err => {
                    assert.equal(err, null,
                        `Expected success, but got error ${err}`);
                    gcpRequestRetry({
                        method: 'DELETE',
                        bucket: bucket.Name,
                        authCredentials: config.credentials,
                    }, 0, err => {
                        if (err) {
                            process.stdout.write(
                                `err in deleting bucket ${err}\n`);
                        }
                        return next(err);
                    });
                });
            }),
        err => done(err));
    });

    it('should put an object to GCP', done => {
        const key = `somekey-${genUniqID()}`;
        gcpClient.upload({
            Bucket: bucketNames.main.Name,
            MPU: bucketNames.mpu.Name,
            Key: key,
            Body: body,
        }, (err, res) => {
            assert.equal(err, null,
                `Expected success, got error ${err}`);
            assert.strictEqual(res.ETag, `"${smallMD5}"`);
            return done();
        });
    });

    it('should put a large object to GCP', done => {
        const key = `somekey-${genUniqID()}`;
        gcpClient.upload({
            Bucket: bucketNames.main.Name,
            MPU: bucketNames.mpu.Name,
            Key: key,
            Body: bigBody,
        }, (err, res) => {
            assert.equal(err, null,
                `Expected success, got error ${err}`);
            assert.strictEqual(res.ETag, `"${bigMD5}"`);
            return done();
        });
    });
});


text:
.PHONY: all pod

all:
	xcodebuild -workspace WatchButton.xcworkspace \
		-scheme WatchButton -sdk iphonesimulator build CODE_SIGN_IDENTITY=-

pod:
	bundle install
	bundle exec pod install --no-repo-update


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<title>Image Properties</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="robots" content="noindex, nofollow" />

								URL

								<input id="btnBrowse" onclick="BrowseServer();" type="button" value="Browse Server"
									fcklang="DlgBtnBrowseServer" />

								<input id="txtUrl" style="width: 100%" type="text" onblur="UpdatePreview();" />

					Short Description

					<input id="txtAlt" style="width: 100%" type="text" />

											Width

											<input type="text" size="3" id="txtWidth" onkeyup="OnSizeChanged('Width',this.value);" />

											Height

											<input type="text" size="3" id="txtHeight" onkeyup="OnSizeChanged('Height',this.value);" />

											Border

											<input type="text" size="2" value="" id="txtBorder" onkeyup="UpdatePreview();" />

											HSpace

											<input type="text" size="2" id="txtHSpace" onkeyup="UpdatePreview();" />

											VSpace

											<input type="text" size="2" id="txtVSpace" onkeyup="UpdatePreview();" />

											Align

											<select id="cmbAlign" onchange="UpdatePreview();">
												<option value="" selected="selected"></option>
												<option fcklang="DlgImgAlignLeft" value="left">Left</option>
												<option fcklang="DlgImgAlignAbsBottom" value="absBottom">Abs Bottom</option>
												<option fcklang="DlgImgAlignAbsMiddle" value="absMiddle">Abs Middle</option>
												<option fcklang="DlgImgAlignBaseline" value="baseline">Baseline</option>
												<option fcklang="DlgImgAlignBottom" value="bottom">Bottom</option>
												<option fcklang="DlgImgAlignMiddle" value="middle">Middle</option>
												<option fcklang="DlgImgAlignRight" value="right">Right</option>
												<option fcklang="DlgImgAlignTextTop" value="textTop">Text Top</option>
												<option fcklang="DlgImgAlignTop" value="top">Top</option>
											</select>

											Preview

		<form id="frmUpload" method="post" target="UploadWindow" enctype="multipart/form-data"
			action="" onsubmit="return CheckUpload();">
			Upload

			<input id="txtUploadFile" style="width: 100%" type="file" size="40" name="NewFile" />

			<input id="btnUpload" type="submit" value="Send it to the Server" fcklang="DlgLnkBtnUpload" />

		</form>

						URL

						<input id="txtLnkUrl" style="width: 100%" type="text" onblur="UpdatePreview();" />

						<input type="button" value="Browse Server" fcklang="DlgBtnBrowseServer" onclick="LnkBrowseServer();" />

						Target

						<select id="cmbLnkTarget">
							<option value="" fcklang="DlgGenNotSet" selected="selected"><not set></option>
							<option value="_blank" fcklang="DlgLnkTargetBlank">New Window (_blank)</option>
							<option value="_top" fcklang="DlgLnkTargetTop">Topmost Window (_top)</option>
							<option value="_self" fcklang="DlgLnkTargetSelf">Same Window (_self)</option>
							<option value="_parent" fcklang="DlgLnkTargetParent">Parent Window (_parent)</option>
						</select>

					Id

					<input id="txtAttId" style="width: 100%" type="text" />

								Language Direction

								<select id="cmbAttLangDir" style="width: 100%">
									<option value="" fcklang="DlgGenNotSet" selected="selected"><not set></option>
									<option value="ltr" fcklang="DlgGenLangDirLtr">Left to Right (LTR)</option>
									<option value="rtl" fcklang="DlgGenLangDirRtl">Right to Left (RTL)</option>
								</select>

								Language Code

								<input id="txtAttLangCode" style="width: 100%" type="text" />

					Long Description URL

					<input id="txtLongDesc" style="width: 100%" type="text" />

					Stylesheet Classes

					<input id="txtAttClasses" style="width: 100%" type="text" />

					 Advisory Title

					<input id="txtAttTitle" style="width: 100%" type="text" />

		Style

		<input id="txtAttStyle" style="width: 100%" type="text" />


text:
package com.intellij.xdebugger.impl.actions;

import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.xdebugger.impl.DebuggerSupport;
import org.jetbrains.annotations.NotNull;

public class EditBreakpointAction extends XDebuggerActionBase implements DumbAware {

  public static class ContextAction extends DumbAwareAction {
    private final GutterIconRenderer myRenderer;
    private final Object myBreakpoint;
    private final DebuggerSupport myDebuggerSupport;

    public ContextAction(GutterIconRenderer breakpointRenderer, Object breakpoint, DebuggerSupport debuggerSupport) {
      super(ActionsBundle.actionText("EditBreakpoint"));
      myRenderer = breakpointRenderer;
      myBreakpoint = breakpoint;
      myDebuggerSupport = debuggerSupport;
      AnAction action = ActionManager.getInstance().getAction("ViewBreakpoints");
      copyShortcutFrom(action);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      final Editor editor = e.getData(CommonDataKeys.EDITOR);
      Project project = getEventProject(e);
      if (editor == null || project == null) return;
      myDebuggerSupport.getEditBreakpointAction().editBreakpoint(project, editor, myBreakpoint, myRenderer);
    }
  }

  @NotNull
  @Override
  protected DebuggerActionHandler getHandler(@NotNull DebuggerSupport debuggerSupport) {
    return debuggerSupport.getEditBreakpointAction();
  }

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.EDT;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/ic_expert_score_stare_unselect" />
    <item
        android:id="@android:id/secondaryProgress"
        android:drawable="@drawable/ic_expert_score_stare_unselect" />
    <item
        android:id="@android:id/progress"
        android:drawable="@drawable/ic_expert_score_stare_select" />
</layer-list>


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/nearby_sharing/nearby_sharing_service_factory.h"

#include <memory>

#include "base/memory/singleton.h"
#include "build/build_config.h"
#include "chrome/browser/browser_features.h"
#include "chrome/browser/nearby_sharing/nearby_sharing_prefs.h"
#include "chrome/browser/nearby_sharing/nearby_sharing_service_factory.h"
#include "chrome/browser/nearby_sharing/nearby_sharing_service_impl.h"
#include "chrome/browser/profiles/profile.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"

namespace {

constexpr char kServiceName[] = "NearbySharingService";

}  // namespace

// static
NearbySharingServiceFactory* NearbySharingServiceFactory::GetInstance() {
  return base::Singleton<NearbySharingServiceFactory>::get();
}

// static
NearbySharingService* NearbySharingServiceFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<NearbySharingServiceImpl*>(
      GetInstance()->GetServiceForBrowserContext(context, true /* create */));
}

NearbySharingServiceFactory::NearbySharingServiceFactory()
    : BrowserContextKeyedServiceFactory(
          kServiceName,
          BrowserContextDependencyManager::GetInstance()) {}

NearbySharingServiceFactory::~NearbySharingServiceFactory() = default;

KeyedService* NearbySharingServiceFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  if (!base::FeatureList::IsEnabled(features::kNearbySharing)) {
    VLOG(1) << __func__ << ": Nearby Sharing feature flag is not enabled.";
    return nullptr;
  }

  PrefService* pref_service = Profile::FromBrowserContext(context)->GetPrefs();

  if (!pref_service->GetBoolean(kNearbySharingEnabledPrefName)) {
    VLOG(1) << __func__ << ": Nearby Sharing feature not enabled in prefs.";
    return nullptr;
  }

  VLOG(1) << __func__ << ": creating NearbySharingService.";
  return new NearbySharingServiceImpl(Profile::FromBrowserContext(context));
}

content::BrowserContext* NearbySharingServiceFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  // Nearby Sharing features are disabled in incognito.
  if (context->IsOffTheRecord())
    return nullptr;

  // TODO(vecore): Ensure only one profile gets bound to Nearby Sharing.
  return context;
}

void NearbySharingServiceFactory::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  RegisterNearbySharingPrefs(registry);
}

bool NearbySharingServiceFactory::ServiceIsCreatedWithBrowserContext() const {
  return true;
}

bool NearbySharingServiceFactory::ServiceIsNULLWhileTesting() const {
  return true;
}


text:
module.exports = {};

const atob = require('atob');
const btoa = require('btoa');

const Class = {
    register: clazz => {
        module.exports[clazz.prototype.constructor.name] = clazz;
    }
};


text:
package org.huberb.decisiontable.tuple;

import java.io.Serializable;
import java.util.Objects;

/**
 * Tuple with 3 elements.
 *
 * @author berni
 */
public class Triple<T, U, V> implements Serializable {

    private static final long serialVersionUID = 20161011L;

    private final T t;
    private final U u;
    private final V v;

    Triple() {
        this(null, null, null);
    }

    public Triple(T t, U u, V v) {
        this.t = t;
        this.u = u;
        this.v = v;
    }

    public T getT() {
        return t;
    }

    public U getU() {
        return u;
    }

    public V getV() {
        return v;
    }

    //---
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 97 * hash + Objects.hashCode(this.t);
        hash = 97 * hash + Objects.hashCode(this.u);
        hash = 97 * hash + Objects.hashCode(this.v);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Triple<?, ?, ?> other = (Triple<?, ?, ?>) obj;
        boolean equalsResult = true;
        equalsResult = equalsResult && Objects.equals(this.t, other.t);
        equalsResult = equalsResult && Objects.equals(this.u, other.u);
        equalsResult = equalsResult && Objects.equals(this.v, other.v);
        return equalsResult;
    }

    @Override
    public String toString() {
        return "Triple{" + "t=" + t + ", u=" + u + ", v=" + v + '}';
    }

}


text:
package org.apache.olingo.fit.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;

public class NavigationLinks {

  private final Map<String, List<InputStream>> inlines = new HashMap<String, List<InputStream>>();

  private final Map<String, List<String>> links = new HashMap<String, List<String>>();

  public NavigationLinks addInlines(final String name, final InputStream inline) {
    return addInlines(name, Collections.<InputStream> singletonList(inline));
  }

  public NavigationLinks addInlines(final String name, final List<InputStream> inline) {
    final List<InputStream> inlineStreams;
    if (inlines.containsKey(name)) {
      inlineStreams = inlines.get(name);
    } else {
      inlineStreams = new ArrayList<InputStream>();
      inlines.put(name, inlineStreams);
    }

    inlineStreams.addAll(inline);

    return this;
  }

  public NavigationLinks addLinks(final String name, final String uri) {
    return addLinks(name, Collections.<String> singletonList(uri));
  }

  public NavigationLinks addLinks(final String name, final List<String> uris) {
    final List<String> current;
    if (links.containsKey(name)) {
      current = links.get(name);
    } else {
      current = new ArrayList<String>();
      links.put(name, current);
    }

    current.addAll(uris);

    return this;
  }

  public Set<String> getInlineNames() {
    return Collections.<String> unmodifiableSet(inlines.keySet());
  }

  public Set<String> getLinkNames() {
    return Collections.<String> unmodifiableSet(links.keySet());
  }

  public List<InputStream> getInlines(final String name) {
    return Collections.<InputStream> unmodifiableList(inlines.get(name));
  }

  public List<String> getLinks(final String name) {
    return Collections.<String> unmodifiableList(links.get(name));
  }

  public Iterable<Map.Entry<String, List<InputStream>>> getInlines() {
    return inlines.entrySet();
  }

  public Iterable<Map.Entry<String, List<String>>> getLinks() {
    return links.entrySet();
  }

  public boolean contains(final String name) {
    return links.containsKey(name) || inlines.containsKey(name);
  }

  public NavigationLinks remove(final String name) {
    removeLink(name);
    removeInlines(name);
    return this;
  }

  public NavigationLinks removeLink(final String name) {
    links.remove(name);
    return this;
  }

  public NavigationLinks removeInlines(final String name) {
    if (inlines.containsKey(name)) {
      for (InputStream is : inlines.get(name)) {
        IOUtils.closeQuietly(is);
      }
    }
    links.remove(name);
    return this;
  }
}


text:
Appearing elements on scroll. Built with jQuery.
## Prerequisites
You need to include **jQuery** before including **scroll-appear**.
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="scroll_appear.js"></script>
```
## Use
Example:
```javascript
<div class="object-to-appear"></div>

<script>
  $(".object-to-appear").appear("swipeLeft", 400, 150);
</script>
```
###### 1st argument ("swipeLeft")
Defines an animation that will be used for this element/elements. So far there are 5 animations:
> fadeIn (default), swipeLeft, swipeRight, zoomIn, zoomOut

###### 2nd argument (400)
Describes animation duration[ms] (default 500).

###### 3rd argument (150)
Tells what height[px] from bottom of the window is needed to trigger animation (default 150).

## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.


text:
.. _chap:distributions:

*************************
Probability distributions
*************************

PyMC provides 35 built-in probability distributions. For each distribution, it provides:

* A function that evaluates its log-probability or log-density: normal_like().
* A function that draws random variables: rnormal().
* A function that computes the expectation associated with the distribution: normal_expval().
* A Stochastic subclass generated from the distribution: Normal.

This section describes the likelihood functions of these distributions.

.. module:: pymc.distributions

Discrete distributions
======================

.. autofunction:: bernoulli_like

.. autofunction:: binomial_like

.. autofunction:: categorical_like

.. autofunction:: discrete_uniform_like

.. autofunction:: geometric_like

.. autofunction:: hypergeometric_like

.. autofunction:: negative_binomial_like

.. autofunction:: poisson_like

Continuous distributions
========================

.. autofunction:: beta_like

.. autofunction:: cauchy_like

.. autofunction:: chi2_like

.. autofunction:: degenerate_like

.. autofunction:: exponential_like

.. autofunction:: exponweib_like

.. autofunction:: gamma_like

.. autofunction:: half_normal_like

.. autofunction:: hypergeometric_like

.. autofunction:: inverse_gamma_like

.. autofunction:: laplace_like

.. autofunction:: logistic_like

.. autofunction:: lognormal_like

.. autofunction:: normal_like

.. autofunction:: skew_normal_like

.. autofunction:: t_like

.. autofunction:: truncnorm_like

.. autofunction:: uniform_like

.. autofunction:: von_mises_like

.. autofunction:: weibull_like

Multivariate discrete distributions
===================================

.. autofunction:: multivariate_hypergeometric_like

.. autofunction:: multinomial_like

Multivariate continuous distributions
=====================================

.. autofunction:: dirichlet_like

.. autofunction:: inverse_wishart_like

.. autofunction:: mv_normal_like

.. autofunction:: mv_normal_chol_like

.. autofunction:: mv_normal_cov_like

.. autofunction:: wishart_like

.. autofunction:: wishart_cov_like


text:
package com.kaching.platform.testing;

import com.kaching.platform.common.Errors;

/**
 * Thrown when an assertion failed for multiple reasons.
 */
public class CombinedAssertionFailedError extends AssertionError {

  private static final long serialVersionUID = 5967202290583940192L;

  private final String message;
  private final Errors errors;

  public CombinedAssertionFailedError() {
    this(null);
  }

  public CombinedAssertionFailedError(String message) {
    this.message = message;
    this.errors = new Errors();
  }

  public void addError(String error) {
    errors.addMessage(error);
  }

  @Override
  public String getMessage() {
    return toString();
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    if (message != null) {
      builder.append(message);
    }
    if (0 < errors.size()) {
      if (message != null) {
        builder.append(':');
        builder.append('\n');
      }
      builder.append(errors.toString());
    }
    return builder.toString();
  }

  /**
   * Throws this {@link CombinedAssertionFailedError} if any error was
   * encountered.
   */
  public void throwIfHasErrors() {
    if (0 < errors.size()) {
      throw this;
    }
  }

}


text:
namespace g{namespace Fuse{namespace Android{namespace NativeViews{struct HorizontalScrollView;}}}}
namespace g{namespace Fuse{namespace Android{namespace NativeViews{struct ScrollView;}}}}

namespace g{
namespace Fuse{
namespace Android{
namespace NativeViews{

// internal sealed extern class HorizontalScrollView :908
// {
::g::Android::android::view::ViewGroup_type* HorizontalScrollView_typeof();
void HorizontalScrollView__ctor_20_fn(HorizontalScrollView* __this, ::g::Fuse::Android::NativeViews::ScrollView* sv);
void HorizontalScrollView__New17_fn(::g::Fuse::Android::NativeViews::ScrollView* sv, HorizontalScrollView** __retval);
void HorizontalScrollView__onScrollChanged_fn(HorizontalScrollView* __this, int* x, int* y, int* oldx, int* oldy);

struct HorizontalScrollView : ::g::Android::android::widget::HorizontalScrollView
{
    static jclass _javaClass6_;
    static jclass& _javaClass6() { return _javaClass6_; }
    uStrong< ::g::Fuse::Android::NativeViews::ScrollView*> _sv;

    void ctor_20(::g::Fuse::Android::NativeViews::ScrollView* sv);
    static HorizontalScrollView* New17(::g::Fuse::Android::NativeViews::ScrollView* sv);
};
// }

}}}} // ::g::Fuse::Android::NativeViews


text:
module DeadlySerious
  module Engine
    class SoCommandContainer
      INPUT_PATTERN = '((<))'
      OUTPUT_PATTERN = '((>))'
      attr_reader :name

      def initialize(a_shell_command, env, config, reader_names, writer_names)
        @env = env
        @readers = reader_names.map { |r| Channel.of_type(r).io_name_for(r, config) }
        @writers = writer_names.map { |w| Channel.of_type(w).io_name_for(w, config) }
        @tokens = prepare_command(a_shell_command)
        @name = @tokens.first +
            @readers.map { |it| " <#{it}" }.join('') +
            @writers.map { |it| " >#{it}" }.join('')
      end

      def run
        in_out = {close_others: true,
                  in: @readers.size == 1 ? [@readers.first, 'r'] : :close,
                  out: @writers.size == 1 ? [@writers.first, 'w'] : :close}

        exec(@env, [@tokens.first, name], *@tokens[1..-1], in_out)
      end

      private

      def prepare_command(a_shell_command)
        shell_tokens = shell_tokens(a_shell_command)
        replace_placeholders(shell_tokens)
      end

      def shell_tokens(a_shell_command)
        case a_shell_command
          when Array
            a_shell_command
          else
            a_shell_command.to_s.split(/\s+/)
        end
      end

      def replace_placeholders(shell_tokens)
        shell_tokens.map do |token|
          case token
            when INPUT_PATTERN
              @readers.shift || fail('Missing reader')
            when OUTPUT_PATTERN
              @writers.shift || fail('Missing writer')
            else
              token.to_s
          end
        end
      end
    end
  end
end


text:
require 'spec_helper_acceptance'

describe 'swapcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
  describe 'success' do
    it 'works with strings' do
      pp = <<-EOS
      $o = swapcase('aBcD')
      notice(inline_template('swapcase is <%= @o.inspect %>'))
      EOS

      apply_manifest(pp, :catch_failures => true) do |r|
        expect(r.stdout).to match(/swapcase is "AbCd"/)
      end
    end
    it 'works with arrays'
  end
  describe 'failure' do
    it 'handles no arguments'
    it 'handles non arrays or strings'
  end
end


text:
<?php
declare(strict_types=1);

namespace Tests\Plugin\Phake;

use Moka\Plugin\Phake\PhakePlugin;
use Moka\Tests\MokaPluginTestCase;

class PhakePluginTest extends MokaPluginTestCase
{
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->setPluginFQCN(PhakePlugin::class);
    }
}


text:
package org.jetbrains.plugins.groovy.codeInspection.bugs;

import javax.annotation.Nonnull;

import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.codeInspection.GroovyFix;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMember;
import com.intellij.psi.PsiModifierList;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.PsiVariable;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;

/**
 * @author Max Medvedev
 */
public class GrModifierFix extends GroovyFix
{
	public static final Function<ProblemDescriptor, PsiModifierList> MODIFIER_LIST = new Function<ProblemDescriptor,
			PsiModifierList>()
	{
		@Override
		public PsiModifierList fun(ProblemDescriptor descriptor)
		{
			final PsiElement element = descriptor.getPsiElement();
			assert element instanceof PsiModifierList : element;
			return (PsiModifierList) element;
		}
	};

	public static final Function<ProblemDescriptor, PsiModifierList> MODIFIER_LIST_OWNER = new
			Function<ProblemDescriptor, PsiModifierList>()
	{
		@Override
		public PsiModifierList fun(ProblemDescriptor descriptor)
		{
			final PsiElement element = descriptor.getPsiElement();
			assert element instanceof PsiModifierListOwner : element;
			return ((PsiModifierListOwner) element).getModifierList();
		}
	};

	private final String myModifier;
	private final String myText;
	private final boolean myDoSet;
	private final Function<ProblemDescriptor, PsiModifierList> myModifierListProvider;

	public GrModifierFix(@Nonnull PsiVariable member,
			@GrModifier.GrModifierConstant String modifier,
			boolean doSet,
			@Nonnull Function<ProblemDescriptor, PsiModifierList> modifierListProvider)
	{
		myModifier = modifier;
		myDoSet = doSet;
		myModifierListProvider = modifierListProvider;
		myText = initText(doSet, member.getName(), modifier);
	}

	public GrModifierFix(@Nonnull PsiMember member,
			@GrModifier.GrModifierConstant String modifier,
			boolean showContainingClass,
			boolean doSet,
			@Nonnull Function<ProblemDescriptor, PsiModifierList> modifierListProvider)
	{
		myModifier = modifier;
		myDoSet = doSet;
		myModifierListProvider = modifierListProvider;
		myText = initText(doSet, getMemberName(member, showContainingClass), modifier);
	}

	public static String initText(boolean doSet, @Nonnull String name, @Nonnull String modifier)
	{
		return GroovyBundle.message(doSet ? "change.modifier" : "change.modifier.not", name,
				toPresentableText(modifier));
	}

	private static String getMemberName(PsiMember member, boolean showContainingClass)
	{
		if(showContainingClass)
		{
			final PsiClass containingClass = member.getContainingClass();
			String containingClassName = containingClass != null ? containingClass.getName() + "." : "";
			return containingClassName + member.getName();
		}
		else
		{
			return member.getName();
		}
	}

	public static String toPresentableText(String modifier)
	{
		return GroovyBundle.message(modifier + ".visibility.presentation");
	}

	@Nonnull
	@Override
	public String getName()
	{
		return myText;
	}

	@Override
	@Nonnull
	public String getFamilyName()
	{
		return GroovyBundle.message("change.modifier.family.name");
	}

	@Override
	protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException
	{
		final PsiModifierList modifierList = getModifierList(descriptor);
		modifierList.setModifierProperty(myModifier, myDoSet);
	}

	private PsiModifierList getModifierList(ProblemDescriptor descriptor)
	{
		return myModifierListProvider.fun(descriptor);
	}
}