text:
from __future__ import division

import numpy as np
from scipy.stats import multivariate_normal

from pgmpy.factors.distributions import BaseDistribution

class GaussianDistribution(BaseDistribution):
    """
    In its most common representation, a multivariate Gaussian distribution
    over X1, X2, ..., Xn is characterized by an n-dimensional mean vector μ,
    and a symmetric n x n covariance matrix Σ.

    This is the base class for its representation.
    """
    def __init__(self, variables, mean, cov):
        """
        Parameters
        ----------
        variables: iterable of any hashable python object
            The variables for which the distribution is defined.

        mean: list, array-like
            1-D array of size n where n is the number of variables.

        cov: n x n, 2-D array like
            n x n dimensional matrix where n is the number of variables.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis = GD(variables=['x1', 'x2', 'x3'],
        ...          mean=np.array([1, -3, 4]),
        ...          cov=np.array([[4, 2, -2],
        ...                        [2, 5, -5],
        ...                        [-2, -5, 8]]))
        >>> dis.variables
        ['x1', 'x2', 'x3']
        >>> dis.mean
        array([[ 1],
               [-3],
               [4]]))
        >>> dis.cov
        array([[4, 2, -2],
               [2, 5, -5],
               [-2, -5, 8]])
        >>> dis.assignment([0, 0, 0])
        0.0014805631279234139
        """
        no_of_var = len(variables)

        self.variables = variables
        self.mean = np.asarray(np.reshape(mean, (no_of_var, 1)), dtype=float)
        self.covariance = np.asarray(cov, dtype=float)
        self._precision_matrix = None

        if len(mean) != no_of_var:
            raise ValueError("Length of mean_vector must be equal to the",
                             "number of variables.")

        if self.covariance.shape != (no_of_var, no_of_var):
            raise ValueError("The Covariance matrix should be a square matrix",
                             " with order equal to the number of variables. ",
                             "Got: {got_shape}, Expected: {exp_shape}".format
                             (got_shape=self.covariance.shape,
                              exp_shape=(no_of_var, no_of_var)))

    @property
    def pdf(self):
        """
        Returns the probability density function(pdf).

        Returns
        -------
        function: The probability density function of the distribution.

        Examples
        --------
        >>> from pgmpy.factors.distributions import GaussianDistribution
        >>> dist = GD(variables=['x1', 'x2', 'x3'],
        ...           mean=[1, -3, 4],
        ...           cov=[[4, 2, -2],
        ...                [2, 5, -5],
        ...                [-2, -5, 8]])
        >>> dist.pdf
        <function pgmpy.factors.distributions.GaussianDistribution.GaussianDistribution.pdf.<locals>.<lambda>>
        >>> dist.pdf([0, 0, 0])
        0.0014805631279234139
        """
        return lambda *args: multivariate_normal.pdf(
            args, self.mean.reshape(1, len(self.variables))[0], self.covariance)

    def assignment(self, *x):
        """
        Returns the probability value of the PDF at the given parameter values.

        Parameters
        ----------
        *x: int, float
            The point at which the value of the pdf needs to be computed. The
            number of values passed should be equal to the number of variables
            in the distribution.

        Returns
        -------
        float: float
            The probability value at the point.

        Examples
        --------
        >>> from pgmpy.factors.distributions import GaussianDistribution
        >>> dist = GaussianDistribution(variables=['x1', 'x2'],
        ...                             mean=[0, 0],
        ...                             cov=[[1, 0],
                                             [0, 1]])
        >>> dist.assignment(0, 0)
        0.15915494309189535
        """
        return self.pdf(*x)

    @property
    def precision_matrix(self):
        """
        Returns the precision matrix of the distribution.

        Precision is defined as the inverse of the variance. This method returns
        the inverse matrix of the covariance.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis = GD(variables=['x1', 'x2', 'x3'],
        ...          mean=[1, -3, 4],
        ...          cov=[[4, 2, -2],
        ...               [2, 5, -5],
        ...               [-2, -5, 8]]))
        >>> dis.precision_matrix
        array([[ 0.3125    , -0.125     ,  0.        ],
               [-0.125     ,  0.58333333,  0.33333333],
               [ 0.        ,  0.33333333,  0.33333333]])
        """
        if self._precision_matrix is None:
            self._precision_matrix = np.linalg.inv(self.covariance)
        return self._precision_matrix

    def marginalize(self, variables, inplace=True):
        """
        Modifies the distribution with marginalized values.

        Parameters
        ----------
        variables: iterator over any hashable object.
                List of variables over which marginalization is to be done.

        inplace: boolean
                If inplace=True it will modify the distribution itself,
                else would return a new distribution.

        Returns
        -------
        GaussianDistribution or None :
                if inplace=True (default) returns None
                if inplace=False return a new GaussianDistribution instance

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis = GD(variables=['x1', 'x2', 'x3'],
        ...          mean=[1, -3, 4],
        ...          cov=[[4, 2, -2],
        ...               [2, 5, -5],
        ...               [-2, -5, 8]]))
        >>> dis.variables
        ['x1', 'x2', 'x3']
        >>> dis.mean
        array([[ 1],
               [-3],
               [ 4]])
        >>> dis.covariance
        array([[ 4,  2, -2],
               [ 2,  5, -5],
               [-2, -5,  8]])

        >>> dis.marginalize(['x3'])
        dis.variables
        ['x1', 'x2']
        >>> dis.mean
        array([[ 1.],
               [-3.]]))
        >>> dis.covariance
        array([[4., 2.],
               [2., 5.]])
        """
        if not isinstance(variables, list):
            raise TypeError("variables: Expected type list or array-like,"
                            "got type {var_type}".format(
                                var_type=type(variables)))

        phi = self if inplace else self.copy()

        index_to_keep = [self.variables.index(var) for var in self.variables
                         if var not in variables]

        phi.variables = [phi.variables[index] for index in index_to_keep]
        phi.mean = phi.mean[index_to_keep]
        phi.covariance = phi.covariance[np.ix_(index_to_keep, index_to_keep)]
        phi._precision_matrix = None

        if not inplace:
            return phi

    def reduce(self, values, inplace=True):
        """
        Reduces the distribution to the context of the given variable values.

        The formula for the obtained conditional distribution is given by -

        For,
        .. math:: N(X_j | X_i = x_i) ~ N(mu_{j.i} ; sig_{j.i})

        where,
        .. math:: mu_{j.i} = mu_j + sig_{j, i} * {sig_{i, i}^{-1}} * (x_i - mu_i)
        .. math:: sig_{j.i} = sig_{j, j} - sig_{j, i} * {sig_{i, i}^{-1}} * sig_{i, j}

        Parameters
        ----------
        values: list, array-like
            A list of tuples of the form (variable_name, variable_value).

        inplace: boolean
            If inplace=True it will modify the factor itself, else would return
            a new ContinuosFactor object.

        Returns
        -------
        GaussianDistribution or None:
                if inplace=True (default) returns None
                if inplace=False returns a new GaussianDistribution instance.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis = GD(variables=['x1', 'x2', 'x3'],
        ...             mean=[1, -3, 4],
        ...             cov=[[4, 2, -2],
        ...                  [2, 5, -5],
        ...                  [-2, -5, 8]])
        >>> dis.variables
        ['x1', 'x2', 'x3']
        >>> dis.mean
        array([[ 1.],
               [-3.],
               [ 4.]])
        >>> dis.covariance
        array([[ 4.,  2., -2.],
               [ 2.,  5., -5.],
               [-2., -5.,  8.]])

        >>> dis.reduce([('x1', 7)])
        >>> dis.variables
        ['x2', 'x3']
        >>> dis.mean
        array([[ 0.],
               [ 1.]])
        >>> dis.covariance
        array([[ 4., -4.],
               [-4.,  7.]])

        """
        if not isinstance(values, list):
            raise TypeError("values: Expected type list or array-like, ",
                            "got type {var_type}".format(
                                var_type=type(values)))

        phi = self if inplace else self.copy()

        var_to_reduce = [var for var, value in values]

        # index_to_keep -> j vector
        index_to_keep = [self.variables.index(var) for var in self.variables
                         if var not in var_to_reduce]
        # index_to_reduce -> i vector
        index_to_reduce = [self.variables.index(var) for var in var_to_reduce]

        mu_j = self.mean[index_to_keep]
        mu_i = self.mean[index_to_reduce]
        x_i = np.array([value for var, value in values]).reshape(len(index_to_reduce), 1)

        sig_i_j = self.covariance[np.ix_(index_to_reduce, index_to_keep)]
        sig_j_i = self.covariance[np.ix_(index_to_keep, index_to_reduce)]
        sig_i_i_inv = np.linalg.inv(self.covariance[np.ix_(index_to_reduce, index_to_reduce)])
        sig_j_j = self.covariance[np.ix_(index_to_keep, index_to_keep)]

        phi.variables = [self.variables[index] for index in index_to_keep]
        phi.mean = mu_j + np.dot(np.dot(sig_j_i, sig_i_i_inv), x_i - mu_i)
        phi.covariance = sig_j_j - np.dot(np.dot(sig_j_i, sig_i_i_inv), sig_i_j)
        phi._precision_matrix = None

        if not inplace:
            return phi

    def normalize(self, inplace=True):
        """
        Normalizes the distribution. In case of a Gaussian Distribution the
        distribution is always normalized, therefore this method doesn't do
        anything and has been implemented only for a consistent API across
        distributions.
        """
        phi = self if inplace else self.copy()

        # The pdf of a Joint Gaussian distrinution is always
        # normalized. Hence, no changes.
        if not inplace:
            return phi

    def copy(self):
        """
        Return a copy of the distribution.

        Returns
        -------
        GaussianDistribution: copy of the distribution

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> gauss_dis = GD(variables=['x1', 'x2', 'x3'],
        ...                mean=[1, -3, 4],
        ...                cov=[[4, 2, -2],
        ...                     [2, 5, -5],
        ...                     [-2, -5, 8]])
        >>> copy_dis = gauss_dis.copy()
        >>> copy_dis.variables
        ['x1', 'x2', 'x3']
        >>> copy_dis.mean
        array([[ 1],
                [-3],
                [ 4]])
        >>> copy_dis.covariance
        array([[ 4,  2, -2],
                [ 2,  5, -5],
                [-2, -5,  8]])
        >>> copy_dis.precision_matrix
        array([[ 0.3125    , -0.125     ,  0.        ],
                [-0.125     ,  0.58333333,  0.33333333],
                [ 0.        ,  0.33333333,  0.33333333]])
        """
        copy_distribution = GaussianDistribution(variables=self.variables,
                                                 mean=self.mean.copy(),
                                                 cov=self.covariance.copy())
        if self._precision_matrix is not None:
            copy_distribution._precision_matrix = self._precision_matrix.copy()

        return copy_distribution

    def to_canonical_factor(self):
        u"""
        Returns an equivalent CanonicalDistribution object.

        The formulas for calculating the cannonical factor parameters
        for N(μ; Σ) = C(K; h; g) are as follows -

        K = sigma^(-1)
        h = sigma^(-1) * mu
        g = -(0.5) * mu.T * sigma^(-1) * mu -
            log((2*pi)^(n/2) * det(sigma)^(0.5))

        where,
        K,h,g are the canonical factor parameters
        sigma is the covariance_matrix of the distribution,
        mu is the mean_vector of the distribution,
        mu.T is the transpose of the matrix mu,
        and det(sigma) is the determinant of the matrix sigma.

        Example
        -------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis = GD(variables=['x1', 'x2', 'x3'],
        ...          mean=[1, -3, 4],
        ...          cov=[[4, 2, -2],
        ...               [2, 5, -5],
        ...               [-2, -5, 8]])
        >>> phi = dis.to_canonical_factor()
        >>> phi.variables
        ['x1', 'x2', 'x3']
        >>> phi.K
        array([[0.3125, -0.125, 0.],
               [-0.125, 0.5833, 0.333],
               [     0., 0.333, 0.333]])
        >>> phi.h
        array([[  0.6875],
               [-0.54166],
               [ 0.33333]]))
        >>> phi.g
        -6.51533
        """
        from pgmpy.factors.continuous import CanonicalDistribution

        mu = self.mean
        sigma = self.covariance

        K = self.precision_matrix

        h = np.dot(K, mu)

        g = -(0.5) * np.dot(mu.T, h)[0, 0] - np.log(
            np.power(2 * np.pi, len(self.variables)/2) *
            np.power(abs(np.linalg.det(sigma)), 0.5))

        return CanonicalDistribution(self.variables, K, h, g)

    def _operate(self, other, operation, inplace=True):
        """
        Gives the CanonicalDistribution operation (product or divide) with
        the other factor.

        Parameters
        ----------
        other: CanonicalDistribution
            The CanonicalDistribution to be multiplied.

        operation: String
            'product' for multiplication operation and
            'divide' for division operation.

        Returns
        -------
        CanonicalDistribution or None:
                        if inplace=True (default) returns None
                        if inplace=False returns a new CanonicalDistribution instance.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis1 = GD(['x1', 'x2', 'x3'], np.array([[1], [-3], [4]]),
        ...             np.array([[4, 2, -2], [2, 5, -5], [-2, -5, 8]]))
        >>> dis2 = GD(['x3', 'x4'], [1, 2], [[2, 3], [5, 6]])
        >>> dis3 = dis1 * dis2
        >>> dis3.covariance
        array([[ 3.6,  1. , -0.4, -0.6],
               [ 1. ,  2.5, -1. , -1.5],
               [-0.4, -1. ,  1.6,  2.4],
               [-1. , -2.5,  4. ,  4.5]])
        >>> dis3.mean
        array([[ 1.6],
               [-1.5],
               [ 1.6],
               [ 3.5]])
        """
        phi = self.to_canonical_factor()._operate(
            other.to_canonical_factor(), operation, inplace=False).to_joint_gaussian()

        if not inplace:
            return phi

    def product(self, other, inplace=True):
        """
        TODO: Make it work when using `*` instead of product.

        Returns the product of two gaussian distributions.

        Parameters
        ----------
        other: GaussianDistribution
            The GaussianDistribution to be multiplied.

        inplace: boolean
            If True, modifies the distribution itself, otherwise returns a new
            GaussianDistribution object.

        Returns
        -------
        CanonicalDistribution or None:
                    if inplace=True (default) returns None.
                    if inplace=False returns a new CanonicalDistribution instance.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis1 = GD(['x1', 'x2', 'x3'], np.array([[1], [-3], [4]]),
        ...            np.array([[4, 2, -2], [2, 5, -5], [-2, -5, 8]]))
        >>> dis2 = GD(['x3', 'x4'], [1, 2], [[2, 3], [5, 6]])
        >>> dis3 = dis1.product(dis2, inplace=False)
        >>> dis3.covariance
        array([[ 3.6,  1. , -0.4, -0.6],
               [ 1. ,  2.5, -1. , -1.5],
               [-0.4, -1. ,  1.6,  2.4],
               [-1. , -2.5,  4. ,  4.5]])
        >>> dis3.mean
        array([[ 1.6],
               [-1.5],
               [ 1.6],
               [ 3.5]])
        """
        return self._operate(other, operation='product', inplace=inplace)

    def divide(self, other, inplace=True):
        """
        Returns the division of two gaussian distributions.

        Parameters
        ----------
        other: GaussianDistribution
            The GaussianDistribution to be divided.

        inplace: boolean
            If True, modifies the distribution itself, otherwise returns a new
            GaussianDistribution object.

        Returns
        -------
        CanonicalDistribution or None:
                    if inplace=True (default) returns None.
                    if inplace=False returns a new CanonicalDistribution instance.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors.distributions import GaussianDistribution as GD
        >>> dis1 = GD(['x1', 'x2', 'x3'], np.array([[1], [-3], [4]]),
        ...            np.array([[4, 2, -2], [2, 5, -5], [-2, -5, 8]]))
        >>> dis2 = GD(['x3', 'x4'], [1, 2], [[2, 3], [5, 6]])
        >>> dis3 = dis1.divide(dis2, inplace=False)
        >>> dis3.covariance
        array([[ 3.6,  1. , -0.4, -0.6],
               [ 1. ,  2.5, -1. , -1.5],
               [-0.4, -1. ,  1.6,  2.4],
               [-1. , -2.5,  4. ,  4.5]])
        >>> dis3.mean
        array([[ 1.6],
               [-1.5],
               [ 1.6],
               [ 3.5]])
        """
        return self._operate(other, operation='divide', inplace=inplace)

    def __repr__(self):
        return "GaussianDistribution representing N({var}) at {address}".format(
            var=self.variables, address=hex(id(self)))

    def __mul__(self, other):
        return self.product(other, inplace=False)

    def __rmul__(self, other):
        return self.__mul__(other)

    def __truediv__(self, other):
        return self.divide(other, inplace=False)

    __div__ = __truediv__

    def __eq__(self, other):
        if not (isinstance(self, GaussianDistribution) and isinstance(self, GaussianDistribution)):
            return False

        elif set(self.scope()) != set(other.scope()):
            return False

        else:
            # Computing transform_index to be able to easily have variables in same order.
            transform_index = [other.index(var) for var in self.variables]

            if not np.allclose(self.mean, other.mean[transform_index]):
                return False
            else:
                mid_cov = other.covariance[transform_index, :]
                transform_cov = mid_cov[:, transform_index]
                if not np.allclose(self.covariance, transform_cov):
                    return False
        return True


text:
define( [], function () {

    'use strict';

    var sprintf = function ( string, args ) {
        if ( !string || !args ) {
            return '';
        }

        var arg;

        for ( var index in args ) {
            arg = args[ index ];

            if ( arg === undefined )
                continue;

            if ( arg.getVariable ) {
                arg = arg.getVariable();
            }
            string = string.replace( '%s', arg );
        }
        return string;
    };

    var checkVariableType = function ( vars, optionalPrefix ) {

        var inputs = vars;
        var varsList = [];
        var prefix = optionalPrefix;
        if ( optionalPrefix === undefined ) {
            prefix = '';
        }

        for ( var i = 0, l = inputs.length; i < l; i++ ) {

            var variable = inputs[ i ];
            var output;

            if ( variable === undefined ) {
                output = 'undefined';
            } else if ( typeof variable === 'string' ) {
                output = variable;
            } else if ( variable.getType ) {
                output = variable.getType() + ' ' + variable.getVariable();
            } else {
                output = variable.getVariable();
            }

            varsList.push( prefix + output );
        }

        return varsList;

    };

    // call glsl function
    // generate a string with output = funcName ( inputs )
    // useful when debuging to print inputs / outputs
    // TODO check type of arguments with regexp in glsl
    // shader function regex
    // [\r\n]\s[(vec4)|(vec3)|(vec2)|(float)|(bool)|(int)].*\(.*[.|\r\n]*\).*[\r\n]*{
    // doesn't handle multiline
    // then split(',')
    // then substring (out,in)
    // then type matching
    // (works by hand here.)
    // for instance, gather types from input and compare themt to glsl decl
    // var inputTypes = [
    //             'vec4',
    //             'vec4',
    //             'sampler2D',
    //             'vec4',
    //             'vec4',
    //             'vec3',
    //             'float',
    //             'vec3',
    //             'float',
    //             'float',
    //             'float',
    //             'float',
    //             'float'
    //         ];
    //         console.assert( inputs.length === inputTypes.length );
    //         var i = inputs.length;
    //         while ( i-- ) {
    //             console.assert( inputs[ i ]._type === inputTypes[ i ], inputs[ i ]._prefix );
    //         }
    var callFunction = function ( funcName, output, inputs ) {

        var osgShader = require( 'osgShader/osgShader' );

        var debug = [];
        var callString = '';

        // debug
        if ( osgShader.debugShaderNode ) {
            debug.push( '\n// output' );
            Array.prototype.push.apply( debug, checkVariableType( [ output ], '// ' ) );
        }

        if ( output ) {
            if ( output.getVariable )
                output = output.getVariable();
            callString = output + ' = ';
        }

        callString = callString + funcName + '( ';

        if ( inputs && inputs.length > 0 ) {

            // debug
            if ( osgShader.debugShaderNode ) {
                debug.push( '// inputs' );
                Array.prototype.push.apply( debug, checkVariableType( inputs, '// ' ) );
            }

            for ( var i = 0, l = inputs.length; i < l; i++ ) {

                // check if it's a variable and not a constant
                if ( inputs[ i ].getVariable )
                    callString += inputs[ i ].getVariable();
                else
                    callString += inputs[ i ];

                if ( i !== l - 1 )
                    callString += ', ';
            }
        }

        callString += ' );\n';

        if ( osgShader.debugShaderNode )
            return debug.join( '\n' ) + '\n' + callString;

        return callString;
    };

    return {
        callFunction: callFunction,
        checkVariableType: checkVariableType,
        sprintf: sprintf
    };

} );

redpajama_set_name: RedPajamaGithub


text:
Exemple from  `tests/scala`

```HTML
docker run -i williamyeh/scala scala
```

1 load from  Docker Hub the image williamyeh/scala
(Docker Hub is a public registry hosting images)
{% fragment %}
2 Launch the image as a container with :
{% fragment %}
 			* Mapping interactive mode -i
{% fragment %}
 			* Execute the command `scala`
{% fragment %}

Note:

2 Launch the image as a container with :
	* Mapping volume (here a file) from host to container,   -v helloworld.sh to /tmp/
	* Execute the command `scala /tmp/helloworld.sh`


text:
<?php
namespace Procure\Domain\Event\Ap;

use Application\Application\Event\AbstractEvent;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class ApRowRemoved extends AbstractEvent{

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Sharpmon
{
    [Serializable]            //Indicate that this class thus object is serializable (used for saving the game)
    public class Item : Effect       //The Item class inherit from the Effect class and also from the ISerializable Interface (so do all the other classes).
    {
        //FIELDS
        [JsonProperty]
        private int HealAmount;         //Variable used to know the healing effectiveness of the object.
        [JsonProperty]
        private int LevelGiven;         //Variable used to know the level empowerement of the object.
        [JsonProperty]
        private int MaxHpBoost;         //Variabe used to know the MaxHp's stat reinforcement of the target.

        //PROPERTIES
        public int GetPrice()
        {
            return this.Price;
        }
        public int GetSellPrice()
        {
            return this.SellPrice;
        }
        public string GetDescription()
        {
            return this.Description;
        }

        //CONSTRUCTOR
        [JsonConstructor]
        public Item(string name, int price, string description, int healAmount, int power = 0, int defense = 0, int dodge = 0, int accucary = 0, int speed = 0, int levelGiven = 0, int maxHpBoost = 0)
        {
            this.Name = name;
            this.Price = price;
            this.SellPrice = this.Price/2;
            this.Description = description;
            this.HealAmount = healAmount;
            this.Power = power;
            this.Defense = defense;
            this.Dodge = dodge;
            this.Accucary = accucary;
            this.Speed = speed;
            this.LevelGiven = levelGiven;
            this.MaxHpBoost = maxHpBoost;
        }

        //METHODS
        /// <summary>
        /// Method to say that the current item is used on a said sharpmon.
        /// If it does someting, it returns true (it returns false when a potion is used a full life sharpmon).
        /// </summary>
        /// <param name="target"></param>
        /// <param name="ennemy"></param>
        public bool Use(Sharpmon target, Sharpmon ennemy)
        {
            if (this.HealAmount > 0 && target.CurrentHp == target.MaxHp)
            {
                Console.WriteLine("This Sharpmon is already full life. Use another item:");
                return false;
            }
            target.CurrentHp += this.HealAmount;
            if(target.CurrentHp > target.MaxHp)
                target.CurrentHp = target.MaxHp;
            target.BasePower += this.Power;
            target.BaseDefense += this.Defense;
            target.BaseDodge += this.Dodge;
            target.BaseAccucary += this.Accucary;
            target.BaseSpeed += this.Speed;
            target.MaxHp += this.MaxHpBoost;
            target.CurrentHp += this.MaxHpBoost;
            if (this.LevelGiven > 0)
                target.OnLevelUp();
            return true;
        }

        /// <summary>
        /// Method using LINQ to get an attack by its name.
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static Item GetItem(string Name, List<Item> items)
        {
            return items.FirstOrDefault(item => item.GetName() == Name);
        }

        /// <summary>
        /// Method to get how much of a specific item is in a list
        /// (used for example to know how much potions are the inventory for a better user experience).
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static int GetNumberOfItem(string Name, List<Item> items)
        {
            return items.Count(item => item.Name == Name);
        }

        /// <summary>
        /// Method which return a true if a given list contains a specific item given by its name.
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static bool ContainItem(string Name, List<Item> items)
        {
            return items.Contains(GetItem(Name, items));
        }
    }
}


text:
package main
import (
        "flag"
        "net/http"

        "github.com/golang/glog"
        "golang.org/x/net/context"
        "github.com/grpc-ecosystem/grpc-gateway/runtime"
        "google.golang.org/grpc"
        gw "{{package.name}}"
)

var (
        server = flag.String("service_endpint", "localhost:8080", "grpc service endpoint of {{package.name}}")
        port = flag.String("port", ":9090", "The port on which to run this proxy")
)

func run() error {
        ctx := context.Background()
        ctx, cancel := context.WithCancel(ctx)
        defer cancel()

        mux := runtime.NewServeMux()
        opts := []grpc.DialOption{grpc.WithInsecure()}
{% for service_name in service_names %}
        glog.Info("{{package.name.title()}} - Registering service {{service_name}}")
        if err := gw.Register{{service_name}}HandlerFromEndpoint(ctx, mux, *server, opts); err != nil {
                glog.Warning("Error registering service {{service_name}}")
                return err
        }
{% endfor %}
        glog.Info("{{package.name.title()}} grpc proxy server will proxy requests to ", *server)
        glog.Info("{{package.name.title()}} grpc proxy server starting to listen on ", *port)
        http.ListenAndServe(*port, mux)
        return nil
}

func main() {
        flag.Parse()
        defer glog.Flush()

        if err := run(); err != nil {
                glog.Fatal(err)
        }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <gradient
        android:angle="270"
        android:endColor="@color/old_glory_red"
        android:startColor="@color/old_glory_red_alt" />

</shape>


text:
from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.template.context import Context
from django.template.loader import get_template
from pynliner import Pynliner
from celery.contrib.methods import task_method
from celery import current_app as app
from urlparse import urljoin

import sys
import traceback
import time
import send_mail as mailer

class VaultierMailer(object):
    """
    Vaultier base mailer class. Feel free to override me

    Base usage:
    >>> mailer = VaultierMailer(template='mailer/my_template',
    >>>                         subject='[Vaultier] New folder')
    >>> mailer.add_to('john@doe.org').send()

    Note: pass template name without extension. Plaintext and html
    version should exists side by side
    """

    _to = []
    from_email = None
    subject = None
    template_style = 'mailer/layout.css'
    object = None
    _template = 'mailer/layout'

    def __init__(self, **kwargs):
        self._to = kwargs.get('to', [])
        self.from_email = kwargs.get('from_email',
                                     settings.VAULTIER.get('from_email'))
        self.subject = kwargs.get('subject', self.subject)
        self._template = kwargs.get('template', self._template)
        self.template_style = kwargs.get('template_style', self.template_style)
        self.object = kwargs.get('object')

    @property
    def to(self):
        """
        Return list of email recipients
        """
        try:
            return iter(self._to)
        except TypeError:
            return [self._to]

    def add_to(self, value):
        """
        Add recipient
        """
        if value not in self._to:
            self._to.append(value)
        return self

    @property
    def template_plain(self):
        """
        Return Template instance for plaintext mail

        :return: Template
        """

        return get_template("{}.txt".format(self._template))

    @property
    def template_html(self):
        """
        Return Template instance for plaintext mail

        :return: Template
        """
        return get_template("{}.html".format(self._template))

    def send(self, **kwargs):
        """
        Send an email, base on the template and context given to the address
        in recipients.

        :return: None
        """

        not_used = kwargs.pop('async', True)

        self._send(**kwargs)

    def format_subject(self):
        """
        Hook to format, compile or whatever with subject before send

        :return: string
        """
        return self.subject

    @app.task(filter=task_method)
    def _send(self, **kwargs):
        """
        Actually send email in background

        :return:
        """

        ## Old code that doesn't work
        # context = self._build_context(**kwargs)
        # plain, html = self._render(context)
        # msg = EmailMultiAlternatives(
        #     from_email=self.from_email,
        #     to=self.to,
        #     body=plain,
        #     subject=self.format_subject()
        # )
        #
        # msg.attach_alternative(html, 'text/html')
        # msg.send()

        # Write email to file in case it doesn't go through
        from_email = self.from_email
        to = list(self.to)
        subject = self.format_subject()
        context = self._build_context(**kwargs)
        plain, html = self._render(context)

        f = open("/vaultier_data/email.log", "a")
        f.write("date:\t\t" + time.strftime("%d/%m/%Y %H:%M:%S") + "\nfrom:\t\t" + str(from_email) + "\nto:\t\t" + ", ".join(to) + "\nsubject:\t" + str(subject) + "\n\n")
        f.write(plain)
        f.write("\n-------------------------------------------------------------------------\n")
        f.close()

        # Attempt sending email through custom script
        try:
            mailer.send_mail(from_email, to, subject, plain, html)
        except:
            fe = open("/vaultier_data/email_errors.log", "a")
            fe.write(time.strftime("%d/%m/%Y %H:%M:%S") + "\n\n" + str(traceback.format_exc()))
            fe.write("\n-------------------------------------------------------------------------\n")
            fe.close()

    def _render(self, context):
        """
        Renders the plain and html versions of a template.
        Return both in a tuple, where the first element is the plain text
        version and the second element is the html version
        :return: (str, str,)
        """
        if not context:
            context = Context({})

        plain = self.template_plain.render(context)
        html = self.template_html.render(context)
        css = get_template(self.template_style).render(Context({}))

        p = Pynliner()
        html = p.from_string(html).with_cssString(css).run()

        return plain, html

    def _build_context(self, **kwargs):
        """
        Must return an instance of django.template.context.Context
        with the template variables set for each implementation
        :return: None
        """
        # adding full url to logo
        kwargs.update({
            'logo_url': "{}vaultier/images/logo-email.png".format(
                urljoin(settings.SITE_URL, settings.STATIC_URL))
        })
        return Context(kwargs)


text:
<?php

namespace Tzsk\Payu\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Tzsk\Payu\Models\PayuTransaction;

class VerifyTransaction implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public PayuTransaction $transaction;

    public function __construct(PayuTransaction $transaction)
    {
        $this->transaction = $transaction;
    }

    public function handle()
    {
        $this->transaction->verify();
    }
}


text:
<component name="libraryTable">
  <library name="Maven: org.eclipse.persistence:org.eclipse.persistence.core:2.6.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/eclipse/persistence/org.eclipse.persistence.core/2.6.1/org.eclipse.persistence.core-2.6.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/eclipse/persistence/org.eclipse.persistence.core/2.6.1/org.eclipse.persistence.core-2.6.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/eclipse/persistence/org.eclipse.persistence.core/2.6.1/org.eclipse.persistence.core-2.6.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
@interface LZPVerticalButton : UIButton

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="@dimen/key_width"
    android:keyHeight="@dimen/key_height"
    android:horizontalGap="2px"
    android:verticalGap="2px"
    >

    <Row></Row>
    <Row></Row>
    <Row></Row>
    <Row>
        <Key android:codes="-5"  android:keyWidth="42px" android:keyIcon="@drawable/blackkey_del" android:iconPreview="@drawable/icon_del"
        	 android:isRepeatable="true" android:keyEdgeFlags="left"/>
        <Key android:codes="113" android:keyLabel="q"/>
        <Key android:codes="119" android:keyLabel="w"/>
        <Key android:codes="101" android:keyLabel="e" android:popupKeyboard="@xml/popup" android:popupCharacters="èéêëęē€" />
        <Key android:codes="114" android:keyLabel="r"/>
        <Key android:codes="116" android:keyLabel="t" android:horizontalGap = "300px"/>
        <Key android:codes="121" android:keyLabel="y" android:popupKeyboard="@xml/popup" android:popupCharacters="ýÿ" />
        <Key android:codes="117" android:keyLabel="u" android:popupKeyboard="@xml/popup" android:popupCharacters="ùúûüŭűū" />
        <Key android:codes="105" android:keyLabel="i" android:popupKeyboard="@xml/popup" android:popupCharacters="ìíîïłī" />
        <Key android:codes="111" android:keyLabel="o" android:popupKeyboard="@xml/popup" android:popupCharacters="òóôõöøőœō" />
        <Key android:codes="112" android:keyLabel="p"/>
        <Key android:codes="-5"  android:keyWidth="42px"
            android:keyIcon="@drawable/blackkey_del" android:iconPreview="@drawable/icon_del"
        	android:isRepeatable="true" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
		<Key android:codes="0"  android:keyWidth="55px" android:keyIcon="@drawable/blackkey_photo" android:iconPreview="@drawable/icon_photo"
                android:keyEdgeFlags="left"/>
        <Key android:codes="97" android:keyLabel="a" android:popupKeyboard="@xml/popup" android:popupCharacters="àáâãäåæą" />
        <Key android:codes="115" android:keyLabel="s" android:popupKeyboard="@xml/popup" android:popupCharacters="§ßśŝš" />
        <Key android:codes="100" android:keyLabel="d" android:popupKeyboard="@xml/popup" android:popupCharacters="đ" />
        <Key android:codes="102" android:keyLabel="f"/>
        <Key android:codes="103" android:keyLabel="g" android:popupKeyboard="@xml/popup" android:popupCharacters="ĝ" />
        <Key android:codes="104" android:keyLabel="h"  android:popupKeyboard="@xml/popup" android:popupCharacters="ĥ" android:horizontalGap = "250px"/>
        <Key android:codes="106" android:keyLabel="j" android:popupKeyboard="@xml/popup" android:popupCharacters="ĵ" />
        <Key android:codes="107" android:keyLabel="k"/>
        <Key android:codes="108" android:keyLabel="l"/>
        <Key android:codes="39" android:keyLabel="\'"/>
        <Key android:codes="0"  android:keyWidth="55px"
            android:keyIcon ="@drawable/blackkey_video"  android:iconPreview="@drawable/icon_video"
			android:keyEdgeFlags="right" />
    </Row>

    <Row>
        <Key android:codes="-1"  android:keyWidth="65px" android:keyIcon="@drawable/blackkey_shift" android:iconPreview="@drawable/icon_shift"
                android:isModifier="true" android:isSticky="true" android:keyEdgeFlags="left"/>
        <Key android:codes="122" android:keyLabel="z" android:popupKeyboard="@xml/popup" android:popupCharacters="żžź" />
        <Key android:codes="120" android:keyLabel="x"/>
        <Key android:codes="99" android:keyLabel="c" android:popupKeyboard="@xml/popup" android:popupCharacters="çćĉč" />
        <Key android:codes="118" android:keyLabel="v"/>
        <Key android:codes="98" android:keyLabel="b"/>
        <Key android:codes="110" android:keyLabel="n" android:popupKeyboard="@xml/popup" android:popupCharacters="ñń" android:horizontalGap = "228px"/>
        <Key android:codes="109" android:keyLabel="m"/>
		<Key android:codes="44" android:keyLabel="," />
		<Key android:codes="46" android:keyLabel="."/>
        <Key android:codes="63" android:keyLabel="\?"/>
		<Key android:codes="-1" android:keyIcon="@drawable/blackkey_shift"  android:iconPreview="@drawable/icon_shift"
		     android:keyWidth="65px" android:isModifier="true" android:isSticky="true"
		     android:keyEdgeFlags="right"/>
    </Row>

    <Row android:rowEdgeFlags="bottom">
        <Key android:codes="-3"   android:keyWidth="65px" android:keyIcon="@drawable/blackkey_input"  android:iconPreview="@drawable/icon_input"
             android:keyEdgeFlags="left"/>
        <Key android:codes="-2" android:keyIcon="@drawable/blackkey_num" android:iconPreview="@drawable/icon_num"/>
        <Key android:codes="0" android:keyIcon="@drawable/blackkey_icon"
             android:popupKeyboard="@xml/popup_smileys" android:iconPreview="@drawable/icon_icon"/>
        <Key android:codes="47" android:keyIcon="@drawable/blackkey_slith" android:iconPreview="@drawable/icon_slith" />
        <Key android:codes="32" android:keyIcon="@drawable/whitekey_space" android:iconPreview="@drawable/icon_space"
             android:keyWidth="84px" android:isRepeatable="true" />
        <Key android:codes="32" android:keyIcon="@drawable/whitekey_space" android:iconPreview="@drawable/icon_space"
             android:keyWidth="84px" android:isRepeatable="true" android:horizontalGap = "230px" />
        <Key android:codes="999" android:keyIcon="@drawable/blackkey_com" android:horizontalGap = "4px" android:iconPreview="@drawable/icon_com"/>
        <Key android:codes="21" android:keyIcon="@drawable/whitekey_left" android:iconPreview="@drawable/icon_left"/>
        <Key android:codes="22" android:keyIcon="@drawable/blackkey_right" android:iconPreview="@drawable/icon_right" />
        <Key android:codes="10" android:keyIcon="@drawable/blackkey_send"  android:iconPreview="@drawable/icon_send"
             android:keyEdgeFlags="right" android:horizontalGap = "13px"/>
    </Row>
</Keyboard>


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="utf-8">

<title>bootstrap-wysihtml5</title>

<link rel="stylesheet" type="text/css" href="lib/css/bootstrap.min.css"></link>

<link rel="stylesheet" type="text/css" href="src/bootstrap-wysihtml5.css"></link>

		<textarea class="textarea" placeholder="Enter text ..." style="width: 810px; height: 200px"></textarea>


text:
package com.azure.cosmos.spark.diagnostics

import com.azure.cosmos.implementation.spark.OperationContext
import com.azure.cosmos.spark.CosmosPredicates.requireNotNull

import java.util.UUID;

private[spark] trait WriteOperation {
  def sparkTaskContext : SparkTaskContext
  def itemIdentifier: CosmosItemIdentifier
}

private[spark] case class UpsertOperation(sparkTaskContext: SparkTaskContext, itemIdentifier: CosmosItemIdentifier)
  extends WriteOperation

private[spark] case class CreateOperation(sparkTaskContext: SparkTaskContext, itemIdentifier: CosmosItemIdentifier)
  extends WriteOperation

private[spark] case class DeleteOperation(sparkTaskContext: SparkTaskContext, itemIdentifier: CosmosItemIdentifier)
  extends WriteOperation

private[spark] case class ReplaceOperation(sparkTaskContext: SparkTaskContext, itemIdentifier: CosmosItemIdentifier)
  extends WriteOperation

private[spark] case class PatchOperation(sparkTaskContext: SparkTaskContext, itemIdentifier: CosmosItemIdentifier)
 extends WriteOperation

private[spark] case class SparkTaskContext(correlationActivityId: UUID,
                                           stageId: Int,
                                           partitionId: Long,
                                           taskAttemptId: Long,
                                           details: String) extends OperationContext {

  requireNotNull(correlationActivityId, "correlationActivityId")

  private val correlationActivityIdAsString = correlationActivityId.toString

  @transient private lazy val cachedToString = {
    "SparkTaskContext(" +
      "correlationActivityId=" + correlationActivityIdAsString +
      ",stageId=" + stageId +
      ",partitionId=" + partitionId +
      ",taskAttemptId=" + taskAttemptId +
      ",details=" + details + ")"
  }

  override def getCorrelationActivityId: String = correlationActivityIdAsString

  override def toString: String = {
    cachedToString
  }
}


text:
import styled, { css } from "styled-components"

const leftRightTopBottom = css`
  display: flex;
  position: absolute;
`

const leftRight = css`
  flex-direction: row;
  cursor: ew-resize;
`

const topBottom = css`
  flex-direction: column;
  cursor: ns-resize;
`

export const Container = styled.div`
   position: relative;
`

export const Left = styled.div`
  ${leftRightTopBottom}
  ${leftRight}
`

export const Right = styled.div`
  ${leftRightTopBottom}
  ${leftRight}
`

export const Top = styled.div`
  ${leftRightTopBottom}
  ${topBottom}
`

export const Bottom = styled.div`
  ${leftRightTopBottom}
  ${topBottom}
`

export const NumberBox = styled.div`
  display: flex;
  position: absolute;
  justify-content: center;
  align-items: center;
  user-select: none;
`

export const Input = styled.input`
  outline: none;
  width: calc(100% - 5px);
  height: calc(100% - 8px);
  text-align: center;
  border: none;
  background-color: transparent;
`

export const ButtonContainer = styled.div`
  overflow: hidden;
`

export const ButtonTriangle = styled.div`
  transition: all .2s;
  user-select: none;
  ${(props: any) => {
    switch (props.theme.position) {
      case "left":
        return `
          border-right-color: #666;
          &:hover {
              border-right-color: black;
          }
        `
      case "top":
        return `
          border-bottom-color: #666;
          &:hover {
              border-bottom-color: black;
          }
        `
      case "right":
        return `
          border-left-color: #666;
          &:hover {
              border-left-color: black;
          }
        `
      case "bottom":
        return `
          border-top-color: #666;
          &:hover {
              border-top-color: black;
          }
        `
    }
  }}
`


text:
"""Module containing Builder_elph and Builder_many_body_elph classes."""

from .builder_base import BuilderBase
from .builder_base import attribute_map
from .builder_base import BuilderManyBody
from ..indexing import StateIndexingDM
from ..indexing import StateIndexingDMc
from ..baths import PhononBaths

from .validation import validate_itype_ph

# -----------------------------------------------------------
# Python modules

from ..approach.elph.pauli import ApproachPauli as ApproachPyPauli
from ..approach.elph.lindblad import ApproachLindblad as ApproachPyLindblad
from ..approach.elph.neumann1 import Approach1vN as ApproachPy1vN
from ..approach.elph.redfield import ApproachRedfield as ApproachPyRedfield
from ..approach.base.neumann2 import Approach2vN as ApproachPy2vN

# Cython compiled modules

try:
    from ..approach.elph.c_pauli import ApproachPauli
    from ..approach.elph.c_lindblad import ApproachLindblad
    from ..approach.elph.c_redfield import ApproachRedfield
    from ..approach.elph.c_neumann1 import Approach1vN
    from ..approach.base.c_neumann2 import Approach2vN
except ImportError:
    print("WARNING: Cannot import Cython compiled modules for the approaches (builder_elph.py).")
    ApproachPauli = ApproachPyPauli
    ApproachLindblad = ApproachPyLindblad
    ApproachRedfield = ApproachPyRedfield
    Approach1vN = ApproachPy1vN
    Approach2vN = ApproachPy2vN
# -----------------------------------------------------------

attribute_map_elph = dict(
    # StateIndexing
    baths='si', velph='baths',
    # PhononBaths
    tlst_ph='baths', dlst_ph='baths',
    Vbbp='baths', bath_func='baths',
    # FunctionProperties
    itype_ph='funcp', eps_elph='funcp'
    )
attribute_map.update(attribute_map_elph)

class BuilderElPh(BuilderBase):
    """"
    Class for building the system for stationary transport calculations
    with Electron-Phonon (elph) coupling.

    For missing descriptions of attributes use help(Builder).

    Attributes
    ----------
    nbaths : int
        Number of the phonon baths.
    velph : dict, list, or array
        Dictionary, list, or numpy array defining single particle tunneling amplitudes.
        numpy array has to be nbaths by nsingle by nsingle.
    tlst_ph : dict, list, or array
        Dictionary, list, or array containing temperatures of the phonon baths.
    dband_ph : dict, list, or array
        Dictionary, list, or array determining bandwidths of the phonon baths.
    bath_func : list
        List of length nbaths containing density of states functions for the phonon baths.
    eps_elph : float
        Small parameter which stabilizes the integration for integrand with a Bose function.
    """

    def __init__(self,
                 nsingle=0, hsingle={}, coulomb={},
                 nleads=0, tleads={}, mulst={}, tlst={}, dband={},
                 nbaths=0, velph={}, tlst_ph={}, dband_ph={},
                 indexing=None, kpnt=None,
                 kerntype='Pauli', symq=True, norm_row=0, solmethod=None,
                 itype=0, itype_ph=0, dqawc_limit=10000,
                 mfreeq=False, phi0_init=None,
                 mtype_qd=complex, mtype_leads=complex,
                 symmetry=None, herm_hs=True, herm_c=False, m_less_n=True,
                 bath_func=None, eps_elph=1.0e-6):

        self._init_copy_data(locals())
        self._init_validate_data()
        self._init_set_globals()
        self._init_set_approach_class()
        self._init_create_setup()
        self._init_create_appr()

    def _init_validate_data(self):
        BuilderBase._init_validate_data(self)
        data = self.data
        data.itype_ph = validate_itype_ph(data.itype_ph)

    def _init_set_globals(self):
        self.globals = globals()

    def _init_create_setup(self):
        BuilderBase._init_create_setup(self)
        data = self.data

        self.funcp.itype_ph = data.itype_ph
        self.funcp.eps_elph = data.eps_elph

        self.baths = PhononBaths(data.nbaths, data.velph, self.si,
                                 data.tlst_ph, data.dband_ph, data.bath_func)

        self.create_si_elph()

    def change_si(self):
        BuilderBase.change_si(self)
        self.create_si_elph()

    def create_si_elph(self):
        si = self.si
        si_elph = StateIndexingDMc(si.nsingle, si.indexing,
                                   si.symmetry, si.nleads)
        si_elph.nbaths = si.nbaths
        self.si_elph = si_elph

    def add(self,
            hsingle=None, coulomb=None, tleads=None, mulst=None, tlst=None, dlst=None,
            velph=None, tlst_ph=None, dlst_ph=None):
        BuilderBase.add(self, hsingle, coulomb, tleads, mulst, tlst, dlst)
        if not (velph is None and tlst_ph is None and dlst_ph is None):
            self.baths.add(velph, tlst_ph, dlst_ph)

    def change(self,
               hsingle=None, coulomb=None, tleads=None, mulst=None, tlst=None, dlst=None,
               velph=None, tlst_ph=None, dlst_ph=None):
        BuilderBase.change(self, hsingle, coulomb, tleads, mulst, tlst, dlst)
        if not (velph is None and tlst_ph is None and dlst_ph is None):
            self.baths.change(velph, tlst_ph, dlst_ph)

    def remove_states(self, dE):
        BuilderBase.remove_states(self, dE)
        self.si_elph.set_statesdm(self.si.statesdm)

    def remove_fock_states(self, lin_state_indices):
        BuilderBase.remove_fock_states(self, lin_state_indices)
        self.baths._init_coupling()
        self.si_elph.remove_fock_states(lin_state_indices)

class BuilderManyBodyElPh(BuilderElPh, BuilderManyBody):
    """
    Class for building the system for stationary transport calculations,
    using many-body states as an input. Also includes Electron-Phonon coupling.

    For missing descriptions of attributes use:
        help(Builder), help(Builder_many_body), help(Builder_elph).

    Attributes
    ----------
    Vbbp : array
        nbaths by nmany by nmany array, which contains many-body electron-phonon coupling matrix.
    """

    def __init__(self,
                 Ea=None, Na=[0], Tba=None, Vbbp=None,
                 mulst={}, tlst={}, dband={}, tlst_ph={}, dband_ph={}, kpnt=None,
                 kerntype='Pauli', symq=True, norm_row=0, solmethod=None,
                 itype=0, dqawc_limit=10000, mfreeq=False, phi0_init=None,
                 mtype_qd=complex, mtype_leads=complex,
                 symmetry=None, herm_hs=True, herm_c=False, m_less_n=True,
                 bath_func=None, eps_elph=1.0e-6):

        nleads = Tba.shape[0] if Tba is not None else 0
        nbaths = Vbbp.shape[0] if Vbbp is not None else 0

        # noinspection PyPep8
        BuilderElPh.__init__(self,
            nleads=nleads, mulst=mulst, tlst=tlst, dband=dband,
            nbaths=nbaths, tlst_ph=tlst_ph, dband_ph=dband_ph, kpnt=kpnt,
            kerntype=kerntype, symq=symq, norm_row=norm_row, solmethod=solmethod,
            itype=itype, dqawc_limit=dqawc_limit, mfreeq=mfreeq, phi0_init=phi0_init,
            mtype_qd=mtype_qd, mtype_leads=mtype_leads,
            symmetry=symmetry, herm_hs=herm_hs, herm_c=herm_c, m_less_n=m_less_n,
            bath_func=bath_func, eps_elph=eps_elph,
            indexing='charge')

        self._init_state_indexing(Na, Ea)

        self.qd.Ea = Ea
        self.leads.Tba = Tba
        self.baths.Vbbp = Vbbp


text:
package org.hswebframework.web.crud.events;

import lombok.Getter;
import lombok.Setter;
import org.hswebframework.ezorm.rdb.events.EventContext;
import org.hswebframework.ezorm.rdb.events.EventListener;
import org.hswebframework.ezorm.rdb.events.EventType;
import org.springframework.core.Ordered;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Getter
@Setter
public class CompositeEventListener implements EventListener {

    private List<EventListener> eventListeners = new CopyOnWriteArrayList<>();

    @Override
    public void onEvent(EventType type, EventContext context) {
        for (EventListener eventListener : eventListeners) {
            eventListener.onEvent(type, context);
        }
    }

    public void addListener(EventListener eventListener) {
        eventListeners.add(eventListener);
        eventListeners.sort(Comparator.comparingLong(e -> e instanceof Ordered ? ((Ordered) e).getOrder() : Ordered.LOWEST_PRECEDENCE));
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.opensim.threejs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.eclipse.jetty.JettyMain;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
import org.opensim.swingui.SwingWorker;
import org.opensim.utils.BrowserLauncher;
import org.opensim.view.pub.OpenSimDB;
import org.opensim.view.pub.ViewDB;

@ActionID(
        category = "Edit",
        id = "org.opensim.threejs.VisualizerWindow"
)
@ActionRegistration(
        displayName = "#CTL_VisualizerWindow"
)
@ActionReference(path = "Menu/Window", position = 10000)
@Messages("CTL_VisualizerWindow=View in Browser")
public final class VisualizerWindowAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // launch server and open page in fixed location to be used as a view
        openVisualizerWindow();
    }

    public static void openVisualizerWindow() {
        ViewDB.getInstance().startVisualizationServer();
        BrowserLauncher.openURL("http://localhost:"+JettyMain.getSERVER_PORT()+JettyMain.getPathToStartPage()+"index.html");
    }

}


text:
package com.orasi.api.soapServices.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.xmlbeans.XmlException;
import org.jaxen.SimpleNamespaceContext;
import org.testng.Reporter;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.eviware.soapui.impl.wsdl.WsdlInterface;
import com.eviware.soapui.impl.wsdl.WsdlOperation;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlImporter;
import com.eviware.soapui.support.SoapUIException;
import com.orasi.utils.XMLTools;

@SuppressWarnings("deprecation")
public abstract class SoapService{

	private String strEnvironment = null;
	private String strServiceURL = null;
	private String strResponseURI = null;
	private String intResponseStatusCode = null;
	private String responseTemplate = null;
	private static Document requestDocument = null;
	private static Document responseDocument = null;
	protected static  StringBuffer buffer = new StringBuffer();

	/*****************************
	 **** Start Gets and Sets ****
	 *****************************/

	/**
	 * @summary Takes the current Request XML Document stored in memory and
	 *          return it as a string for simple output
	 * @precondition Requires XML Document to be loaded by using
	 *               {@link #setRequestDocument}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Will return the current Request XML as a string
	 */
	public String getRequest() {
		StringWriter sw = new StringWriter();
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = null;
		try {
			transformer = tf.newTransformer();
		} catch (TransformerConfigurationException e) {
			throw new RuntimeException("Failed to create XML Transformer");
		}
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

		try {
			transformer.transform(new DOMSource(getRequestDocument()),
					new StreamResult(sw));
		} catch (TransformerException e) {
			throw new RuntimeException(
					"Failed to transform Request XML Document. Ensure XML Document has been successfully loaded.");
		}
		return sw.toString();
	}

	/**
	 * @summary Takes the current Response XML Document stored in memory and
	 *          return it as a string for simple output
	 * @precondition Requires XML Document to be loaded by using
	 *               {@link #setResponseDocument}
	 * @author Justin Phlegar
	 * @version Created 08/28/2014
	 * @return Will return the current Response XML as a string
	 */
	public String getResponse() {
		StringWriter sw = new StringWriter();
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = null;
		try {
			transformer = tf.newTransformer();
		} catch (TransformerConfigurationException e) {
			throw new RuntimeException("Failed to create XML Transformer");
		}
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

		try {
			transformer.transform(new DOMSource(getResponseDocument()),
					new StreamResult(sw));
		} catch (TransformerException e) {
			throw new RuntimeException(
					"Failed to transform Response XML Document. Ensure XML Document has been successfully loaded.");
		}
		return sw.toString();
	}

	/**
	 * @summary Returns the environment under test. Current accepted
	 *          environments are:

	 *          Dev - Developer server or environment

	 *          Bashful - Integrated Testing Environment

	 *          Sleepy - Functional Environment 1

	 *          Snow White - Functional Environment 2

	 *          Doc - Performance Environment 1

	 *          Evil Queen - Performance Environment 2

	 *          Grumpy - Pre-Production Staging Environment
	 * @precondition The environment under test needs to be set by
	 *               {@link #setEnvironment(String)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Returns the environment under test as a String
	 */
	public String getEnvironment() {
		return strEnvironment;
	}

	/**
	 * @summary After a service request has been sent, if the Status code of the
	 *          response has been stored, then this function can be used to
	 *          retrieve that status code
	 * @precondition The Response Status Code needs to be set by
	 *               {@link #setRepsonseStatusCode(String)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Returns the Status Code of a response as a String
	 */
	public String getResponseStatusCode() {
		return intResponseStatusCode;
	}

	/**
	 * @summary Return the URL of the service under test
	 * @precondition The Service URL needs to be set by
	 *               {@link #setServiceURL(String)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Returns the Service URL as a String
	 */
	public String getServiceURL() {
		return strServiceURL;
	}

	/**
	 * @summary This is used to retrieve the current XML Document as it is in
	 *          memory.
	 * @precondition The XML Document needs to be set by
	 *               {@link #setRequestDocument(Document)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Returns the stored Request XML as a Document
	 */
	protected Document getRequestDocument() {
		return requestDocument;
	}

	/**
	 * @summary This is used to retrieve the current Response Document as it is
	 *          in memory
	 * @precondition The Response Document needs to be set by
	 *               {@link #setResponseDocument(Document)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Returns the stored Response XML as a Document object
	 */
	protected static Document getResponseDocument() {
		return responseDocument;
	}

	/**
	 * @summary This is used to retrieve the current Response URI string as it
	 *          is in memory
	 * @precondition Requires XML Document to be loaded by using
	 *               {@link #setResponseBaseURI(String)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Returns the stored Response URI as a String
	 */
	protected String getResponseBaseURI() {
		return strResponseURI;
	}

	/**
	 * @summary This is used to retrieve the current Response XML Template as it
	 *          is in memory
	 * @precondition Requires XML Document to be loaded by using
	 *               {@link #setResponseTemplate(String)}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @return Will return the Response XML Template as a String
	 */
	protected String getResponseTemplate() {
		return responseTemplate;
	}

	/**
	 * @summary Sets the environment under test. Current accepted environments
	 *          are:

	 *          Dev - Developer server or environment

	 *          Bashful - Integrated Testing Environment

	 *          Sleepy - Functional Environment 1

	 *          Snow White - Functional Environment 2

	 *          Doc - Performance Environment 1

	 *          Evil Queen - Performance Environment 2

	 *          Grumpy - Pre-Production Staging Environment

	 *

	 *          Can be retrieved by {@link #getEnvironment()}
	 * @precondition The environment under test must be one of the environments
	 *               listed above.
	 * @author Justin Phlegar
	 * @version Created 08/28/2014
	 * @param environment
	 *            String: Environment under test
	 */
	protected void setEnvironment(String environment) {
		strEnvironment = environment;
	}

	/**
	 * @summary Used to store the XML file as a Document object in memory. Can
	 *          be retrieved using {@link #getRequestDocument()}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param doc
	 *            Document XML file of the Request to be stored in memory
	 */
	protected static void setRequestDocument(Document doc) {
		requestDocument = doc;
	}

	/**
	 * @summary Used to store the XML file as a Document object in memory. Can
	 *          be retrieved using {@link #getRequestDocument()}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param code
	 *            String: Response error code
	 */
	protected void setRepsonseStatusCode(String code) {
		intResponseStatusCode = code;
	}

	/**
	 * @summary Set a Response XML Document to be stored in memory to be
	 *          retrieved and edited easily. Retrieve XML Document using
	 *          {@link #getResponseDocument()} or as a String using
	 *          {@link #getResponse()}
	 * @precondition Requires valid XML Document to be sent
	 * @author Justin Phlegar
	 * @version Created 08/28/2014
	 * @param doc
	 *            Document: XML file of the Response to be stored in memory
	 */
	protected void setResponseDocument(Document doc) {
		responseDocument = doc;
	}

	/**
	 * @summary Used to store the XML file of the base Soap Response file as a
	 *          Document object in memory. Can be retrieved using
	 *          {@link #getResponseTemplate()}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param response
	 *            String: Store the base XML response as a String
	 */
	protected void setResponseTemplate(String response) {
		responseTemplate = response;
	}

	/**
	 * @summary Used to store the main Namespace URI for a Response document.
	 *          Can be retrieved using {@link #getRequestDocument()}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param uri
	 *            String: Main Namespace URI of a response.
	 */
	protected void setResponseBaseURI(String uri) {
		strResponseURI = uri;
	}

	/**
	 * @summary Used to store URL of the Service Under Test in memory. Can be
	 *          retrieved using {@link #getServiceURL())}
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param url
	 *            String: URL Endpoint of the Service Under Test
	 */
	protected void setServiceURL(String url) {
		strServiceURL = url;
	}

	/***************************
	 **** End Gets and Sets ****
	 ***************************/

	/*************************************
	 ********* Public Methods ************
	 *************************************/

	/**
	 * @summary Lazily check the response and return the value of the first
	 *          matching tag
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param tag
	 *            String: Finds and returns the value of the first tag it finds
	 *            with this tag name
	 */
	public String getFirstNodeValueByTagName(String tag) {
		// Get the response document from memory
		NodeList nList = getResponseDocument().getElementsByTagName(tag);
		return nList.item(0).getTextContent();
	}

	/**
	 * @summary Takes an xpath and return the value if found in the request
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param xpath
	 *            String: xpath to evaluate
	 */
	public String getRequestNodeValueByXPath(String xpath) {
		return XMLTools.getValueByXpath(getRequestDocument(), xpath);
	}

	/**
	 * @summary Takes an xpath and return the value if found in the response
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param xpath
	 *            String: xpath to evaluate
	 */
	public static String getResponseNodeValueByXPath(String xpath) {
		return XMLTools.getValueByXpath(getResponseDocument(), xpath);
	}

	public String getResponseNodeValueByXPath(String xpath, String[][] namespaces) {
		SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
		for(int nsCounter = 0; nsCounter < namespaces.length; nsCounter++){
			nsContext.addNamespace(namespaces[nsCounter][0], namespaces[nsCounter][1]);
		}
		XPathFactory xPathFactory = XPathFactory.newInstance();
		XPath xPath = xPathFactory.newXPath();
		XPathExpression expr;
		NodeList nList = null;
		Document doc = getResponseDocument();

		try {
			expr = xPath.compile(xpath);
			nList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		} catch (XPathExpressionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return nList.item(0).getTextContent();
	}
	/**
	 * @summary Find and open the excel file sent. If successful, look and find
	 *          the matching scenario name then return its xpath and value data.
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param file
	 *            String: File location either in the project or the hard disk
	 *            path
	 * @param scenario
	 *            String: Name of the scenario to poll data for
	 * @throws FileNotFoundException
	 *             Could not find the file in the path given
	 * @throws BiffException
	 * @throws IOException
	 *             Failed to open the file
	 * @throws ArrayIndexOutOfBoundsException
	 *             Loop failed to catch and ending row
	 */
	protected Object[][] getTestScenario(String file, String scenario) {

		String[][] tabArray = null;
		try {

			// Get the file location from the project main/resources folder
			String filePath = getClass().getResource(file).getPath();

			// in case file path has a %20 for a whitespace, replace with actual
			// whitespace
			filePath = filePath.replace("%20", " ");

			// Open excel workbook to work and from file from the path
			Workbook workbook = Workbook.getWorkbook(new File(filePath));
			Sheet sheet = workbook.getSheet(0);
			int startRow, startCol, endRow, endCol, ci, cj;

			// Find the specific cell containing the scenario to run.
			Cell tableStart = sheet.findCell(scenario);
			startRow = tableStart.getRow();
			startCol = tableStart.getColumn();

			// Loop through cell in Regex column to find the first blank cell.
			// This is set as the last row
			for (int i = startRow + 1;; i++) {
				try {
					if (sheet.getCell(startCol + 1, i).getContents().toString()
							.equals("")) {
						endRow = i;
						break;
					}
				} catch (ArrayIndexOutOfBoundsException arrayError) {
					endRow = i;
					break;
				}

			}
			endCol = startCol + 3;

			// Create array based on size of columns and rows found
			tabArray = new String[endRow - startRow - 1][endCol - startCol - 1];
			ci = 0;

			// Feed results to the dual array
			for (int i = startRow + 1; i < endRow; i++, ci++) {
				cj = 0;
				for (int j = startCol + 1; j < endCol; j++, cj++) {
					tabArray[ci][cj] = sheet.getCell(j, i).getContents();
				}
			}
		} catch (FileNotFoundException fnfe) {
			throw new RuntimeException(fnfe.getCause());
		} catch (BiffException be) {
			throw new RuntimeException(be.getCause());
		} catch (IOException ioe) {
			throw new RuntimeException("Unable to open file " + file + "\n"
					+ ioe.getCause());
		}
		return (tabArray);
	}

	/**
	 * @summary Takes the pre-built Request XML in memory and sends to the
	 *          service
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @throws UnsupportedOperationException
	 *             Operation given did not match any of the existing operations
	 * @throws SOAPException
	 * @throws IOException
	 *             Failed to read the Request properly
	 */
	public SOAPMessage sendRequest() {
		SOAPMessage request = null;
		SOAPMessage response = null;
		SOAPConnectionFactory connectionFactory = null;
		SOAPConnection connection = null;
		SOAPBody responseBody = null;
		MessageFactory messageFactory = null;

		// Get the service endpoint from previously stored URL
		String url = getServiceURL();

		try {
			messageFactory = MessageFactory
					.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

			// Convert XML Request to SoapMessage
			request = messageFactory.createMessage(new MimeHeaders(),
					new StringBufferInputStream(getRequest()));
			request.writeTo(System.out);
			System.out.println();

			// Send out Soap Request to the endopoint
			connectionFactory = SOAPConnectionFactory.newInstance();

			connection = connectionFactory.createConnection();
			response = connection.call(request, url);

			// Normalize Response and get the soap body
			response.getSOAPBody().normalize();
			responseBody = response.getSOAPBody();
		} catch (UnsupportedOperationException uoe) {
			throw new RuntimeException(
					"Operation given did not match any operations in the service"
							+ uoe.getCause());
		} catch (SOAPException soape) {
			throw new RuntimeException(soape.getCause());
		} catch (IOException ioe) {
			throw new RuntimeException("Failed to read the request properly"
					+ ioe.getCause());
		}

		// Check for faults and report
		if (responseBody.hasFault()) {
			SOAPFault newFault = responseBody.getFault();
			setRepsonseStatusCode(newFault.getFaultCode());
			System.out
					.println("sendSoapReq FAULT:  " + newFault.getFaultCode());
		} else {
			setRepsonseStatusCode("200");
		}

		try {
			connection.close();

		} catch (SOAPException soape) {
			throw new RuntimeException(soape.getCause());
		}

		// Covert Soap Response to XML and set it as Response in memory
		Document doc = XMLTools.makeXMLDocument(response);
		doc.normalize();
		setResponseDocument(doc);
		setResponseBaseURI(responseBody.getNamespaceURI());
		System.out.println();
		System.out.println();
		System.out.println("Response");
		System.out.println(getResponse());
		return response;
	}

	/**
	 * @summary Takes the pre-built Request XML in memory and sends to the
	 *          service
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @throws UnsupportedOperationException
	 *             Operation given did not match any of the existing operations
	 * @throws SOAPException
	 * @throws IOException
	 *             Failed to read the Request properly
	 */
	public SOAPMessage sendRequest(String[] headerName, String[] headerValue) {
		SOAPMessage request = null;
		SOAPMessage response = null;
		SOAPConnectionFactory connectionFactory = null;
		SOAPConnection connection = null;
		SOAPBody responseBody = null;
		MessageFactory messageFactory = null;

		// Get the service endpoint from previously stored URL
		String url = getServiceURL();

		try {
			messageFactory = MessageFactory
					.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

			// Convert XML Request to SoapMessage

			MimeHeaders headers = new MimeHeaders();
			headers.setHeader(headerName[0], headerValue[0]);
			if(headerName.length > 1){
				for(int headerCounter = 0; headerCounter < headerName.length; headerCounter++){
					headers.addHeader(headerName[headerCounter], headerValue[headerCounter]);
				}
			}
			request = messageFactory.createMessage(headers,
					new StringBufferInputStream(getRequest()));
			request.writeTo(System.out);
			System.out.println();

			// Send out Soap Request to the endopoint
			connectionFactory = SOAPConnectionFactory.newInstance();

			connection = connectionFactory.createConnection();
			response = connection.call(request, url);

			// Normalize Response and get the soap body
			response.getSOAPBody().normalize();
			responseBody = response.getSOAPBody();
		} catch (UnsupportedOperationException uoe) {
			throw new RuntimeException(
					"Operation given did not match any operations in the service"
							+ uoe.getCause());
		} catch (SOAPException soape) {
			throw new RuntimeException(soape.getCause());
		} catch (IOException ioe) {
			throw new RuntimeException("Failed to read the request properly"
					+ ioe.getCause());
		}

		// Check for faults and report
		if (responseBody.hasFault()) {
			SOAPFault newFault = responseBody.getFault();
			setRepsonseStatusCode(newFault.getFaultCode());
			System.out
					.println("sendSoapReq FAULT:  " + newFault.getFaultCode());
		} else {
			setRepsonseStatusCode("200");
		}

		try {
			connection.close();

		} catch (SOAPException soape) {
			throw new RuntimeException(soape.getCause());
		}

		// Covert Soap Response to XML and set it as Response in memory
		Document doc = XMLTools.makeXMLDocument(response);
		doc.normalize();
		setResponseDocument(doc);
		setResponseBaseURI(responseBody.getNamespaceURI());
		System.out.println();
		System.out.println();
		System.out.println("Response");
		System.out.println(getResponse());
		return response;
	}

	/**
	 * @summary Update multiple XPath nodes or attributes based on the value. The value
	 *          is not limited to simple values, but may also call various
	 *          functions by adding "fx:" as a prefix. Please see
	 *          {@link #handleValueFunction} for more information
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param xpath
	 *            String: xpath to evaluate
	 * @param value
	 *            String: Depending on value given, will update the xpath value,
	 *            attribute, or call a separate function.
	 *

Value syntax expressions:
	 *
value="abc"  -- Indirectly states that the node value will be set as "abc"
	 *
value="value:abc"  -- Directly states that the node value will be set as "abc"
	 *
value="attribute:attrName,abc"  -- Directly states that the node attribute "attrName" will be set as "abc"
	 *
value="fx:funcName" -- Will call the function "funcName" to be handled in {@link #handleValueFunction}
	 */
	public void setRequestNodeValueByXPath(String xpath, String value) {
			XMLTools.setRequestNodeValueByXPath(getRequestDocument(),xpath,value);
	}

	/**
	 * @summary Update multiple XPath nodes or attributes based on the value. The value
	 *          is not limited to simple values, but may also call various
	 *          functions by adding "fx:" as a prefix. Please see
	 *          {@link #handleValueFunction} for more information
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param xpath
	 *            String: xpath to evaluate
	 * @param value
	 *            String: Depending on value given, will update the xpath value,
	 *            attribute, or call a separate function.
	 *

Value syntax expressions:
	 *
value="abc"  -- Indirectly states that the node value will be set as "abc"
	 *
value="value:abc"  -- Directly states that the node value will be set as "abc"
	 *
value="attribute:attrName,abc"  -- Directly states that the node attribute "attrName" will be set as "abc"
	 *
value="fx:funcName" -- Will call the function "funcName" to be handled in {@link #handleValueFunction}
	 */
	public void setRequestNodeValueByXPath(Object[][] scenarios) {
		for (int x = 0; x < scenarios.length; x++) {
			XMLTools.setRequestNodeValueByXPath(getRequestDocument(),scenarios[x][0].toString(),
					scenarios[x][1].toString());
		}
	}

	/**
	 * @summary Validate XML Repsonse and reports findings
	 * @author Justin Phlegar
	 * @version Created: 08/28/2014
	 * @param doc Document: XML Document to evalute
	 * @param xpath String: xpath to evaluate
	 * @param value String: Depending on value given, will validate the xpath node or attribute value,
	 *

Value syntax expressions:
	 *
value="abc"  -- Indirectly states that the node value will be validated and expected to be "abc"
	 *
value="value:abc"  -- Directly states that the node value will be validated and expected to be "abc"
	 *
value="attribute:attrName,abc"  -- Directly states that the node attribute "attrName" will be validated and expected to be "abc"
	 *
	 */
	public boolean validateNodeValueByXPath(Document doc, Object[][] scenarios) {
		boolean status = true;
		buffer.setLength(0);
		buffer.append("
");
		buffer.append("
XPath	");
		buffer.append("Regex	");
		buffer.append("Value	");
		buffer.append("Status
");
		for (int x = 0; x < scenarios.length; x++) {
			if (!XMLTools.validateNodeValueByXPath(doc, scenarios[x][0].toString(),
					scenarios[x][1].toString())) {
				status = false;
			}
		}
		buffer.append("
");
		Reporter.log(buffer.toString()+ "
");
		return status;
	}

	public boolean validateResponse(String resourcePath, String scenario) {
		return validateNodeValueByXPath(getResponseDocument(),
				getTestScenario(resourcePath, scenario));
	}

	protected String sendGetRequest(String strUrl) throws Exception {

		StringBuilder rawResponse = new StringBuilder();

		URL urlRequest = null;

		try {
			urlRequest = new URL(strUrl);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpURLConnection conn = (HttpURLConnection) urlRequest
				.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("GET");

		InputStream stream = conn.getInputStream();
		BufferedReader bufferReader = new BufferedReader(new InputStreamReader(
				stream));

		String buffer = "";
		while ((buffer = bufferReader.readLine()) != null) {
			rawResponse.append(buffer);
		}

		return rawResponse.toString();
	}

	protected void setEnvironmentServiceURL(String service, String environment) {
		setEnvironment(environment);

		// include the %20 as whitespace for URL format
		if (environment.toLowerCase().contains(" ")){
			environment.replaceAll(" ", "%20");
		}

		String url = "http://dmweb.wdw-ilab.wdw.disney.com:8081/EnvSrvcEndPntRepository/rest/retrieveServiceEndpoint/{environment}/{service}";
		String responseXML = "";
		Document responseDoc = null;
		url = url.replace("{environment}", environment);
		url = url.replace("{service}", service);

		try {
			responseXML = sendGetRequest(url);
			responseDoc = XMLTools.makeXMLDocument(responseXML);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		setServiceURL(getFirstNodeValueByTagName(responseDoc, "endPoint") + "?wsdl");

	}

	protected void setEnvironmentServiceURL(String endpoint) {
		if (endpoint.contains("http")){
			setServiceURL(endpoint + "?wsdl");
		}else{
			setServiceURL(endpoint + ".wsdl");
		}
	}

	protected String buildRequestFromWSDL(String service) {
		Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
		logger.setUseParentHandlers(false);
		logger.setLevel(Level.OFF);

		WsdlProject project = null;

		try {
			project = new WsdlProject();
		} catch (XmlException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SoapUIException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		WsdlInterface[] wsdls = null;
		try {
			wsdls = WsdlImporter.importWsdl(project, getServiceURL());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		WsdlInterface wsdl = wsdls[0];
		WsdlOperation op = wsdl.getOperationByName(service);
		setResponseTemplate(op.createResponse(true));
		return op.createRequest(true);
	}

	protected void removeComments() {
		setRequestDocument((Document) XMLTools
				.removeComments(getRequestDocument()));
	}

	protected void removeWhiteSpace() {
		setRequestDocument(XMLTools.removeWhiteSpace(getRequestDocument()));
	}

	private String getFirstNodeValueByTagName(Document doc, String tag) {
		NodeList nList = doc.getElementsByTagName(tag);
		return nList.item(0).getTextContent();
	}

	public boolean validateRepsonseXML() {
		Document doc = getResponseDocument();
		String uri = getResponseBaseURI();

		if (doc == null) {
			throw new RuntimeException("Reponse document was null.");
		} else if (uri.isEmpty()) {
			throw new RuntimeException("URI was null.");
		}

		return XMLTools.validateXMLSchema(uri, doc);
	}
}


text:
'use strict';

const Router = require('express').Router;
const debug = require('debug')('alexa-skillz:user-router');
const User = require('../model/user.js');
const userRouter = module.exports = Router();

userRouter.get('/api/users', function(request, response, next) {
  debug('GET: /api/users');

  User.find(function(err, users) {
    if (err) {
      return next(err);
    }
    response.json(users);
  });
});

userRouter.get('/api/users/:user', function(request, response) {
  debug('GET: /api/users/:user');

  response.json(request.user);
});

userRouter.param('user', function(request, response, next, id) {
  var query = User.findById(id);

  query.exec(function(err, user) {
    if (err) {
      return next(err);
    }

    if (!user) {
      return next(new Error('Not found.'));
    }

    request.user = user;
    return next();
  });
});


text:
import os
from terrarium import makeTile

path = '../data/B'

if not os.path.exists(path):
    os.makedirs(path)

makeTile(path, 82, 198, 9, True)


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

type Meta struct {
	Next    int
	NextUrl string `json:"next_url"`
	Total   int
}

type DeployBot struct {
	Config *Config
}

func (d *DeployBot) getRawContent(url string) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func (d *DeployBot) getContent(url string) ([]byte, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("https://%s.deploybot.com/api/v1/%s", d.Config.Domain, url), nil)
	req.Header.Add("X-Api-Token", d.Config.Token)
	if err != nil {
		return nil, err
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func (d *DeployBot) postContent(url string, post_body string) ([]byte, error) {
	req, err := http.NewRequest("POST", fmt.Sprintf("https://%s.deploybot.com/api/v1/%s", d.Config.Domain, url), ioutil.NopCloser(strings.NewReader(post_body)))
	req.Header.Add("X-Api-Token", d.Config.Token)
	if err != nil {
		return nil, err
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func (d *DeployBot) fetch(path string, v interface{}) error {
	content, err := d.getContent(path)
	if err != nil {
		return err
	}
	return json.Unmarshal(content, v)
}

func (d *DeployBot) GetRepositories() (*Repositories, error) {
	repositories := new(Repositories)
	err := d.fetch("repositories", repositories)
	if err != nil {
		return nil, err
	}
	return repositories, err
}

func (d *DeployBot) GetRepository(id int) (*Repository, error) {
	repository := new(Repository)
	err := d.fetch(fmt.Sprintf("repositories/%d", id), repository)
	if err != nil {
		return nil, err
	}
	return repository, err
}

func (d *DeployBot) GetEnvironments() (*Environments, error) {
	environments := new(Environments)
	err := d.fetch("environments", environments)
	if err != nil {
		return nil, err
	}
	return environments, err
}

func (d *DeployBot) GetEnvironmentsByRepository(repositoryId int) (*Environments, error) {
	environments := new(Environments)
	err := d.fetch(fmt.Sprintf("environments?repository_id=%d", repositoryId), environments)
	if err != nil {
		return nil, err
	}
	return environments, err
}

func (d *DeployBot) GetEnvironment(id int) (*Environment, error) {
	environment := new(Environment)
	err := d.fetch(fmt.Sprintf("environments/%d", id), environment)
	if err != nil {
		return nil, err
	}
	return environment, err
}

func (d *DeployBot) GetDeploymentsByRepository(repositoryId int) (*Deployments, error) {
	deployments := new(Deployments)
	err := d.fetch(fmt.Sprintf("repository_id=%d", repositoryId), deployments)
	if err != nil {
		return nil, err
	}
	return deployments, err
}

func (d *DeployBot) GetDeploymentsByEnvironment(environmentId int) (*Deployments, error) {
	deployments := new(Deployments)
	err := d.fetch(fmt.Sprintf("deployments?environment_id=%d", environmentId), deployments)
	if err != nil {
		return nil, err
	}
	return deployments, err
}

func (d *DeployBot) GetDeployment(id int) (*Deployment, error) {
	deployment := new(Deployment)
	err := d.fetch(fmt.Sprintf("deployments/%d", id), deployment)
	if err != nil {
		return nil, err
	}
	return deployment, err
}

func (d *DeployBot) TriggerDeployment(settings DeploymentSetting) (*Deployment, error) {
	body, _ := json.Marshal(settings)
	content, err := d.postContent("deployments", string(body))
	if err != nil {
		return nil, err
	}
	var deployment Deployment
	err = json.Unmarshal(content, &deployment)
	if err != nil {
		return nil, err
	}

	return &deployment, err
}

func (d *DeployBot) GetUsers() (*Users, error) {
	users := new(Users)
	err := d.fetch("users", users)
	if err != nil {
		return nil, err
	}
	return users, err
}

func (d *DeployBot) GetUser(id int) (*User, error) {
	user := new(User)
	err := d.fetch(fmt.Sprintf("users/%d", id), user)
	if err != nil {
		return nil, err
	}
	return user, err
}

func (d *DeployBot) GetServers() (*Servers, error) {
	servers := new(Servers)
	err := d.fetch("servers", servers)
	if err != nil {
		return nil, err
	}
	return servers, err
}

func (d *DeployBot) GetServersByEnvironment(environmentId int) (*Servers, error) {
	servers := new(Servers)
	err := d.fetch(fmt.Sprintf("servers?environment_id=%d", environmentId), servers)
	if err != nil {
		return nil, err
	}
	return servers, err
}

func (d *DeployBot) GetServersByRepository(repositoryId int) (*Servers, error) {
	servers := new(Servers)
	err := d.fetch(fmt.Sprintf("servers?repository_id=%d", repositoryId), servers)
	if err != nil {
		return nil, err
	}
	return servers, err
}

func (d *DeployBot) GetServer(id int) (*Server, error) {
	server := new(Server)
	err := d.fetch(fmt.Sprintf("servers/%d", id), server)
	if err != nil {
		return nil, err
	}
	return server, err
}

func (d *DeployBot) Refresh(repository *Repository) error {
	content, err := d.getRawContent(repository.RefreshWebhookUrl)
	if err != nil {
		return err
	}
	fmt.Println(string(content))
	return nil
}


text:
namespace engiX
{
    class D3dGeneratedMeshNode : public SceneNode
    {
    public:
        typedef std::vector<D3D11Vertex_PositionColored> VertexList;
        typedef std::vector<UINT> IndexList;

        D3dGeneratedMeshNode(_In_ ActorID actorId, _In_ const GeometryGenerator::MeshData& mesh, _In_ Color3 color, _In_ GameScene* pScene);
        ~D3dGeneratedMeshNode();

        HRESULT OnPreRender();
        HRESULT OnConstruct();
        void OnRender();
        ID3D11Buffer* VertextBuffer() { return m_pVertexBuffer; }
        ID3D11Buffer* IndexBuffer() { return m_pIndexBuffer; }
        size_t VertexCount() const { return m_vertices.size(); }
        size_t IndexCount() const { return m_indices.size(); }
        bool RenderWireframe() const { return m_rasterizeDesc.FillMode == D3D11_FILL_WIREFRAME; }
        bool RenderBackface() const { return m_rasterizeDesc.CullMode != D3D11_CULL_BACK; }

    protected:
        VertexList m_vertices;
        IndexList m_indices;
        D3dShader m_shader;
        ID3D11Buffer* m_pVertexBuffer;
        ID3D11Buffer* m_pIndexBuffer;
        D3D11_RASTERIZER_DESC m_rasterizeDesc;
        ID3D11RasterizerState* m_pRasterizeState;
    };
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container"
    android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="com.iangclifton.androidessentials.AsyncActivity" tools:ignore="MergeRootFrame" />


text:
module Logical
  module Naf
    module JobStatuses
      class Errored

        def self.all(conditions)
          <<-SQL
            (
              SELECT
                j.*, null AS "historical_job_id"
              FROM
                "#{::Naf.schema_name}"."historical_jobs" AS j
              WHERE
                j.finished_at IS NOT NULL AND
                (j.exit_status > 0 OR
                j.request_to_terminate = true)
                #{conditions}
              ORDER BY
                finished_at desc
            )
          SQL
        end

      end
    end
  end
end


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>IConvertTo Members</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Documentation - Microsoft .NET Framework 4.0

IConvertTo Members

        IConvertTo overview

Public Instance Methods

CanConvertTo	 Returns whether this converter can convert the object to the specified type

ConvertTo	 Converts the given value object to the specified type, using the arguments

See Also

        IConvertTo Interface | log4net.Util.TypeConverters Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="IConvertTo interface">
        </param>
        <param name="Keyword" value="log4net.Util.TypeConverters.IConvertTo interface">
        </param>
        <param name="Keyword" value="IConvertTo interface, all members">
        </param>
      </object>

          Copyright 2004-2011 The Apache Software Foundation.