text:
#include "XMLVariableWriter.h"

#include <boost/scope_exit.hpp>

BEGIN_NAMESPACE_MW

	void	variable_writer_error_func(void * _parser_context, const char * error, ...){

		va_list ap;
		va_start(ap, error);

		//mXMLParser *parser = (XMLParser *)_parser;
		//parser->addParserError(error);
#define ERROR_MSG_BUFFER_SIZE	512
		char buffer[ERROR_MSG_BUFFER_SIZE];// = { '\0' };
		vsnprintf(buffer, ERROR_MSG_BUFFER_SIZE-1, error, ap);
		va_end(ap);

		//xmlParserCtxt *context = (xmlParserCtxt *)_parser_context;
		//string error_string((char *)buffer);
		cerr << buffer << endl;
		merror(M_PARSER_MESSAGE_DOMAIN, "%s", buffer);
	}

void XMLVariableWriter::writeVariablesToFile(vector< shared_ptr<Variable> > variables,
											 boost::filesystem::path file){

    xmlParserCtxt *context = xmlNewParserCtxt();
    xmlSetGenericErrorFunc(context, &variable_writer_error_func);
    BOOST_SCOPE_EXIT( context ) {
        xmlSetGenericErrorFunc(NULL, NULL);
        xmlFreeParserCtxt(context);
    } BOOST_SCOPE_EXIT_END

    xmlDocPtr doc = xmlNewDoc((const xmlChar *)"1.0");
    BOOST_SCOPE_EXIT( doc ) {
        xmlFreeDoc(doc);
    } BOOST_SCOPE_EXIT_END

    xmlNodePtr mml_root = xmlNewDocNode(doc, NULL, (const xmlChar *)"monkeyml", NULL);
    xmlDocSetRootElement(doc, mml_root);

    xmlNewProp(mml_root, (const xmlChar *)"version", (const xmlChar *)"1.1");
    xmlNodePtr assignments_node = xmlNewChild(mml_root, NULL, (const xmlChar *)"variable_assignments", NULL);

    vector< shared_ptr<Variable> >::iterator i;
    for(i = variables.begin(); i != variables.end(); i++){
        shared_ptr<Variable> var = *i;
        xmlNodePtr variable_node = variableToXML(var);
        xmlAddChild(assignments_node, variable_node);
    }

    string path_str = file.string();
    xmlSaveFormatFile(path_str.c_str(), doc, 1);
}

xmlNodePtr XMLVariableWriter::variableToXML(shared_ptr<Variable> var){

    xmlNodePtr new_node = xmlNewNode(NULL, (const xmlChar *)"variable_assignment");
    xmlNewProp(new_node, (const xmlChar *)"variable", (const xmlChar *)((var->getVariableName()).c_str()));

 Datum value = var->getValue();

    GenericDataType type = value.getDataType();
    if(type == M_INTEGER){
        xmlNewProp(new_node, (const xmlChar *)"type", (const xmlChar *)"integer");
		xmlNewProp(new_node, (const xmlChar *)"value", (const xmlChar *)(value.toString().c_str()));
    } else if(type == M_FLOAT){
        xmlNewProp(new_node, (const xmlChar *)"type", (const xmlChar *)"float");
		xmlNewProp(new_node, (const xmlChar *)"value", (const xmlChar *)(value.toString().c_str()));
    } else if(type == M_BOOLEAN){
        xmlNewProp(new_node, (const xmlChar *)"type", (const xmlChar *)"boolean");
		xmlNewProp(new_node, (const xmlChar *)"value", (const xmlChar *)(value.toString().c_str()));
    } else if(type == M_STRING) {
        xmlNewProp(new_node, (const xmlChar *)"type", (const xmlChar *)"string");
		xmlNewProp(new_node, (const xmlChar *)"value", (const xmlChar *)(value.toString().c_str()));
    } else if(type == M_DICTIONARY) {
		xmlAddChild(new_node, recursiveValueToXML(value));
    } else if(type == M_LIST) {
		xmlAddChild(new_node, recursiveValueToXML(value));
    } else {
		throw SimpleException("Trying to save variables with bad type");
	}

    return new_node;
}

xmlNodePtr XMLVariableWriter::recursiveValueToXML(const Datum &value) {
    xmlNodePtr value_node;

	if(value.getDataType() == M_DICTIONARY) {
		value_node = xmlNewNode(NULL, (const xmlChar *)"dictionary");
        for (auto &item : value.getDict()) {
            xmlNodePtr dictionary_element_node = xmlNewNode(NULL, (const xmlChar *)"dictionary_element");
            xmlNodePtr key_node = xmlNewNode(NULL, (const xmlChar *)"key");
            xmlNodeSetContent(key_node, (const xmlChar *)item.first.toString().c_str());
            xmlNodePtr subvalue_node = xmlNewNode(NULL, (const xmlChar *)"value");

            auto &subvalue = item.second;
            if(subvalue.getDataType() == M_DICTIONARY || subvalue.getDataType() == M_LIST) {
                xmlAddChild(subvalue_node, recursiveValueToXML(subvalue));
            } else {
                GenericDataType type = subvalue.getDataType();
                if(type == M_INTEGER){
                    xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"integer");
                    xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
                } else if(type == M_FLOAT){
                    xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"float");
                    xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
                } else if(type == M_BOOLEAN){
                    xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"boolean");
                    xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
                } else if(type == M_STRING) {
                    xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"string");
                    xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
                } else {
                    throw SimpleException("Trying to find the value of a variable with a bad type");
                }
            }

            xmlAddChild(dictionary_element_node, key_node);
            xmlAddChild(dictionary_element_node, subvalue_node);
            xmlAddChild(value_node, dictionary_element_node);
        }
	} else if(value.getDataType() == M_LIST) {
		value_node = xmlNewNode(NULL, (const xmlChar *)"list_data");
        for (auto &subvalue : value.getList()) {
			xmlNodePtr list_element_node = xmlNewNode(NULL, (const xmlChar *)"list_element");
			xmlNodePtr subvalue_node = xmlNewNode(NULL, (const xmlChar *)"value");

			if(subvalue.getDataType() == M_DICTIONARY || subvalue.getDataType() == M_LIST) {
				xmlAddChild(subvalue_node, recursiveValueToXML(subvalue));
			} else {
				GenericDataType type = subvalue.getDataType();
				if(type == M_INTEGER){
					xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"integer");
					xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
				} else if(type == M_FLOAT){
					xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"float");
					xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
				} else if(type == M_BOOLEAN){
					xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"boolean");
					xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
				} else if(type == M_STRING) {
					xmlNewProp(subvalue_node, (const xmlChar *)"type", (const xmlChar *)"string");
					xmlNewProp(subvalue_node, (const xmlChar *)"value", (const xmlChar *)(subvalue.toString().c_str()));
				} else {
					throw SimpleException("Trying to find the value of a variable with a bad type");
				}
			}
			xmlAddChild(list_element_node, subvalue_node);
			xmlAddChild(value_node, list_element_node);
		}
	} else {
		throw SimpleException("Trying to save container data (M_LIST or M_DICT) and it's constructed incorrectly");
	}

	return value_node;
}

END_NAMESPACE_MW


text:
package org.fcrepo.server.storage.translation;

import org.junit.Test;

import org.fcrepo.server.storage.translation.FOXML1_1DODeserializer;
import org.fcrepo.server.storage.translation.FOXML1_1DOSerializer;

import static org.fcrepo.common.Models.CONTENT_MODEL_3_0;

/**
 * Unit tests for FOXML1_1DODeserializer.
 *
 * @author Chris Wilper
 */
public class TestFOXML1_1DODeserializer
        extends TestFOXMLDODeserializer {

    public TestFOXML1_1DODeserializer() {
        // superclass sets protected fields
        // m_deserializer and m_serializer as given below
        super(new FOXML1_1DODeserializer(), new FOXML1_1DOSerializer());
    }

    //---
    // Tests
    //---

    @Test
    public void testDeserializeSimpleCModelObject() {
        doSimpleTest(CONTENT_MODEL_3_0);
    }

    // Supports legacy test runners
    public static junit.framework.Test suite() {
        return new junit.framework.JUnit4TestAdapter(TestFOXML1_1DODeserializer.class);
    }

}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import print_function

import numpy as np
import scipy as sp
from scipy import linalg, optimize, rand

from ..base import BaseEstimator, RegressorMixin
from ..metrics.pairwise import manhattan_distances
from ..utils import check_random_state, check_array, check_X_y
from ..utils.validation import check_is_fitted
from . import regression_models as regression
from . import correlation_models as correlation

MACHINE_EPSILON = np.finfo(np.double).eps

def l1_cross_distances(X):
    """
    Computes the nonzero componentwise L1 cross-distances between the vectors
    in X.

    Parameters
    ----------

    X: array_like
        An array with shape (n_samples, n_features)

    Returns
    -------

    D: array with shape (n_samples * (n_samples - 1) / 2, n_features)
        The array of componentwise L1 cross-distances.

    ij: arrays with shape (n_samples * (n_samples - 1) / 2, 2)
        The indices i and j of the vectors in X associated to the cross-
        distances in D: D[k] = np.abs(X[ij[k, 0]] - Y[ij[k, 1]]).
    """
    X = check_array(X)
    n_samples, n_features = X.shape
    n_nonzero_cross_dist = n_samples * (n_samples - 1) // 2
    ij = np.zeros((n_nonzero_cross_dist, 2), dtype=np.int)
    D = np.zeros((n_nonzero_cross_dist, n_features))
    ll_1 = 0
    for k in range(n_samples - 1):
        ll_0 = ll_1
        ll_1 = ll_0 + n_samples - k - 1
        ij[ll_0:ll_1, 0] = k
        ij[ll_0:ll_1, 1] = np.arange(k + 1, n_samples)
        D[ll_0:ll_1] = np.abs(X[k] - X[(k + 1):n_samples])

    return D, ij

class GaussianProcess(BaseEstimator, RegressorMixin):
    """The Gaussian Process model class.

    Read more in the :ref:`User Guide <gaussian_process>`.

    Parameters
    ----------
    regr : string or callable, optional
        A regression function returning an array of outputs of the linear
        regression functional basis. The number of observations n_samples
        should be greater than the size p of this basis.
        Default assumes a simple constant regression trend.
        Available built-in regression models are::

            'constant', 'linear', 'quadratic'

    corr : string or callable, optional
        A stationary autocorrelation function returning the autocorrelation
        between two points x and x'.
        Default assumes a squared-exponential autocorrelation model.
        Built-in correlation models are::

            'absolute_exponential', 'squared_exponential',
            'generalized_exponential', 'cubic', 'linear'

    beta0 : double array_like, optional
        The regression weight vector to perform Ordinary Kriging (OK).
        Default assumes Universal Kriging (UK) so that the vector beta of
        regression weights is estimated using the maximum likelihood
        principle.

    storage_mode : string, optional
        A string specifying whether the Cholesky decomposition of the
        correlation matrix should be stored in the class (storage_mode =
        'full') or not (storage_mode = 'light').
        Default assumes storage_mode = 'full', so that the
        Cholesky decomposition of the correlation matrix is stored.
        This might be a useful parameter when one is not interested in the
        MSE and only plan to estimate the BLUP, for which the correlation
        matrix is not required.

    verbose : boolean, optional
        A boolean specifying the verbose level.
        Default is verbose = False.

    theta0 : double array_like, optional
        An array with shape (n_features, ) or (1, ).
        The parameters in the autocorrelation model.
        If thetaL and thetaU are also specified, theta0 is considered as
        the starting point for the maximum likelihood estimation of the
        best set of parameters.
        Default assumes isotropic autocorrelation model with theta0 = 1e-1.

    thetaL : double array_like, optional
        An array with shape matching theta0's.
        Lower bound on the autocorrelation parameters for maximum
        likelihood estimation.
        Default is None, so that it skips maximum likelihood estimation and
        it uses theta0.

    thetaU : double array_like, optional
        An array with shape matching theta0's.
        Upper bound on the autocorrelation parameters for maximum
        likelihood estimation.
        Default is None, so that it skips maximum likelihood estimation and
        it uses theta0.

    normalize : boolean, optional
        Input X and observations y are centered and reduced wrt
        means and standard deviations estimated from the n_samples
        observations provided.
        Default is normalize = True so that data is normalized to ease
        maximum likelihood estimation.

    nugget : double or ndarray, optional
        Introduce a nugget effect to allow smooth predictions from noisy
        data.  If nugget is an ndarray, it must be the same length as the
        number of data points used for the fit.
        The nugget is added to the diagonal of the assumed training covariance;
        in this way it acts as a Tikhonov regularization in the problem.  In
        the special case of the squared exponential correlation function, the
        nugget mathematically represents the variance of the input values.
        Default assumes a nugget close to machine precision for the sake of
        robustness (nugget = 10. * MACHINE_EPSILON).

    optimizer : string, optional
        A string specifying the optimization algorithm to be used.
        Default uses 'fmin_cobyla' algorithm from scipy.optimize.
        Available optimizers are::

            'fmin_cobyla', 'Welch'

        'Welch' optimizer is dued to Welch et al., see reference [WBSWM1992]_.
        It consists in iterating over several one-dimensional optimizations
        instead of running one single multi-dimensional optimization.

    random_start : int, optional
        The number of times the Maximum Likelihood Estimation should be
        performed from a random starting point.
        The first MLE always uses the specified starting point (theta0),
        the next starting points are picked at random according to an
        exponential distribution (log-uniform on [thetaL, thetaU]).
        Default does not use random starting point (random_start = 1).

    random_state: integer or numpy.RandomState, optional
        The generator used to shuffle the sequence of coordinates of theta in
        the Welch optimizer. If an integer is given, it fixes the seed.
        Defaults to the global numpy random number generator.

    Attributes
    ----------
    theta_ : array
        Specified theta OR the best set of autocorrelation parameters (the \
        sought maximizer of the reduced likelihood function).

    reduced_likelihood_function_value_ : array
        The optimal reduced likelihood function value.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.gaussian_process import GaussianProcess
    >>> X = np.array([[1., 3., 5., 6., 7., 8.]]).T
    >>> y = (X * np.sin(X)).ravel()
    >>> gp = GaussianProcess(theta0=0.1, thetaL=.001, thetaU=1.)
    >>> gp.fit(X, y)                                      # doctest: +ELLIPSIS
    GaussianProcess(beta0=None...
            ...

    Notes
    -----
    The presentation implementation is based on a translation of the DACE
    Matlab toolbox, see reference [NLNS2002]_.

    References
    ----------

    .. [NLNS2002] `H.B. Nielsen, S.N. Lophaven, H. B. Nielsen and J.
        Sondergaard.  DACE - A MATLAB Kriging Toolbox.` (2002)
        http://www2.imm.dtu.dk/~hbn/dace/dace.pdf

    .. [WBSWM1992] `W.J. Welch, R.J. Buck, J. Sacks, H.P. Wynn, T.J. Mitchell,
        and M.D.  Morris (1992). Screening, predicting, and computer
        experiments.  Technometrics, 34(1) 15--25.`
        http://www.jstor.org/pss/1269548
    """

    _regression_types = {
        'constant': regression.constant,
        'linear': regression.linear,
        'quadratic': regression.quadratic}

    _correlation_types = {
        'absolute_exponential': correlation.absolute_exponential,
        'squared_exponential': correlation.squared_exponential,
        'generalized_exponential': correlation.generalized_exponential,
        'cubic': correlation.cubic,
        'linear': correlation.linear}

    _optimizer_types = [
        'fmin_cobyla',
        'Welch']

    def __init__(self, regr='constant', corr='squared_exponential', beta0=None,
                 storage_mode='full', verbose=False, theta0=1e-1,
                 thetaL=None, thetaU=None, optimizer='fmin_cobyla',
                 random_start=1, normalize=True,
                 nugget=10. * MACHINE_EPSILON, random_state=None):

        self.regr = regr
        self.corr = corr
        self.beta0 = beta0
        self.storage_mode = storage_mode
        self.verbose = verbose
        self.theta0 = theta0
        self.thetaL = thetaL
        self.thetaU = thetaU
        self.normalize = normalize
        self.nugget = nugget
        self.optimizer = optimizer
        self.random_start = random_start
        self.random_state = random_state

    def fit(self, X, y):
        """
        The Gaussian Process model fitting method.

        Parameters
        ----------
        X : double array_like
            An array with shape (n_samples, n_features) with the input at which
            observations were made.

        y : double array_like
            An array with shape (n_samples, ) or shape (n_samples, n_targets)
            with the observations of the output to be predicted.

        Returns
        -------
        gp : self
            A fitted Gaussian Process model object awaiting data to perform
            predictions.
        """
        # Run input checks
        self._check_params()

        self.random_state = check_random_state(self.random_state)

        # Force data to 2D numpy.array
        X, y = check_X_y(X, y, multi_output=True, y_numeric=True)
        self.y_ndim_ = y.ndim
        if y.ndim == 1:
            y = y[:, np.newaxis]

        # Check shapes of DOE & observations
        n_samples, n_features = X.shape
        _, n_targets = y.shape

        # Run input checks
        self._check_params(n_samples)

        # Normalize data or don't
        if self.normalize:
            X_mean = np.mean(X, axis=0)
            X_std = np.std(X, axis=0)
            y_mean = np.mean(y, axis=0)
            y_std = np.std(y, axis=0)
            X_std[X_std == 0.] = 1.
            y_std[y_std == 0.] = 1.
            # center and scale X if necessary
            X = (X - X_mean) / X_std
            y = (y - y_mean) / y_std
        else:
            X_mean = np.zeros(1)
            X_std = np.ones(1)
            y_mean = np.zeros(1)
            y_std = np.ones(1)

        # Calculate matrix of distances D between samples
        D, ij = l1_cross_distances(X)
        if (np.min(np.sum(D, axis=1)) == 0.
                and self.corr != correlation.pure_nugget):
            raise Exception("Multiple input features cannot have the same"
                            " target value.")

        # Regression matrix and parameters
        F = self.regr(X)
        n_samples_F = F.shape[0]
        if F.ndim > 1:
            p = F.shape[1]
        else:
            p = 1
        if n_samples_F != n_samples:
            raise Exception("Number of rows in F and X do not match. Most "
                            "likely something is going wrong with the "
                            "regression model.")
        if p > n_samples_F:
            raise Exception(("Ordinary least squares problem is undetermined "
                             "n_samples=%d must be greater than the "
                             "regression model size p=%d.") % (n_samples, p))
        if self.beta0 is not None:
            if self.beta0.shape[0] != p:
                raise Exception("Shapes of beta0 and F do not match.")

        # Set attributes
        self.X = X
        self.y = y
        self.D = D
        self.ij = ij
        self.F = F
        self.X_mean, self.X_std = X_mean, X_std
        self.y_mean, self.y_std = y_mean, y_std

        # Determine Gaussian Process model parameters
        if self.thetaL is not None and self.thetaU is not None:
            # Maximum Likelihood Estimation of the parameters
            if self.verbose:
                print("Performing Maximum Likelihood Estimation of the "
                      "autocorrelation parameters...")
            self.theta_, self.reduced_likelihood_function_value_, par = \
                self._arg_max_reduced_likelihood_function()
            if np.isinf(self.reduced_likelihood_function_value_):
                raise Exception("Bad parameter region. "
                                "Try increasing upper bound")

        else:
            # Given parameters
            if self.verbose:
                print("Given autocorrelation parameters. "
                      "Computing Gaussian Process model parameters...")
            self.theta_ = self.theta0
            self.reduced_likelihood_function_value_, par = \
                self.reduced_likelihood_function()
            if np.isinf(self.reduced_likelihood_function_value_):
                raise Exception("Bad point. Try increasing theta0.")

        self.beta = par['beta']
        self.gamma = par['gamma']
        self.sigma2 = par['sigma2']
        self.C = par['C']
        self.Ft = par['Ft']
        self.G = par['G']

        if self.storage_mode == 'light':
            # Delete heavy data (it will be computed again if required)
            # (it is required only when MSE is wanted in self.predict)
            if self.verbose:
                print("Light storage mode specified. "
                      "Flushing autocorrelation matrix...")
            self.D = None
            self.ij = None
            self.F = None
            self.C = None
            self.Ft = None
            self.G = None

        return self

    def predict(self, X, eval_MSE=False, batch_size=None):
        """
        This function evaluates the Gaussian Process model at x.

        Parameters
        ----------
        X : array_like
            An array with shape (n_eval, n_features) giving the point(s) at
            which the prediction(s) should be made.

        eval_MSE : boolean, optional
            A boolean specifying whether the Mean Squared Error should be
            evaluated or not.
            Default assumes evalMSE = False and evaluates only the BLUP (mean
            prediction).

        batch_size : integer, optional
            An integer giving the maximum number of points that can be
            evaluated simultaneously (depending on the available memory).
            Default is None so that all given points are evaluated at the same
            time.

        Returns
        -------
        y : array_like, shape (n_samples, ) or (n_samples, n_targets)
            An array with shape (n_eval, ) if the Gaussian Process was trained
            on an array of shape (n_samples, ) or an array with shape
            (n_eval, n_targets) if the Gaussian Process was trained on an array
            of shape (n_samples, n_targets) with the Best Linear Unbiased
            Prediction at x.

        MSE : array_like, optional (if eval_MSE == True)
            An array with shape (n_eval, ) or (n_eval, n_targets) as with y,
            with the Mean Squared Error at x.
        """
        check_is_fitted(self, "X")

        # Check input shapes
        X = check_array(X)
        n_eval, _ = X.shape
        n_samples, n_features = self.X.shape
        n_samples_y, n_targets = self.y.shape

        # Run input checks
        self._check_params(n_samples)

        if X.shape[1] != n_features:
            raise ValueError(("The number of features in X (X.shape[1] = %d) "
                              "should match the number of features used "
                              "for fit() "
                              "which is %d.") % (X.shape[1], n_features))

        if batch_size is None:
            # No memory management
            # (evaluates all given points in a single batch run)

            # Normalize input
            X = (X - self.X_mean) / self.X_std

            # Initialize output
            y = np.zeros(n_eval)
            if eval_MSE:
                MSE = np.zeros(n_eval)

            # Get pairwise componentwise L1-distances to the input training set
            dx = manhattan_distances(X, Y=self.X, sum_over_features=False)
            # Get regression function and correlation
            f = self.regr(X)
            r = self.corr(self.theta_, dx).reshape(n_eval, n_samples)

            # Scaled predictor
            y_ = np.dot(f, self.beta) + np.dot(r, self.gamma)

            # Predictor
            y = (self.y_mean + self.y_std * y_).reshape(n_eval, n_targets)

            if self.y_ndim_ == 1:
                y = y.ravel()

            # Mean Squared Error
            if eval_MSE:
                C = self.C
                if C is None:
                    # Light storage mode (need to recompute C, F, Ft and G)
                    if self.verbose:
                        print("This GaussianProcess used 'light' storage mode "
                              "at instantiation. Need to recompute "
                              "autocorrelation matrix...")
                    reduced_likelihood_function_value, par = \
                        self.reduced_likelihood_function()
                    self.C = par['C']
                    self.Ft = par['Ft']
                    self.G = par['G']

                rt = linalg.solve_triangular(self.C, r.T, lower=True)

                if self.beta0 is None:
                    # Universal Kriging
                    u = linalg.solve_triangular(self.G.T,
                                                np.dot(self.Ft.T, rt) - f.T,
                                                lower=True)
                else:
                    # Ordinary Kriging
                    u = np.zeros((n_targets, n_eval))

                MSE = np.dot(self.sigma2.reshape(n_targets, 1),
                             (1. - (rt ** 2.).sum(axis=0)
                              + (u ** 2.).sum(axis=0))[np.newaxis, :])
                MSE = np.sqrt((MSE ** 2.).sum(axis=0) / n_targets)

                # Mean Squared Error might be slightly negative depending on
                # machine precision: force to zero!
                MSE[MSE < 0.] = 0.

                if self.y_ndim_ == 1:
                    MSE = MSE.ravel()

                return y, MSE

            else:

                return y

        else:
            # Memory management

            if type(batch_size) is not int or batch_size <= 0:
                raise Exception("batch_size must be a positive integer")

            if eval_MSE:

                y, MSE = np.zeros(n_eval), np.zeros(n_eval)
                for k in range(max(1, n_eval / batch_size)):
                    batch_from = k * batch_size
                    batch_to = min([(k + 1) * batch_size + 1, n_eval + 1])
                    y[batch_from:batch_to], MSE[batch_from:batch_to] = \
                        self.predict(X[batch_from:batch_to],
                                     eval_MSE=eval_MSE, batch_size=None)

                return y, MSE

            else:

                y = np.zeros(n_eval)
                for k in range(max(1, n_eval / batch_size)):
                    batch_from = k * batch_size
                    batch_to = min([(k + 1) * batch_size + 1, n_eval + 1])
                    y[batch_from:batch_to] = \
                        self.predict(X[batch_from:batch_to],
                                     eval_MSE=eval_MSE, batch_size=None)

                return y

    def reduced_likelihood_function(self, theta=None):
        """
        This function determines the BLUP parameters and evaluates the reduced
        likelihood function for the given autocorrelation parameters theta.

        Maximizing this function wrt the autocorrelation parameters theta is
        equivalent to maximizing the likelihood of the assumed joint Gaussian
        distribution of the observations y evaluated onto the design of
        experiments X.

        Parameters
        ----------
        theta : array_like, optional
            An array containing the autocorrelation parameters at which the
            Gaussian Process model parameters should be determined.
            Default uses the built-in autocorrelation parameters
            (ie ``theta = self.theta_``).

        Returns
        -------
        reduced_likelihood_function_value : double
            The value of the reduced likelihood function associated to the
            given autocorrelation parameters theta.

        par : dict
            A dictionary containing the requested Gaussian Process model
            parameters:

                sigma2
                        Gaussian Process variance.
                beta
                        Generalized least-squares regression weights for
                        Universal Kriging or given beta0 for Ordinary
                        Kriging.
                gamma
                        Gaussian Process weights.
                C
                        Cholesky decomposition of the correlation matrix [R].
                Ft
                        Solution of the linear equation system : [R] x Ft = F
                G
                        QR decomposition of the matrix Ft.
        """
        check_is_fitted(self, "X")

        if theta is None:
            # Use built-in autocorrelation parameters
            theta = self.theta_

        # Initialize output
        reduced_likelihood_function_value = - np.inf
        par = {}

        # Retrieve data
        n_samples = self.X.shape[0]
        D = self.D
        ij = self.ij
        F = self.F

        if D is None:
            # Light storage mode (need to recompute D, ij and F)
            D, ij = l1_cross_distances(self.X)
            if (np.min(np.sum(D, axis=1)) == 0.
                    and self.corr != correlation.pure_nugget):
                raise Exception("Multiple X are not allowed")
            F = self.regr(self.X)

        # Set up R
        r = self.corr(theta, D)
        R = np.eye(n_samples) * (1. + self.nugget)
        R[ij[:, 0], ij[:, 1]] = r
        R[ij[:, 1], ij[:, 0]] = r

        # Cholesky decomposition of R
        try:
            C = linalg.cholesky(R, lower=True)
        except linalg.LinAlgError:
            return reduced_likelihood_function_value, par

        # Get generalized least squares solution
        Ft = linalg.solve_triangular(C, F, lower=True)
        try:
            Q, G = linalg.qr(Ft, econ=True)
        except:
            #/usr/lib/python2.6/dist-packages/scipy/linalg/decomp.py:1177:
            # DeprecationWarning: qr econ argument will be removed after scipy
            # 0.7. The economy transform will then be available through the
            # mode='economic' argument.
            Q, G = linalg.qr(Ft, mode='economic')
            pass

        sv = linalg.svd(G, compute_uv=False)
        rcondG = sv[-1] / sv[0]
        if rcondG < 1e-10:
            # Check F
            sv = linalg.svd(F, compute_uv=False)
            condF = sv[0] / sv[-1]
            if condF > 1e15:
                raise Exception("F is too ill conditioned. Poor combination "
                                "of regression model and observations.")
            else:
                # Ft is too ill conditioned, get out (try different theta)
                return reduced_likelihood_function_value, par

        Yt = linalg.solve_triangular(C, self.y, lower=True)
        if self.beta0 is None:
            # Universal Kriging
            beta = linalg.solve_triangular(G, np.dot(Q.T, Yt))
        else:
            # Ordinary Kriging
            beta = np.array(self.beta0)

        rho = Yt - np.dot(Ft, beta)
        sigma2 = (rho ** 2.).sum(axis=0) / n_samples
        # The determinant of R is equal to the squared product of the diagonal
        # elements of its Cholesky decomposition C
        detR = (np.diag(C) ** (2. / n_samples)).prod()

        # Compute/Organize output
        reduced_likelihood_function_value = - sigma2.sum() * detR
        par['sigma2'] = sigma2 * self.y_std ** 2.
        par['beta'] = beta
        par['gamma'] = linalg.solve_triangular(C.T, rho)
        par['C'] = C
        par['Ft'] = Ft
        par['G'] = G

        return reduced_likelihood_function_value, par

    def _arg_max_reduced_likelihood_function(self):
        """
        This function estimates the autocorrelation parameters theta as the
        maximizer of the reduced likelihood function.
        (Minimization of the opposite reduced likelihood function is used for
        convenience)

        Parameters
        ----------
        self : All parameters are stored in the Gaussian Process model object.

        Returns
        -------
        optimal_theta : array_like
            The best set of autocorrelation parameters (the sought maximizer of
            the reduced likelihood function).

        optimal_reduced_likelihood_function_value : double
            The optimal reduced likelihood function value.

        optimal_par : dict
            The BLUP parameters associated to thetaOpt.
        """

        # Initialize output
        best_optimal_theta = []
        best_optimal_rlf_value = []
        best_optimal_par = []

        if self.verbose:
            print("The chosen optimizer is: " + str(self.optimizer))
            if self.random_start > 1:
                print(str(self.random_start) + " random starts are required.")

        percent_completed = 0.

        # Force optimizer to fmin_cobyla if the model is meant to be isotropic
        if self.optimizer == 'Welch' and self.theta0.size == 1:
            self.optimizer = 'fmin_cobyla'

        if self.optimizer == 'fmin_cobyla':

            def minus_reduced_likelihood_function(log10t):
                return - self.reduced_likelihood_function(
                    theta=10. ** log10t)[0]

            constraints = []
            for i in range(self.theta0.size):
                constraints.append(lambda log10t, i=i:
                                   log10t[i] - np.log10(self.thetaL[0, i]))
                constraints.append(lambda log10t, i=i:
                                   np.log10(self.thetaU[0, i]) - log10t[i])

            for k in range(self.random_start):

                if k == 0:
                    # Use specified starting point as first guess
                    theta0 = self.theta0
                else:
                    # Generate a random starting point log10-uniformly
                    # distributed between bounds
                    log10theta0 = (np.log10(self.thetaL)
                                   + self.random_state.rand(*self.theta0.shape)
                                   * np.log10(self.thetaU / self.thetaL))
                    theta0 = 10. ** log10theta0

                # Run Cobyla
                try:
                    log10_optimal_theta = \
                        optimize.fmin_cobyla(minus_reduced_likelihood_function,
                                             np.log10(theta0).ravel(), constraints,
                                             iprint=0)
                except ValueError as ve:
                    print("Optimization failed. Try increasing the ``nugget``")
                    raise ve

                optimal_theta = 10. ** log10_optimal_theta
                optimal_rlf_value, optimal_par = \
                    self.reduced_likelihood_function(theta=optimal_theta)

                # Compare the new optimizer to the best previous one
                if k > 0:
                    if optimal_rlf_value > best_optimal_rlf_value:
                        best_optimal_rlf_value = optimal_rlf_value
                        best_optimal_par = optimal_par
                        best_optimal_theta = optimal_theta
                else:
                    best_optimal_rlf_value = optimal_rlf_value
                    best_optimal_par = optimal_par
                    best_optimal_theta = optimal_theta
                if self.verbose and self.random_start > 1:
                    if (20 * k) / self.random_start > percent_completed:
                        percent_completed = (20 * k) / self.random_start
                        print("%s completed" % (5 * percent_completed))

            optimal_rlf_value = best_optimal_rlf_value
            optimal_par = best_optimal_par
            optimal_theta = best_optimal_theta

        elif self.optimizer == 'Welch':

            # Backup of the given atrributes
            theta0, thetaL, thetaU = self.theta0, self.thetaL, self.thetaU
            corr = self.corr
            verbose = self.verbose

            # This will iterate over fmin_cobyla optimizer
            self.optimizer = 'fmin_cobyla'
            self.verbose = False

            # Initialize under isotropy assumption
            if verbose:
                print("Initialize under isotropy assumption...")
            self.theta0 = check_array(self.theta0.min())
            self.thetaL = check_array(self.thetaL.min())
            self.thetaU = check_array(self.thetaU.max())
            theta_iso, optimal_rlf_value_iso, par_iso = \
                self._arg_max_reduced_likelihood_function()
            optimal_theta = theta_iso + np.zeros(theta0.shape)

            # Iterate over all dimensions of theta allowing for anisotropy
            if verbose:
                print("Now improving allowing for anisotropy...")
            for i in self.random_state.permutation(theta0.size):
                if verbose:
                    print("Proceeding along dimension %d..." % (i + 1))
                self.theta0 = check_array(theta_iso)
                self.thetaL = check_array(thetaL[0, i])
                self.thetaU = check_array(thetaU[0, i])

                def corr_cut(t, d):
                    return corr(check_array(np.hstack([optimal_theta[0][0:i],
                                                       t[0],
                                                       optimal_theta[0][(i +
                                                                         1)::]])),
                                d)

                self.corr = corr_cut
                optimal_theta[0, i], optimal_rlf_value, optimal_par = \
                    self._arg_max_reduced_likelihood_function()

            # Restore the given atrributes
            self.theta0, self.thetaL, self.thetaU = theta0, thetaL, thetaU
            self.corr = corr
            self.optimizer = 'Welch'
            self.verbose = verbose

        else:

            raise NotImplementedError("This optimizer ('%s') is not "
                                      "implemented yet. Please contribute!"
                                      % self.optimizer)

        return optimal_theta, optimal_rlf_value, optimal_par

    def _check_params(self, n_samples=None):

        # Check regression model
        if not callable(self.regr):
            if self.regr in self._regression_types:
                self.regr = self._regression_types[self.regr]
            else:
                raise ValueError("regr should be one of %s or callable, "
                                 "%s was given."
                                 % (self._regression_types.keys(), self.regr))

        # Check regression weights if given (Ordinary Kriging)
        if self.beta0 is not None:
            self.beta0 = np.atleast_2d(self.beta0)
            if self.beta0.shape[1] != 1:
                # Force to column vector
                self.beta0 = self.beta0.T

        # Check correlation model
        if not callable(self.corr):
            if self.corr in self._correlation_types:
                self.corr = self._correlation_types[self.corr]
            else:
                raise ValueError("corr should be one of %s or callable, "
                                 "%s was given."
                                 % (self._correlation_types.keys(), self.corr))

        # Check storage mode
        if self.storage_mode != 'full' and self.storage_mode != 'light':
            raise ValueError("Storage mode should either be 'full' or "
                             "'light', %s was given." % self.storage_mode)

        # Check correlation parameters
        self.theta0 = np.atleast_2d(self.theta0)
        lth = self.theta0.size

        if self.thetaL is not None and self.thetaU is not None:
            self.thetaL = np.atleast_2d(self.thetaL)
            self.thetaU = np.atleast_2d(self.thetaU)
            if self.thetaL.size != lth or self.thetaU.size != lth:
                raise ValueError("theta0, thetaL and thetaU must have the "
                                 "same length.")
            if np.any(self.thetaL <= 0) or np.any(self.thetaU < self.thetaL):
                raise ValueError("The bounds must satisfy O < thetaL <= "
                                 "thetaU.")

        elif self.thetaL is None and self.thetaU is None:
            if np.any(self.theta0 <= 0):
                raise ValueError("theta0 must be strictly positive.")

        elif self.thetaL is None or self.thetaU is None:
            raise ValueError("thetaL and thetaU should either be both or "
                             "neither specified.")

        # Force verbose type to bool
        self.verbose = bool(self.verbose)

        # Force normalize type to bool
        self.normalize = bool(self.normalize)

        # Check nugget value
        self.nugget = np.asarray(self.nugget)
        if np.any(self.nugget) < 0.:
            raise ValueError("nugget must be positive or zero.")
        if (n_samples is not None
                and self.nugget.shape not in [(), (n_samples,)]):
            raise ValueError("nugget must be either a scalar "
                             "or array of length n_samples.")

        # Check optimizer
        if self.optimizer not in self._optimizer_types:
            raise ValueError("optimizer should be one of %s"
                             % self._optimizer_types)

        # Force random_start type to int
        self.random_start = int(self.random_start)

    def predict_gradient(self, X):
        """
        This function evaluates the Gaussian Process model at x.

        Parameters
        ----------
        X : array_like
            An array with shape (n_eval, n_features) giving the point(s) at
            which the prediction(s) should be made.

        Returns
        -------
        yprime : array_like, shape (n_eval, n_features).
        """

        # assert self.corr == 'squared_exponential'
        X = check_array(X)
        X = (X - self.X_mean) / self.X_std
        X = sp.atleast_2d(X)

        n_eval, _ = X.shape
        n_samples, n_features = self.X.shape
        n_samples_y, n_targets = self.y.shape

        # Get pairwise componentwise L1-distances to the input training set
        dx = manhattan_distances(X, Y=self.X, sum_over_features=False)
        # Get regression correlation
        r = self.corr(self.theta_, dx).reshape(n_eval, n_samples)
        # Get derivative of regression correlation
        dr_dx = -2 * self.theta_ * (X - self.X) * r.T
        # Predictor of function derivative
        yprime = self.y_std * sp.dot(dr_dx.T, self.gamma)
        return yprime

    def accumulate_data(self, X, y):
        """
        Add datapoints without fitting them.
        Parameters
        ----------
        X : double array_like
            An array with shape (n_samples, n_features) with the input at which
            new observations were made.
        y : double array_like
            An array with shape (n_samples, ) or shape (n_samples, n_targets)
            with the new observations of the output to be predicted.
        Returns
        -------
        gp : self
            A Gaussian Process model object.
        """
        # Force data to 2D numpy.array
        X, y = check_X_y(X, y) # , multi_output=True, y_numeric=True)
        if y.ndim == 1:
            y = y[:, None]

        if hasattr(self, 'X'):
            # retrieve old X and y to make them compatible with new observations.
            if self.normalize:
                X_old = self.X_std * (self.X + self.X_mean)
                y_old = self.y_std * (self.y + self.y_mean)
            else:
                X_old, y_old = self.X, self.y
            # stack unscaled old and new data together
            self.X, self.y = sp.vstack((X_old, X)), sp.vstack((y_old, y))
        else:
            # No data present
            self.X, self.y = X, y
        # Clear out the data scaling
        self.X_mean, self.y_mean = sp.zeros(1), sp.zeros(1)
        self.X_std, self.y_std = sp.ones(1), sp.ones(1)

        return self

    def update_fit(self, X, y):
        """
        The Gaussian Process model fitting method.
        Parameters
        ----------
        X : double array_like
            An array with shape (n_samples, n_features) with the input at which
            new observations were made.
        y : double array_like
            An array with shape (n_samples, ) or shape (n_samples, n_targets)
            with the new observations of the output to be predicted.
        Returns
        -------
        gp : self
            A re-fitted Gaussian Process model object awaiting data to perform
            predictions.
        """
        # Add (X, y) training points to the current dataset.

        X, y = check_X_y(X, y)
        self.accumulate_data(X, y)
        # start ML optimisation from the previously optimised hyperparameters (if present)
        if hasattr(self, 'theta_'):
            self.theta0 = self.theta_
        # perform fitting
        self.fit(self.X, self.y)
        return self


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.Tests;
using Net.Pkcs11Interop.Tests.HighLevelAPI;
using Net.Pkcs11Interop.Common;

namespace TestProject1.HighLevelAPI
{
    [TestClass]
    public class CKM_GOSTR3411_12_512_Tests
    {
        [TestMethod]
        public void _01_DigestSinglePartTest()
        {
            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RO session
                using (Session session = slot.OpenSession(true))
                {
                    // Specify digesting mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_GOSTR3411_12_512);

                    byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world, how do you do?");

                    // Digest data
                    byte[] digest = session.Digest(mechanism, sourceData);

                    // Do something interesting with digest value
                    //Assert.IsTrue(Convert.ToBase64String(digest) == "e1AsOh9IyGCa4hLN+2Od7jlnP14=");
                }
            }
        }
    }
}


text:
<?php
/**
 * XprofileField
 *
 * PHP version 5
 *
 * @category Class
 * @package  QuantiModo\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * quantimodo
 *
 * We make it easy to retrieve and analyze normalized user data from a wide array of devices and applications. Check out our [docs and sdk's](https://github.com/QuantiModo/docs) or [contact us](https://help.quantimo.do).
 *
 * OpenAPI spec version: 5.8.112511
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.9
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace QuantiModo\Client\Model;

use \ArrayAccess;
use \QuantiModo\Client\ObjectSerializer;

/**
 * XprofileField Class Doc Comment
 *
 * @category Class
 * @package  QuantiModo\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class XprofileField implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'XprofileField';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'id' => 'int',
        'group_id' => 'int',
        'parent_id' => 'int',
        'type' => 'string',
        'name' => 'string',
        'description' => 'string',
        'is_required' => 'int',
        'is_default_option' => 'int',
        'field_order' => 'int',
        'option_order' => 'int',
        'order_by' => 'string',
        'can_delete' => 'int',
        'meta_data_array' => 'object[]'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'id' => null,
        'group_id' => null,
        'parent_id' => null,
        'type' => null,
        'name' => null,
        'description' => null,
        'is_required' => null,
        'is_default_option' => null,
        'field_order' => null,
        'option_order' => null,
        'order_by' => null,
        'can_delete' => null,
        'meta_data_array' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'id' => 'id',
        'group_id' => 'groupId',
        'parent_id' => 'parentId',
        'type' => 'type',
        'name' => 'name',
        'description' => 'description',
        'is_required' => 'isRequired',
        'is_default_option' => 'isDefaultOption',
        'field_order' => 'fieldOrder',
        'option_order' => 'optionOrder',
        'order_by' => 'orderBy',
        'can_delete' => 'canDelete',
        'meta_data_array' => 'metaDataArray'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'id' => 'setId',
        'group_id' => 'setGroupId',
        'parent_id' => 'setParentId',
        'type' => 'setType',
        'name' => 'setName',
        'description' => 'setDescription',
        'is_required' => 'setIsRequired',
        'is_default_option' => 'setIsDefaultOption',
        'field_order' => 'setFieldOrder',
        'option_order' => 'setOptionOrder',
        'order_by' => 'setOrderBy',
        'can_delete' => 'setCanDelete',
        'meta_data_array' => 'setMetaDataArray'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'id' => 'getId',
        'group_id' => 'getGroupId',
        'parent_id' => 'getParentId',
        'type' => 'getType',
        'name' => 'getName',
        'description' => 'getDescription',
        'is_required' => 'getIsRequired',
        'is_default_option' => 'getIsDefaultOption',
        'field_order' => 'getFieldOrder',
        'option_order' => 'getOptionOrder',
        'order_by' => 'getOrderBy',
        'can_delete' => 'getCanDelete',
        'meta_data_array' => 'getMetaDataArray'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['id'] = isset($data['id']) ? $data['id'] : null;
        $this->container['group_id'] = isset($data['group_id']) ? $data['group_id'] : null;
        $this->container['parent_id'] = isset($data['parent_id']) ? $data['parent_id'] : null;
        $this->container['type'] = isset($data['type']) ? $data['type'] : null;
        $this->container['name'] = isset($data['name']) ? $data['name'] : null;
        $this->container['description'] = isset($data['description']) ? $data['description'] : null;
        $this->container['is_required'] = isset($data['is_required']) ? $data['is_required'] : null;
        $this->container['is_default_option'] = isset($data['is_default_option']) ? $data['is_default_option'] : null;
        $this->container['field_order'] = isset($data['field_order']) ? $data['field_order'] : null;
        $this->container['option_order'] = isset($data['option_order']) ? $data['option_order'] : null;
        $this->container['order_by'] = isset($data['order_by']) ? $data['order_by'] : null;
        $this->container['can_delete'] = isset($data['can_delete']) ? $data['can_delete'] : null;
        $this->container['meta_data_array'] = isset($data['meta_data_array']) ? $data['meta_data_array'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        if ($this->container['id'] === null) {
            $invalidProperties[] = "'id' can't be null";
        }
        if ($this->container['group_id'] === null) {
            $invalidProperties[] = "'group_id' can't be null";
        }
        if ($this->container['parent_id'] === null) {
            $invalidProperties[] = "'parent_id' can't be null";
        }
        if ($this->container['type'] === null) {
            $invalidProperties[] = "'type' can't be null";
        }
        if ($this->container['name'] === null) {
            $invalidProperties[] = "'name' can't be null";
        }
        if ($this->container['description'] === null) {
            $invalidProperties[] = "'description' can't be null";
        }
        if ($this->container['is_required'] === null) {
            $invalidProperties[] = "'is_required' can't be null";
        }
        if ($this->container['is_default_option'] === null) {
            $invalidProperties[] = "'is_default_option' can't be null";
        }
        if ($this->container['field_order'] === null) {
            $invalidProperties[] = "'field_order' can't be null";
        }
        if ($this->container['option_order'] === null) {
            $invalidProperties[] = "'option_order' can't be null";
        }
        if ($this->container['order_by'] === null) {
            $invalidProperties[] = "'order_by' can't be null";
        }
        if ($this->container['can_delete'] === null) {
            $invalidProperties[] = "'can_delete' can't be null";
        }
        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets id
     *
     * @return int
     */
    public function getId()
    {
        return $this->container['id'];
    }

    /**
     * Sets id
     *
     * @param int $id What do you expect?
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->container['id'] = $id;

        return $this;
    }

    /**
     * Gets group_id
     *
     * @return int
     */
    public function getGroupId()
    {
        return $this->container['group_id'];
    }

    /**
     * Sets group_id
     *
     * @param int $group_id What do you expect?
     *
     * @return $this
     */
    public function setGroupId($group_id)
    {
        $this->container['group_id'] = $group_id;

        return $this;
    }

    /**
     * Gets parent_id
     *
     * @return int
     */
    public function getParentId()
    {
        return $this->container['parent_id'];
    }

    /**
     * Sets parent_id
     *
     * @param int $parent_id What do you expect?
     *
     * @return $this
     */
    public function setParentId($parent_id)
    {
        $this->container['parent_id'] = $parent_id;

        return $this;
    }

    /**
     * Gets type
     *
     * @return string
     */
    public function getType()
    {
        return $this->container['type'];
    }

    /**
     * Sets type
     *
     * @param string $type What do you expect?
     *
     * @return $this
     */
    public function setType($type)
    {
        $this->container['type'] = $type;

        return $this;
    }

    /**
     * Gets name
     *
     * @return string
     */
    public function getName()
    {
        return $this->container['name'];
    }

    /**
     * Sets name
     *
     * @param string $name What do you expect?
     *
     * @return $this
     */
    public function setName($name)
    {
        $this->container['name'] = $name;

        return $this;
    }

    /**
     * Gets description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->container['description'];
    }

    /**
     * Sets description
     *
     * @param string $description What do you expect?
     *
     * @return $this
     */
    public function setDescription($description)
    {
        $this->container['description'] = $description;

        return $this;
    }

    /**
     * Gets is_required
     *
     * @return int
     */
    public function getIsRequired()
    {
        return $this->container['is_required'];
    }

    /**
     * Sets is_required
     *
     * @param int $is_required What do you expect?
     *
     * @return $this
     */
    public function setIsRequired($is_required)
    {
        $this->container['is_required'] = $is_required;

        return $this;
    }

    /**
     * Gets is_default_option
     *
     * @return int
     */
    public function getIsDefaultOption()
    {
        return $this->container['is_default_option'];
    }

    /**
     * Sets is_default_option
     *
     * @param int $is_default_option What do you expect?
     *
     * @return $this
     */
    public function setIsDefaultOption($is_default_option)
    {
        $this->container['is_default_option'] = $is_default_option;

        return $this;
    }

    /**
     * Gets field_order
     *
     * @return int
     */
    public function getFieldOrder()
    {
        return $this->container['field_order'];
    }

    /**
     * Sets field_order
     *
     * @param int $field_order What do you expect?
     *
     * @return $this
     */
    public function setFieldOrder($field_order)
    {
        $this->container['field_order'] = $field_order;

        return $this;
    }

    /**
     * Gets option_order
     *
     * @return int
     */
    public function getOptionOrder()
    {
        return $this->container['option_order'];
    }

    /**
     * Sets option_order
     *
     * @param int $option_order What do you expect?
     *
     * @return $this
     */
    public function setOptionOrder($option_order)
    {
        $this->container['option_order'] = $option_order;

        return $this;
    }

    /**
     * Gets order_by
     *
     * @return string
     */
    public function getOrderBy()
    {
        return $this->container['order_by'];
    }

    /**
     * Sets order_by
     *
     * @param string $order_by What do you expect?
     *
     * @return $this
     */
    public function setOrderBy($order_by)
    {
        $this->container['order_by'] = $order_by;

        return $this;
    }

    /**
     * Gets can_delete
     *
     * @return int
     */
    public function getCanDelete()
    {
        return $this->container['can_delete'];
    }

    /**
     * Sets can_delete
     *
     * @param int $can_delete What do you expect?
     *
     * @return $this
     */
    public function setCanDelete($can_delete)
    {
        $this->container['can_delete'] = $can_delete;

        return $this;
    }

    /**
     * Gets meta_data_array
     *
     * @return object[]
     */
    public function getMetaDataArray()
    {
        return $this->container['meta_data_array'];
    }

    /**
     * Sets meta_data_array
     *
     * @param object[] $meta_data_array Additional xprofilefield key-value data
     *
     * @return $this
     */
    public function setMetaDataArray($meta_data_array)
    {
        $this->container['meta_data_array'] = $meta_data_array;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Extensions;

// ReSharper disable once CheckNamespace
namespace Umbraco.Cms.Core.Services;

internal class ContentVersionService : IContentVersionService
{
    private readonly IAuditRepository _auditRepository;
    private readonly IContentVersionCleanupPolicy _contentVersionCleanupPolicy;
    private readonly IDocumentVersionRepository _documentVersionRepository;
    private readonly IEventMessagesFactory _eventMessagesFactory;
    private readonly ILanguageRepository _languageRepository;
    private readonly ILogger<ContentVersionService> _logger;
    private readonly ICoreScopeProvider _scopeProvider;

    public ContentVersionService(
        ILogger<ContentVersionService> logger,
        IDocumentVersionRepository documentVersionRepository,
        IContentVersionCleanupPolicy contentVersionCleanupPolicy,
        ICoreScopeProvider scopeProvider,
        IEventMessagesFactory eventMessagesFactory,
        IAuditRepository auditRepository,
        ILanguageRepository languageRepository)
    {
        _logger = logger;
        _documentVersionRepository = documentVersionRepository;
        _contentVersionCleanupPolicy = contentVersionCleanupPolicy;
        _scopeProvider = scopeProvider;
        _eventMessagesFactory = eventMessagesFactory;
        _auditRepository = auditRepository;
        _languageRepository = languageRepository;
    }

    /// <inheritdoc />
    public IReadOnlyCollection<ContentVersionMeta> PerformContentVersionCleanup(DateTime asAtDate) =>

        // Media - ignored
        // Members - ignored
        CleanupDocumentVersions(asAtDate);

    /// <inheritdoc />
    public IEnumerable<ContentVersionMeta>? GetPagedContentVersions(int contentId, long pageIndex, int pageSize, out long totalRecords, string? culture = null)
    {
        if (pageIndex < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(pageIndex));
        }

        if (pageSize <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(pageSize));
        }

        using (ICoreScope scope = _scopeProvider.CreateCoreScope(autoComplete: true))
        {
            var languageId = _languageRepository.GetIdByIsoCode(culture, true);
            scope.ReadLock(Constants.Locks.ContentTree);
            return _documentVersionRepository.GetPagedItemsByContentId(contentId, pageIndex, pageSize, out totalRecords, languageId);
        }
    }

    /// <inheritdoc />
    public void SetPreventCleanup(int versionId, bool preventCleanup, int userId = -1)
    {
        using (ICoreScope scope = _scopeProvider.CreateCoreScope(autoComplete: true))
        {
            scope.WriteLock(Constants.Locks.ContentTree);
            _documentVersionRepository.SetPreventCleanup(versionId, preventCleanup);

            ContentVersionMeta? version = _documentVersionRepository.Get(versionId);

            if (version is null)
            {
                return;
            }

            AuditType auditType = preventCleanup
                ? AuditType.ContentVersionPreventCleanup
                : AuditType.ContentVersionEnableCleanup;

            var message = $"set preventCleanup = '{preventCleanup}' for version '{versionId}'";

            Audit(auditType, userId, version.ContentId, message, $"{version.VersionDate}");
        }
    }

    private IReadOnlyCollection<ContentVersionMeta> CleanupDocumentVersions(DateTime asAtDate)
    {
        List<ContentVersionMeta> versionsToDelete;

        /* Why so many scopes?
         *
         * We could just work out the set to delete at SQL infra level which was the original plan, however we agreed that really we should fire
         * ContentService.DeletingVersions so people can hook & cancel if required.
         *
         * On first time run of cleanup on a site with a lot of history there may be a lot of historic ContentVersions to remove e.g. 200K for our.umbraco.com.
         * If we weren't supporting SQL CE we could do TVP, or use temp tables to bulk delete with joins to our list of version ids to nuke.
         * (much nicer, we can kill 100k in sub second time-frames).
         *
         * However we are supporting SQL CE, so the easiest thing to do is use the Umbraco InGroupsOf helper to create a query with 2K args of version
         * ids to delete at a time.
         *
         * This is already done at the repository level, however if we only had a single scope at service level we're still locking
         * the ContentVersions table (and other related tables) for a couple of minutes which makes the back office unusable.
         *
         * As a quick fix, we can also use InGroupsOf at service level, create a scope per group to give other connections a chance
         * to grab the locks and execute their queries.
         *
         * This makes the back office a tiny bit sluggish during first run but it is usable for loading tree and publishing content.
         *
         * There are optimizations we can do, we could add a bulk delete for SqlServerSyntaxProvider which differs in implementation
         * and fallback to this naive approach only for SQL CE, however we agreed it is not worth the effort as this is a one time pain,
         * subsequent runs shouldn't have huge numbers of versions to cleanup.
         *
         * tl;dr lots of scopes to enable other connections to use the DB whilst we work.
         */
        using (ICoreScope scope = _scopeProvider.CreateCoreScope(autoComplete: true))
        {
            IReadOnlyCollection<ContentVersionMeta>? allHistoricVersions =
                _documentVersionRepository.GetDocumentVersionsEligibleForCleanup();

            if (allHistoricVersions is null)
            {
                return Array.Empty<ContentVersionMeta>();
            }

            _logger.LogDebug("Discovered {count} candidate(s) for ContentVersion cleanup", allHistoricVersions.Count);
            versionsToDelete = new List<ContentVersionMeta>(allHistoricVersions.Count);

            IEnumerable<ContentVersionMeta> filteredContentVersions =
                _contentVersionCleanupPolicy.Apply(asAtDate, allHistoricVersions);

            foreach (ContentVersionMeta version in filteredContentVersions)
            {
                EventMessages messages = _eventMessagesFactory.Get();

                if (scope.Notifications.PublishCancelable(
                        new ContentDeletingVersionsNotification(version.ContentId, messages, version.VersionId)))
                {
                    _logger.LogDebug("Delete cancelled for ContentVersion [{versionId}]", version.VersionId);
                    continue;
                }

                versionsToDelete.Add(version);
            }
        }

        if (!versionsToDelete.Any())
        {
            _logger.LogDebug("No remaining ContentVersions for cleanup");
            return Array.Empty<ContentVersionMeta>();
        }

        _logger.LogDebug("Removing {count} ContentVersion(s)", versionsToDelete.Count);

        foreach (IEnumerable<ContentVersionMeta> group in versionsToDelete.InGroupsOf(Constants.Sql.MaxParameterCount))
        {
            using (ICoreScope scope = _scopeProvider.CreateCoreScope(autoComplete: true))
            {
                scope.WriteLock(Constants.Locks.ContentTree);
                var groupEnumerated = group.ToList();
                _documentVersionRepository.DeleteVersions(groupEnumerated.Select(x => x.VersionId));

                foreach (ContentVersionMeta version in groupEnumerated)
                {
                    EventMessages messages = _eventMessagesFactory.Get();

                    scope.Notifications.Publish(
                        new ContentDeletedVersionsNotification(version.ContentId, messages, version.VersionId));
                }
            }
        }

        using (_scopeProvider.CreateCoreScope(autoComplete: true))
        {
            Audit(AuditType.Delete, Constants.Security.SuperUserId, -1, $"Removed {versionsToDelete.Count} ContentVersion(s) according to cleanup policy");
        }

        return versionsToDelete;
    }

    private void Audit(AuditType type, int userId, int objectId, string? message = null, string? parameters = null)
    {
        var entry = new AuditItem(
            objectId,
            type,
            userId,
            UmbracoObjectTypes.Document.GetName(),
            message,
            parameters);

        _auditRepository.Save(entry);
    }
}


text:
using namespace cv;

VideoDevice::VideoDevice(){
    //does absolutely nothing
}

void VideoDevice::startCapture(int id){
    camera = VideoCapture(id);
}

Mat VideoDevice:: getImage(){
    takeImage();
    return image;
}

void VideoDevice::takeImage(){
    camera >> image;
}


text:
namespace ui {

namespace {

void PrepareEmptyTestData(Pickle* pickle) {
  std::map<string16, string16> data;
  WriteCustomDataToPickle(data, pickle);
}

void PrepareTestData(Pickle* pickle) {
  std::map<string16, string16> data;
  data.insert(std::make_pair(ASCIIToUTF16("abc"), string16()));
  data.insert(std::make_pair(ASCIIToUTF16("de"), ASCIIToUTF16("1")));
  data.insert(std::make_pair(ASCIIToUTF16("f"), ASCIIToUTF16("23")));
  WriteCustomDataToPickle(data, pickle);
}

TEST(CustomDataHelperTest, EmptyReadTypes) {
  Pickle pickle;
  PrepareEmptyTestData(&pickle);

  std::vector<string16> types;
  ReadCustomDataTypes(pickle.data(), pickle.size(), &types);
  EXPECT_EQ(0u, types.size());
}

TEST(CustomDataHelperTest, EmptyReadSingleType) {
  Pickle pickle;
  PrepareEmptyTestData(&pickle);

  string16 result;
  ReadCustomDataForType(pickle.data(),
                        pickle.size(),
                        ASCIIToUTF16("f"),
                        &result);
  EXPECT_EQ(string16(), result);
}

TEST(CustomDataHelperTest, EmptyReadMap) {
  Pickle pickle;
  PrepareEmptyTestData(&pickle);

  std::map<string16, string16> result;
  ReadCustomDataIntoMap(pickle.data(), pickle.size(), &result);
  EXPECT_EQ(0u, result.size());
}

TEST(CustomDataHelperTest, ReadTypes) {
  Pickle pickle;
  PrepareTestData(&pickle);

  std::vector<string16> types;
  ReadCustomDataTypes(pickle.data(), pickle.size(), &types);

  std::vector<string16> expected;
  expected.push_back(ASCIIToUTF16("abc"));
  expected.push_back(ASCIIToUTF16("de"));
  expected.push_back(ASCIIToUTF16("f"));
  EXPECT_EQ(expected, types);
}

TEST(CustomDataHelperTest, ReadSingleType) {
  Pickle pickle;
  PrepareTestData(&pickle);

  string16 result;
  ReadCustomDataForType(pickle.data(),
                        pickle.size(),
                        ASCIIToUTF16("abc"),
                        &result);
  EXPECT_EQ(string16(), result);

  ReadCustomDataForType(pickle.data(),
                        pickle.size(),
                        ASCIIToUTF16("de"),
                        &result);
  EXPECT_EQ(ASCIIToUTF16("1"), result);

  ReadCustomDataForType(pickle.data(),
                        pickle.size(),
                        ASCIIToUTF16("f"),
                        &result);
  EXPECT_EQ(ASCIIToUTF16("23"), result);
}

TEST(CustomDataHelperTest, ReadMap) {
  Pickle pickle;
  PrepareTestData(&pickle);

  std::map<string16, string16> result;
  ReadCustomDataIntoMap(pickle.data(), pickle.size(), &result);

  std::map<string16, string16> expected;
  expected.insert(std::make_pair(ASCIIToUTF16("abc"), string16()));
  expected.insert(std::make_pair(ASCIIToUTF16("de"), ASCIIToUTF16("1")));
  expected.insert(std::make_pair(ASCIIToUTF16("f"), ASCIIToUTF16("23")));
  EXPECT_EQ(expected, result);
}

TEST(CustomDataHelperTest, BadReadTypes) {
  // ReadCustomDataTypes makes the additional guarantee that the contents of the
  // result vector will not change if the input is malformed.
  std::vector<string16> expected;
  expected.push_back(ASCIIToUTF16("abc"));
  expected.push_back(ASCIIToUTF16("de"));
  expected.push_back(ASCIIToUTF16("f"));

  Pickle malformed;
  malformed.WriteUInt64(1000);
  malformed.WriteString16(ASCIIToUTF16("hello"));
  malformed.WriteString16(ASCIIToUTF16("world"));
  std::vector<string16> actual(expected);
  ReadCustomDataTypes(malformed.data(), malformed.size(), &actual);
  EXPECT_EQ(expected, actual);

  Pickle malformed2;
  malformed2.WriteUInt64(1);
  malformed2.WriteString16(ASCIIToUTF16("hello"));
  std::vector<string16> actual2(expected);
  ReadCustomDataTypes(malformed2.data(), malformed2.size(), &actual2);
  EXPECT_EQ(expected, actual2);
}

TEST(CustomDataHelperTest, BadPickle) {
  string16 result_data;
  std::map<string16, string16> result_map;

  Pickle malformed;
  malformed.WriteUInt64(1000);
  malformed.WriteString16(ASCIIToUTF16("hello"));
  malformed.WriteString16(ASCIIToUTF16("world"));

  ReadCustomDataForType(malformed.data(),
                        malformed.size(),
                        ASCIIToUTF16("f"),
                        &result_data);
  ReadCustomDataIntoMap(malformed.data(), malformed.size(), &result_map);
  EXPECT_EQ(0u, result_data.size());
  EXPECT_EQ(0u, result_map.size());

  Pickle malformed2;
  malformed2.WriteUInt64(1);
  malformed2.WriteString16(ASCIIToUTF16("hello"));

  ReadCustomDataForType(malformed2.data(),
                        malformed2.size(),
                        ASCIIToUTF16("f"),
                        &result_data);
  ReadCustomDataIntoMap(malformed2.data(), malformed2.size(), &result_map);
  EXPECT_EQ(0u, result_data.size());
  EXPECT_EQ(0u, result_map.size());
}

}  // namespace

}  // namespace ui


text: require "google/apis/batch_v1"


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace IntelliTect.Coalesce.CodeGeneration.Templating
{
    public class TemplateDescriptor
    {
        public Assembly ManifestResourceAssembly { get; set; }

        public string TemplatePath { get; set; }

        public string TemplateFileName { get; set; }

        public string FullPath => Path.Combine(TemplatePath, TemplateFileName);

        public string ManifestResourceFullName =>
            ManifestResourceAssembly.GetName().Name + "." + FullPath.Replace('/', '.').Replace('\\', '.');

        public TemplateDescriptor()
        {
            ManifestResourceAssembly = Assembly.GetCallingAssembly();
        }

        public TemplateDescriptor(string templatePath, string templateFileName)
            : this(Assembly.GetCallingAssembly(), templatePath, templateFileName)
        {
        }

        public TemplateDescriptor(Assembly containingAssembly, string templatePath, string templateFileName)
        {
            ManifestResourceAssembly = containingAssembly;
            TemplatePath = templatePath;
            TemplateFileName = templateFileName;
        }

        public override string ToString() => ManifestResourceAssembly != null ? ManifestResourceFullName : FullPath;
    }
}


text:
<md-toolbar class="md-hue-2">

</md-toolbar>


text:
package us.dot.its.jpo.ode.plugin.j2735.oss;

import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.bind.DatatypeConverter;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import us.dot.its.jpo.ode.j2735.dsrc.BasicSafetyMessage;
import us.dot.its.jpo.ode.plugin.asn1.Asn1Object;
import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm;

public class OssAsn1CoderTest {

   static OssAsn1Coder coder;

   @BeforeClass
   public static void setUpBeforeClass() throws Exception {
      coder = new OssAsn1Coder();
   }

   @Ignore
   @Test
   public void testOssAsn1Coder() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_DecodeBase64() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_DecodeHex() {
      String asn_hex = "401480CA4000000000000000000000000000000000000000000000000000000000000000F800D9EFFFB7FFF00000000000000000000000000000000000000000000000000000001FE07000000000000000000000000000000000001FF0";

      System.out.println(coder.UPER_DecodeHex(asn_hex));

   }

   @Ignore
   @Test
   public void testUPER_DecodeBytes() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_DecodeBase64ToJson() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_DecodeHexToJson() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_DecodeBytesToJson() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_EncodeBase64() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_EncodeHex() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_EncodeBytes() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_EncodeBase64FromJson() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_EncodeHexfromJson() {
      fail("Not yet implemented");
   }

   @Ignore
   @Test
   public void testUPER_EncodeBytesFromJson() {
      fail("Not yet implemented");
   }

}


text:
class ChromeBrowserState;

// Wraps information to add/show to/in a context menu
@interface ElementsToAddToContextMenu : NSObject

// The title of the context menu. Can be nil.
@property(nonatomic, copy) NSString* title;

// List of elements to add to a context menu. Can be nil.
@property(nonatomic, copy) NSMutableArray<UIMenuElement*>* elements;

@end

namespace web {
class WebState;
}  // namespace web

namespace ios {
namespace provider {

// Returns the elements to add to the context menu, with their title. If no
// elements needs to be added, returns nil.
ElementsToAddToContextMenu* GetContextMenuElementsToAdd(
    ChromeBrowserState* browser_state,
    web::WebState* web_state,
    web::ContextMenuParams params,
    UIViewController* presenting_view_controller);

// Returns set of `NSTextCheckingType` representing the intent types that
// can be handled by the provider, for the given `web_state`.
NSTextCheckingType GetHandledIntentTypes(web::WebState* web_state);

// Returns `CRWContextMenuItem` items for the given `match`, for the given
// `web_state`.
NSArray<CRWContextMenuItem*>* GetContextMenuElementsToAdd(
    web::WebState* web_state,
    NSTextCheckingResult* match,
    NSString* text,
    UIViewController* presenting_view_controller);

// Returns a full set of intents of `handled_types`, located inside `text`. The
// `model_path` for the give web state should be passed in if a detection by
// model is required. (Note that some flags might still not allow it.)
absl::optional<base::Value> ExtractDataElementsFromText(
    const std::string& text,
    NSTextCheckingType handled_types,
    const base::FilePath& model_path);

}  // namespace provider
}  // namespace ios

#endif  // IOS_PUBLIC_PROVIDER_CHROME_BROWSER_CONTEXT_MENU_CONTEXT_MENU_API_H_


text:
namespace dom_distiller {
namespace android {

class DistilledPagePrefsAndroid {
 public:
  DistilledPagePrefsAndroid(JNIEnv* env,
                            jobject obj,
                            DistilledPagePrefs* distilled_page_prefs_ptr);
  virtual ~DistilledPagePrefsAndroid();
  static bool Register(JNIEnv* env);
  void SetFontFamily(JNIEnv* env, jobject obj, jint font_family);
  jint GetFontFamily(JNIEnv* env, jobject obj);
  void SetTheme(JNIEnv* env, jobject obj, jint theme);
  jint GetTheme(JNIEnv* env, jobject obj);

  void AddObserver(JNIEnv* env, jobject obj, jlong obs);
  void RemoveObserver(JNIEnv* env, jobject obj, jlong obs);

 private:
  DistilledPagePrefs* distilled_page_prefs_;

  DISALLOW_COPY_AND_ASSIGN(DistilledPagePrefsAndroid);
};

class DistilledPagePrefsObserverAndroid : public DistilledPagePrefs::Observer {
 public:
  DistilledPagePrefsObserverAndroid(JNIEnv* env, jobject obj);
  virtual ~DistilledPagePrefsObserverAndroid();

  // DistilledPagePrefs::Observer implementation.
  void OnChangeFontFamily(
      DistilledPagePrefs::FontFamily new_font_family) override;
  void OnChangeTheme(DistilledPagePrefs::Theme new_theme) override;

  virtual void DestroyObserverAndroid(JNIEnv* env, jobject obj);

 private:
  base::android::ScopedJavaGlobalRef<jobject> java_ref_;
};

}  // namespace android
}  // namespace dom_distiller

#endif  // COMPONENTS_DOM_DISTILLER_CORE_DISTILLED_PAGE_PREFS_ANDROID_H_


text:
from __future__ import unicode_literals

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=255)),
                ('slug', models.SlugField(blank=True, max_length=255, null=True)),
                ('content', models.TextField(max_length=4000)),
                ('status', models.CharField(choices=[(b'D', b'Draft'), (b'P', b'Published')], default=b'D', max_length=1)),
                ('create_date', models.DateTimeField(auto_now_add=True)),
                ('update_date', models.DateTimeField(blank=True, null=True)),
                ('create_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
                ('update_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('-create_date',),
                'verbose_name': 'Article',
                'verbose_name_plural': 'Articles',
            },
        ),
        migrations.CreateModel(
            name='ArticleComment',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('comment', models.CharField(max_length=500)),
                ('date', models.DateTimeField(auto_now_add=True)),
                ('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.Article')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('date',),
                'verbose_name': 'Article Comment',
                'verbose_name_plural': 'Article Comments',
            },
        ),
        migrations.CreateModel(
            name='Tag',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('tag', models.CharField(max_length=50)),
                ('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.Article')),
            ],
            options={
                'verbose_name': 'Tag',
                'verbose_name_plural': 'Tags',
            },
        ),
        migrations.AlterUniqueTogether(
            name='tag',
            unique_together=set([('tag', 'article')]),
        ),
        migrations.AlterIndexTogether(
            name='tag',
            index_together=set([('tag', 'article')]),
        ),
    ]


text:
import os
import platform
import struct
import sys

from setuptools import setup

python_version_major = sys.version_info.major

if python_version_major == 2:
    from urllib import urlretrieve
else:
    from urllib.request import urlretrieve

with open(os.path.join(os.path.dirname(__file__),
                       "elephant", "VERSION")) as version_file:
    version = version_file.read().strip()

with open("README.md") as f:
    long_description = f.read()
with open('requirements/requirements.txt') as fp:
    install_requires = fp.read().splitlines()
extras_require = {}
for extra in ['extras', 'docs', 'tests', 'tutorials']:
    with open('requirements/requirements-{0}.txt'.format(extra)) as fp:
        extras_require[extra] = fp.read()

def download_spade_fim():
    """
    Downloads SPADE specific PyFIM binary file.
    """
    if platform.system() == "Windows":
        fim_filename = "fim.pyd"
    else:
        # Linux
        fim_filename = "fim.so"
    spade_src_dir = os.path.join(os.path.dirname(__file__), "elephant",
                                 "spade_src")
    fim_lib_path = os.path.join(spade_src_dir, fim_filename)
    if os.path.exists(fim_lib_path):
        return

    arch_bits = struct.calcsize("P") * 8
    url_fim = "http://www.borgelt.net/bin{arch}/py{py_ver}/{filename}". \
        format(arch=arch_bits, py_ver=python_version_major,
               filename=fim_filename)
    try:
        urlretrieve(url_fim, filename=fim_lib_path)
        print("Successfully downloaded fim lib to {}".format(fim_lib_path))
    except Exception:
        print("Unable to download {url} module.".format(url=url_fim))

if len(sys.argv) > 1 and sys.argv[1].lower() != 'sdist':
    download_spade_fim()

setup(
    name="elephant",
    version=version,
    packages=['elephant', 'elephant.test'],
    include_package_data=True,

    install_requires=install_requires,
    extras_require=extras_require,

    author="Elephant authors and contributors",
    author_email="andrew.davison@unic.cnrs-gif.fr",
    description="Elephant is a package for analysis of electrophysiology"
                " data in Python",
    long_description=long_description,
    license="BSD",
    url='http://neuralensemble.org/elephant',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Scientific/Engineering']
)


text:
Files in this directory are Windows batch files generated by osbash to
configure host-only networks, produce a base disk, and build OpenStack
training-labs VMs as configured when osbash created them.

When copying these files to a Windows host, make sure to preserve the
Windows-style CR/LF newlines, or the batch scripts may fail (e.g. not
find jump labels).


text:
<?php
	require_once('../includes/admin.php');

	$admin_posts = new Posts;


text:
import base64
import functools
import urllib
import urlparse

from tornado.web import HTTPError

# taken from tornado.web.authenticated

def authenticated_plus(extra_check):
    """Decorate methods with this to require that the user be logged in."""

    def wrap(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            if not (self.current_user and extra_check(self.current_user)):
                if self.request.method in ("GET", "HEAD"):
                    url = self.get_login_url()
                    if "?" not in url:
                        if urlparse.urlsplit(url).scheme:
                            # if login url is absolute, make next absolute too
                            next_url = self.request.full_url()
                        else:
                            next_url = self.request.uri
                        url += "?" + urllib.urlencode(dict(next=next_url))
                    self.redirect(url)
                    return
                raise HTTPError(403)
            return method(self, *args, **kwargs)

        return wrapper

    return wrap

def basic_auth(checkfunc, realm="Authentication Required!"):
    """Decorate methods with this to require basic auth"""

    def wrap(method):
        def request_auth(self):
            self.set_header('WWW-Authenticate', 'Basic realm=%s' % realm)
            self.set_status(401)
            self.finish()
            return False

        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            auth = self.request.headers.get('Authorization')
            if auth is None or not auth.startswith('Basic '):
                return request_auth(self)
            auth = auth[6:]
            try:
                username, password = base64.decodestring(auth).split(':', 2)
            except:
                return request_auth(self)

            if checkfunc(username, password):
                self.request.basic_auth = (username, password)
                return method(self, *args, **kwargs)
            else:
                return request_auth(self)

        return wrapper

    return wrap


text:
package edu.usu.sdl.opencatalog.service;

/**
 *  Handles all user business logic
 * @author dshurtleff
 */
public class UserServiceImpl
{

}


text:
<readable><title>3334537556_a2cf4e9b9a</title><content>
A group of people on skis with two dogs .
A man dressed in a horned hat poses for a picture on skis with three other people and a dog .
Four people holding each others shoulders with a brown dog in front of them , standing on snow .
People dressed in costumes are on skis .
People , some dressed in costumes , and dogs on a snowy mountain .
</content></readable>


text:
using namespace Ogre;

SystemTextureLoader::SystemTextureLoader(HWND window)
	:ManualResourceLoader(),
	m_WindowHandle(window)
{
}

SystemTextureLoader::~SystemTextureLoader(void)
{
}

void SystemTextureLoader::prepareResource ( Resource *resource)
{
	if(D3D9Texture *tex = dynamic_cast<D3D9Texture*>(resource))
	{}
}

typedef BOOL (WINAPI *DwmGetDxSharedSurface_td) (
	__in HWND hwnd,
	__out_opt UINT32* p1,
	__out_opt UINT64* p2,
	__out_opt UINT32* p3,
	__out_opt UINT32* p4,
	__out_opt UINT64* p5 );

DwmGetDxSharedSurface_td DwmGetSharedSurface = NULL;

HANDLE GetDWMSharedHandle(HWND hwnd)
{
    if (!DwmGetSharedSurface)
	{
        DwmGetSharedSurface = ((DwmGetDxSharedSurface_td)GetProcAddress(GetModuleHandle(TEXT("USER32")), "DwmGetDxSharedSurface"));
	}

    UINT32 hwndInt = (UINT32)hwnd;
    UINT64 p2 = -1,p5 = -1;
    UINT32 p1 = -1,p3 = -1,p4 = -1;

    DwmGetSharedSurface(hwnd,&p1,&p2,&p3,&p4,&p5);

    return (HANDLE)p1;
}

void SystemTextureLoader::loadResource ( Resource *resource)
{
	if(D3D11Texture *tex = dynamic_cast<D3D11Texture*>(resource))
	{
		//comment this out if building with standard ogre
		HANDLE texHandle = GetDWMSharedHandle( m_WindowHandle);
		tex->LoadSharedResource(texHandle);
	}
}


text:
<?php
/**
 * QuotaServiceQuotaTest
 *
 * PHP version 5
 *
 * @category Class
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * quotaService/settings.proto
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: version not set
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.14
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the model.
 */

namespace Alfaview;

use PHPUnit\Framework\TestCase;

/**
 * QuotaServiceQuotaTest Class Doc Comment
 *
 * @category    Class
 * @description QuotaServiceQuota
 * @package     Alfaview
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class QuotaServiceQuotaTest extends TestCase
{

    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass(): void
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp(): void
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown(): void
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass(): void
    {
    }

    /**
     * Test "QuotaServiceQuota"
     */
    public function testQuotaServiceQuota()
    {
    }

    /**
     * Test attribute "name"
     */
    public function testPropertyName()
    {
    }

    /**
     * Test attribute "resource"
     */
    public function testPropertyResource()
    {
    }

    /**
     * Test attribute "start_time"
     */
    public function testPropertyStartTime()
    {
    }

    /**
     * Test attribute "end_time"
     */
    public function testPropertyEndTime()
    {
    }

    /**
     * Test attribute "limit"
     */
    public function testPropertyLimit()
    {
    }

    /**
     * Test attribute "timeframe"
     */
    public function testPropertyTimeframe()
    {
    }

    /**
     * Test attribute "metadata"
     */
    public function testPropertyMetadata()
    {
    }

    /**
     * Test attribute "limits"
     */
    public function testPropertyLimits()
    {
    }

    /**
     * Test attribute "remove"
     */
    public function testPropertyRemove()
    {
    }
}