text:
from __future__ import division

from itertools import product

from collections import namedtuple

import numpy as np

from pgmpy.extern import tabulate
from pgmpy.extern import six
from pgmpy.extern.six.moves import map, range, reduce, zip
from pgmpy.utils import StateNameInit, StateNameDecorator

State = namedtuple('State', ['var', 'state'])

class DiscreteFactor(object):
    """
    Base class for DiscreteFactor.

    Public Methods
    --------------
    assignment(index)
    get_cardinality(variable)
    marginalize([variable_list])
    normalize()
    product(*DiscreteFactor)
    reduce([variable_values_list])
    """

    @StateNameInit()
    def __init__(self, variables, cardinality, values):
        """
        Initialize a factor class.

        Defined above, we have the following mapping from variable
        assignments to the index of the row vector in the value field:

        +-----+-----+-----+-------------------+
        |  x1 |  x2 |  x3 |    phi(x1, x2, x3)|
        +-----+-----+-----+-------------------+
        | x1_0| x2_0| x3_0|     phi.value(0)  |
        +-----+-----+-----+-------------------+
        | x1_0| x2_0| x3_1|     phi.value(1)  |
        +-----+-----+-----+-------------------+
        | x1_0| x2_1| x3_0|     phi.value(2)  |
        +-----+-----+-----+-------------------+
        | x1_0| x2_1| x3_1|     phi.value(3)  |
        +-----+-----+-----+-------------------+
        | x1_1| x2_0| x3_0|     phi.value(4)  |
        +-----+-----+-----+-------------------+
        | x1_1| x2_0| x3_1|     phi.value(5)  |
        +-----+-----+-----+-------------------+
        | x1_1| x2_1| x3_0|     phi.value(6)  |
        +-----+-----+-----+-------------------+
        | x1_1| x2_1| x3_1|     phi.value(7)  |
        +-----+-----+-----+-------------------+

        Parameters
        ----------
        variables: list, array-like
            List of variables in the scope of the factor.

        cardinality: list, array_like
            List of cardinalities of each variable. `cardinality` array must have a value
            corresponding to each variable in `variables`.

        values: list, array_like
            List of values of factor.
            A DiscreteFactor's values are stored in a row vector in the value
            using an ordering such that the left-most variables as defined in
            `variables` cycle through their values the fastest.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 2, 2], np.ones(8))
        >>> phi
        <DiscreteFactor representing phi(x1:2, x2:2, x3:2) at 0x7f8188fcaa90>
        >>> print(phi)
        +------+------+------+-----------------+
        | x1   | x2   | x3   |   phi(x1,x2,x3) |
        |------+------+------+-----------------|
        | x1_0 | x2_0 | x3_0 |          1.0000 |
        | x1_0 | x2_0 | x3_1 |          1.0000 |
        | x1_0 | x2_1 | x3_0 |          1.0000 |
        | x1_0 | x2_1 | x3_1 |          1.0000 |
        | x1_1 | x2_0 | x3_0 |          1.0000 |
        | x1_1 | x2_0 | x3_1 |          1.0000 |
        | x1_1 | x2_1 | x3_0 |          1.0000 |
        | x1_1 | x2_1 | x3_1 |          1.0000 |
        +------+------+------+-----------------+
        """
        if isinstance(variables, six.string_types):
            raise TypeError("Variables: Expected type list or array like, got string")

        values = np.array(values, dtype=float)

        if len(cardinality) != len(variables):
            raise ValueError("Number of elements in cardinality must be equal to number of variables")

        if values.size != np.product(cardinality):
            raise ValueError("Values array must be of size: {size}".format(size=np.product(cardinality)))

        if len(set(variables)) != len(variables):
            raise ValueError("Variable names cannot be same")

        self.variables = list(variables)
        self.cardinality = np.array(cardinality, dtype=int)
        self.values = values.reshape(self.cardinality)

    def scope(self):
        """
        Returns the scope of the factor.

        Returns
        -------
        list: List of variable names in the scope of the factor.

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], np.ones(12))
        >>> phi.scope()
        ['x1', 'x2', 'x3']
        """
        return self.variables

    def get_cardinality(self, variables):
        """
        Returns cardinality of a given variable

        Parameters
        ----------
        variables: list, array-like
                A list of variable names.

        Returns
        -------
        dict: Dictionary of the form {variable: variable_cardinality}

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi.get_cardinality(['x1'])
        {'x1': 2}
        >>> phi.get_cardinality(['x1', 'x2'])
        {'x1': 2, 'x2': 3}
        """
        if isinstance(variables, six.string_types):
            raise TypeError("variables: Expected type list or array-like, got type str")

        if not all([var in self.variables for var in variables]):
            raise ValueError("Variable not in scope")

        return {var: self.cardinality[self.variables.index(var)] for var in variables}

    @StateNameDecorator(argument=None, return_val=True)
    def assignment(self, index):
        """
        Returns a list of assignments for the corresponding index.

        Parameters
        ----------
        index: list, array-like
            List of indices whose assignment is to be computed

        Returns
        -------
        list: Returns a list of full assignments of all the variables of the factor.

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['diff', 'intel'], [2, 2], np.ones(4))
        >>> phi.assignment([1, 2])
        [[('diff', 0), ('intel', 1)], [('diff', 1), ('intel', 0)]]
        """
        index = np.array(index)

        max_possible_index = np.prod(self.cardinality) - 1
        if not all(i <= max_possible_index for i in index):
            raise IndexError("Index greater than max possible index")

        assignments = np.zeros((len(index), len(self.scope())), dtype=np.int)
        rev_card = self.cardinality[::-1]
        for i, card in enumerate(rev_card):
            assignments[:, i] = index % card
            index = index // card

        assignments = assignments[:, ::-1]

        return [[(key, val) for key, val in zip(self.variables, values)] for values in assignments]

    def identity_factor(self):
        """
        Returns the identity factor.

        Def: The identity factor of a factor has the same scope and cardinality as the original factor,
             but the values for all the assignments is 1. When the identity factor is multiplied with
             the factor it returns the factor itself.

        Returns
        -------
        DiscreteFactor: The identity factor.

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi_identity = phi.identity_factor()
        >>> phi_identity.variables
        ['x1', 'x2', 'x3']
        >>> phi_identity.values
        array([[[ 1.,  1.],
                [ 1.,  1.],
                [ 1.,  1.]],

               [[ 1.,  1.],
                [ 1.,  1.],
                [ 1.,  1.]]])
        """
        return DiscreteFactor(self.variables, self.cardinality, np.ones(self.values.size))

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

        Parameters
        ----------
        variables: list, array-like
            List of variables over which to marginalize.

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

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

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi.marginalize(['x1', 'x3'])
        >>> phi.values
        array([ 14.,  22.,  30.])
        >>> phi.variables
        ['x2']
        """

        if isinstance(variables, six.string_types):
            raise TypeError("variables: Expected type list or array-like, got type str")

        phi = self if inplace else self.copy()

        for var in variables:
            if var not in phi.variables:
                raise ValueError("{var} not in scope.".format(var=var))

        var_indexes = [phi.variables.index(var) for var in variables]

        index_to_keep = sorted(set(range(len(self.variables))) - set(var_indexes))
        phi.variables = [phi.variables[index] for index in index_to_keep]
        phi.cardinality = phi.cardinality[index_to_keep]

        phi.values = np.sum(phi.values, axis=tuple(var_indexes))

        if not inplace:
            return phi

    def maximize(self, variables, inplace=True):
        """
        Maximizes the factor with respect to `variables`.

        Parameters
        ----------
        variables: list, array-like
            List of variables with respect to which factor is to be maximized

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

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

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [3, 2, 2], [0.25, 0.35, 0.08, 0.16, 0.05, 0.07,
        ...                                              0.00, 0.00, 0.15, 0.21, 0.09, 0.18])
        >>> phi.variables
        ['x1','x2','x3']
        >>> phi.maximize(['x2'])
        >>> phi.variables
        ['x1', 'x3']
        >>> phi.cardinality
        array([3, 2])
        >>> phi.values
        array([[ 0.25,  0.35],
               [ 0.05,  0.07],
               [ 0.15,  0.21]])
        """
        if isinstance(variables, six.string_types):
            raise TypeError("variables: Expected type list or array-like, got type str")

        phi = self if inplace else self.copy()

        for var in variables:
            if var not in phi.variables:
                raise ValueError("{var} not in scope.".format(var=var))

        var_indexes = [phi.variables.index(var) for var in variables]

        index_to_keep = sorted(set(range(len(self.variables))) - set(var_indexes))
        phi.variables = [phi.variables[index] for index in index_to_keep]
        phi.cardinality = phi.cardinality[index_to_keep]

        phi.values = np.max(phi.values, axis=tuple(var_indexes))

        if not inplace:
            return phi

    def normalize(self, inplace=True):
        """
        Normalizes the values of factor so that they sum to 1.

        Parameters
        ----------
        inplace: boolean
            If inplace=True it will modify the factor itself, else would return
            a new factor

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

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi.values
        array([[[ 0,  1],
                [ 2,  3],
                [ 4,  5]],

               [[ 6,  7],
                [ 8,  9],
                [10, 11]]])
        >>> phi.normalize()
        >>> phi.variables
        ['x1', 'x2', 'x3']
        >>> phi.cardinality
        array([2, 3, 2])
        >>> phi.values
        array([[[ 0.        ,  0.01515152],
                [ 0.03030303,  0.04545455],
                [ 0.06060606,  0.07575758]],

               [[ 0.09090909,  0.10606061],
                [ 0.12121212,  0.13636364],
                [ 0.15151515,  0.16666667]]])

        """
        phi = self if inplace else self.copy()

        phi.values = phi.values / phi.values.sum()

        if not inplace:
            return phi

    @StateNameDecorator(argument='values', return_val=None)
    def reduce(self, values, inplace=True):
        """
        Reduces the factor to the context of given variable values.

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

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

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

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi.reduce([('x1', 0), ('x2', 0)])
        >>> phi.variables
        ['x3']
        >>> phi.cardinality
        array([2])
        >>> phi.values
        array([0., 1.])
        """
        if isinstance(values, six.string_types):
            raise TypeError("values: Expected type list or array-like, got type str")

        if (any(isinstance(value, six.string_types) for value in values) or
                not all(isinstance(state, (int, np.integer)) for var, state in values)):
            raise TypeError("values: must contain tuples or array-like elements of the form "
                            "(hashable object, type int)")

        phi = self if inplace else self.copy()

        var_index_to_del = []
        slice_ = [slice(None)] * len(self.variables)
        for var, state in values:
            var_index = phi.variables.index(var)
            slice_[var_index] = state
            var_index_to_del.append(var_index)

        var_index_to_keep = sorted(set(range(len(phi.variables))) - set(var_index_to_del))
        # set difference is not gaurenteed to maintain ordering
        phi.variables = [phi.variables[index] for index in var_index_to_keep]
        phi.cardinality = phi.cardinality[var_index_to_keep]
        phi.values = phi.values[tuple(slice_)]

        if not inplace:
            return phi

    def sum(self, phi1, inplace=True):
        """
        DiscreteFactor sum with `phi1`.

        Parameters
        ----------
        phi1: `DiscreteFactor` instance.
            DiscreteFactor to be added.

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

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

        Example
        -------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi2 = DiscreteFactor(['x3', 'x4', 'x1'], [2, 2, 2], range(8))
        >>> phi1.sum(phi2, inplace=True)
        >>> phi1.variables
        ['x1', 'x2', 'x3', 'x4']
        >>> phi1.cardinality
        array([2, 3, 2, 2])
        >>> phi1.values
        array([[[[ 0,  0],
                 [ 4,  6]],

                [[ 0,  4],
                 [12, 18]],

                [[ 0,  8],
                 [20, 30]]],

               [[[ 6, 18],
                 [35, 49]],

                [[ 8, 24],
                 [45, 63]],

                [[10, 30],
                 [55, 77]]]])
        """
        phi = self if inplace else self.copy()
        if isinstance(phi1, (int, float)):
            phi.values += phi1
        else:
            phi1 = phi1.copy()

            # modifying phi to add new variables
            extra_vars = set(phi1.variables) - set(phi.variables)
            if extra_vars:
                slice_ = [slice(None)] * len(phi.variables)
                slice_.extend([np.newaxis] * len(extra_vars))
                phi.values = phi.values[slice_]

                phi.variables.extend(extra_vars)

                new_var_card = phi1.get_cardinality(extra_vars)
                phi.cardinality = np.append(phi.cardinality, [new_var_card[var] for var in extra_vars])

            # modifying phi1 to add new variables
            extra_vars = set(phi.variables) - set(phi1.variables)
            if extra_vars:
                slice_ = [slice(None)] * len(phi1.variables)
                slice_.extend([np.newaxis] * len(extra_vars))
                phi1.values = phi1.values[slice_]

                phi1.variables.extend(extra_vars)
                # No need to modify cardinality as we don't need it.

            # rearranging the axes of phi1 to match phi
            for axis in range(phi.values.ndim):
                exchange_index = phi1.variables.index(phi.variables[axis])
                phi1.variables[axis], phi1.variables[exchange_index] = phi1.variables[exchange_index], \
                    phi1.variables[axis]
                phi1.values = phi1.values.swapaxes(axis, exchange_index)

            phi.values = phi.values + phi1.values

        if not inplace:
            return phi

    def product(self, phi1, inplace=True):
        """
        DiscreteFactor product with `phi1`.

        Parameters
        ----------
        phi1: `DiscreteFactor` instance
            DiscreteFactor to be multiplied.

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

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

        Example
        -------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi2 = DiscreteFactor(['x3', 'x4', 'x1'], [2, 2, 2], range(8))
        >>> phi1.product(phi2, inplace=True)
        >>> phi1.variables
        ['x1', 'x2', 'x3', 'x4']
        >>> phi1.cardinality
        array([2, 3, 2, 2])
        >>> phi1.values
        array([[[[ 0,  0],
                 [ 4,  6]],

                [[ 0,  4],
                 [12, 18]],

                [[ 0,  8],
                 [20, 30]]],

               [[[ 6, 18],
                 [35, 49]],

                [[ 8, 24],
                 [45, 63]],

                [[10, 30],
                 [55, 77]]]]
        """
        phi = self if inplace else self.copy()
        if isinstance(phi1, (int, float)):
            phi.values *= phi1
        else:
            phi1 = phi1.copy()

            # modifying phi to add new variables
            extra_vars = set(phi1.variables) - set(phi.variables)
            if extra_vars:
                slice_ = [slice(None)] * len(phi.variables)
                slice_.extend([np.newaxis] * len(extra_vars))
                phi.values = phi.values[slice_]

                phi.variables.extend(extra_vars)

                new_var_card = phi1.get_cardinality(extra_vars)
                phi.cardinality = np.append(phi.cardinality, [new_var_card[var] for var in extra_vars])

            # modifying phi1 to add new variables
            extra_vars = set(phi.variables) - set(phi1.variables)
            if extra_vars:
                slice_ = [slice(None)] * len(phi1.variables)
                slice_.extend([np.newaxis] * len(extra_vars))
                phi1.values = phi1.values[slice_]

                phi1.variables.extend(extra_vars)
                # No need to modify cardinality as we don't need it.

            # rearranging the axes of phi1 to match phi
            for axis in range(phi.values.ndim):
                exchange_index = phi1.variables.index(phi.variables[axis])
                phi1.variables[axis], phi1.variables[exchange_index] = phi1.variables[exchange_index], \
                    phi1.variables[axis]
                phi1.values = phi1.values.swapaxes(axis, exchange_index)

            phi.values = phi.values * phi1.values

        if not inplace:
            return phi

    def divide(self, phi1, inplace=True):
        """
        DiscreteFactor division by `phi1`.

        Parameters
        ----------
        phi1 : `DiscreteFactor` instance
            The denominator for division.

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

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

        Examples
        --------
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
        >>> phi2 = DiscreteFactor(['x3', 'x1'], [2, 2], range(1, 5)])
        >>> phi1.divide(phi2)
        >>> phi1.variables
        ['x1', 'x2', 'x3']
        >>> phi1.cardinality
        array([2, 3, 2])
        >>> phi1.values
        array([[[ 0.        ,  0.33333333],
                [ 2.        ,  1.        ],
                [ 4.        ,  1.66666667]],

               [[ 3.        ,  1.75      ],
                [ 4.        ,  2.25      ],
                [ 5.        ,  2.75      ]]])
        """
        phi = self if inplace else self.copy()
        phi1 = phi1.copy()

        if set(phi1.variables) - set(phi.variables):
            raise ValueError("Scope of divisor should be a subset of dividend")

        # Adding extra variables in phi1.
        extra_vars = set(phi.variables) - set(phi1.variables)
        if extra_vars:
            slice_ = [slice(None)] * len(phi1.variables)
            slice_.extend([np.newaxis] * len(extra_vars))
            phi1.values = phi1.values[slice_]

            phi1.variables.extend(extra_vars)

        # Rearranging the axes of phi1 to match phi
        for axis in range(phi.values.ndim):
            exchange_index = phi1.variables.index(phi.variables[axis])
            phi1.variables[axis], phi1.variables[exchange_index] = phi1.variables[exchange_index], phi1.variables[axis]
            phi1.values = phi1.values.swapaxes(axis, exchange_index)

        phi.values = phi.values / phi1.values

        # If factor division 0/0 = 0 but is undefined for x/0. In pgmpy we are using
        # np.inf to represent x/0 cases.
        phi.values[np.isnan(phi.values)] = 0

        if not inplace:
            return phi

    def copy(self):
        """
        Returns a copy of the factor.

        Returns
        -------
        DiscreteFactor: copy of the factor

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.factors import DiscreteFactor
        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 3], np.arange(18))
        >>> phi_copy = phi.copy()
        >>> phi_copy.variables
        ['x1', 'x2', 'x3']
        >>> phi_copy.cardinality
        array([2, 3, 3])
        >>> phi_copy.values
        array([[[ 0,  1,  2],
                [ 3,  4,  5],
                [ 6,  7,  8]],

               [[ 9, 10, 11],
                [12, 13, 14],
                [15, 16, 17]]])
        """
        # not creating a new copy of self.values and self.cardinality
        # because __init__ methods does that.
        return DiscreteFactor(self.scope(), self.cardinality, self.values)

    def __str__(self):
        if six.PY2:
            return self._str(phi_or_p='phi', tablefmt="psql")
        else:
            return self._str(phi_or_p='phi')

    def _str(self, phi_or_p="phi", tablefmt="fancy_grid", print_state_names=True):
        """
        Generate the string from `__str__` method.

        Parameters
        ----------
        phi_or_p: 'phi' | 'p'
                'phi': When used for Factors.
                  'p': When used for CPDs.
        print_state_names: boolean
                If True, the user defined state names are displayed.
        """
        string_header = list(map(lambda x: six.text_type(x), self.scope()))
        string_header.append('{phi_or_p}({variables})'.format(phi_or_p=phi_or_p,
                                                              variables=','.join(string_header)))

        value_index = 0
        factor_table = []
        for prob in product(*[range(card) for card in self.cardinality]):
            if self.state_names and print_state_names:
                prob_list = ["{var}({state})".format(
                    var=list(self.variables)[i], state=self.state_names[list(
                        self.variables)[i]][prob[i]])
                             for i in range(len(self.variables))]
            else:
                prob_list = ["{s}_{d}".format(s=list(self.variables)[i], d=prob[i])
                             for i in range(len(self.variables))]

            prob_list.append(self.values.ravel()[value_index])
            factor_table.append(prob_list)
            value_index += 1

        return tabulate(factor_table, headers=string_header, tablefmt=tablefmt, floatfmt=".4f")

    def __repr__(self):
        var_card = ", ".join(['{var}:{card}'.format(var=var, card=card)
                              for var, card in zip(self.variables, self.cardinality)])
        return "<DiscreteFactor representing phi({var_card}) at {address}>".format(address=hex(id(self)), var_card=var_card)

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

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

    def __add__(self, other):
        return self.sum(other, inplace=False)

    def __radd__(self, other):
        return self.__add__(other)

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

    __div__ = __truediv__

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

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

        else:
            phi = other.copy()
            for axis in range(self.values.ndim):
                exchange_index = phi.variables.index(self.variables[axis])
                phi.variables[axis], phi.variables[exchange_index] = (phi.variables[exchange_index],
                                                                      phi.variables[axis])
                phi.cardinality[axis], phi.cardinality[exchange_index] = (phi.cardinality[exchange_index],
                                                                          phi.cardinality[axis])
                phi.values = phi.values.swapaxes(axis, exchange_index)

            if phi.values.shape != self.values.shape:
                return False
            elif not np.allclose(phi.values, self.values):
                return False
            elif not all(self.cardinality == phi.cardinality):
                return False
            else:
                return True

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        variable_hashes = [hash(variable) for variable in self.variables]
        sorted_var_hashes = sorted(variable_hashes)
        phi = self.copy()
        for axis in range(phi.values.ndim):
            exchange_index = variable_hashes.index(sorted_var_hashes[axis])
            variable_hashes[axis], variable_hashes[exchange_index] = (variable_hashes[exchange_index],
                                                                      variable_hashes[axis])
            phi.cardinality[axis], phi.cardinality[exchange_index] = (phi.cardinality[exchange_index],
                                                                      phi.cardinality[axis])
            phi.values = phi.values.swapaxes(axis, exchange_index)
        return hash(str(sorted_var_hashes) + str(phi.values) + str(phi.cardinality))

def factor_product(*args):
    """
    Returns factor product over `args`.

    Parameters
    ----------
    args: `DiscreteFactor` instances.
        factors to be multiplied

    Returns
    -------
    DiscreteFactor: `DiscreteFactor` representing factor product over all the `DiscreteFactor` instances in args.

    Examples
    --------
    >>> from pgmpy.factors import DiscreteFactor, factor_product
    >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
    >>> phi2 = DiscreteFactor(['x3', 'x4', 'x1'], [2, 2, 2], range(8))
    >>> phi = factor_product(phi1, phi2)
    >>> phi.variables
    ['x1', 'x2', 'x3', 'x4']
    >>> phi.cardinality
    array([2, 3, 2, 2])
    >>> phi.values
    array([[[[ 0,  0],
             [ 4,  6]],

            [[ 0,  4],
             [12, 18]],

            [[ 0,  8],
             [20, 30]]],

           [[[ 6, 18],
             [35, 49]],

            [[ 8, 24],
             [45, 63]],

            [[10, 30],
             [55, 77]]]])
    """
    if not all(isinstance(phi, DiscreteFactor) for phi in args):
        raise TypeError("Arguments must be factors")
    return reduce(lambda phi1, phi2: phi1 * phi2, args)

def factor_divide(phi1, phi2):
    """
    Returns `DiscreteFactor` representing `phi1 / phi2`.

    Parameters
    ----------
    phi1: Factor
        The Dividend.

    phi2: Factor
        The Divisor.

    Returns
    -------
    DiscreteFactor: `DiscreteFactor` representing factor division `phi1 / phi2`.

    Examples
    --------
    >>> from pgmpy.factors import DiscreteFactor, factor_divide
    >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))
    >>> phi2 = DiscreteFactor(['x3', 'x1'], [2, 2], range(1, 5))
    >>> phi = factor_divide(phi1, phi2)
    >>> phi.variables
    ['x1', 'x2', 'x3']
    >>> phi.cardinality
    array([2, 3, 2])
    >>> phi.values
    array([[[ 0.        ,  0.33333333],
            [ 2.        ,  1.        ],
            [ 4.        ,  1.66666667]],

           [[ 3.        ,  1.75      ],
            [ 4.        ,  2.25      ],
            [ 5.        ,  2.75      ]]])
    """
    if not isinstance(phi1, DiscreteFactor) or not isinstance(phi2, DiscreteFactor):
        raise TypeError("phi1 and phi2 should be factors instances")
    return phi1.divide(phi2, inplace=False)


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace BoletoNet
{
    #region Enumerado

    public enum EnumEspecieDocumento_BankBoston
    {
        DuplicataMercantil,
        DuplicataServico,
        NotaSeguro,
        ReciboEscolar,
        ReciboAssociacao,
        ReciboCondominio,
        NotaDebito,
        Outros,
    }

    #endregion

    public class EspecieDocumento_BankBoston: AbstractEspecieDocumento, IEspecieDocumento
    {
        #region Construtores

		public EspecieDocumento_BankBoston()
		{
			try
			{
			}
			catch (Exception ex)
			{
                throw new Exception("Erro ao carregar objeto", ex);
			}
		}

        public EspecieDocumento_BankBoston(string codigo)
        {
            try
            {
                this.carregar(codigo);
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao carregar objeto", ex);
            }
        }

		#endregion

        #region Metodos Privados

        public string getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston especie)
        {
            switch (especie)
            {
                case EnumEspecieDocumento_BankBoston.DuplicataMercantil: return "1";
                case EnumEspecieDocumento_BankBoston.DuplicataServico: return "2";
                case EnumEspecieDocumento_BankBoston.NotaSeguro: return "3";
                case EnumEspecieDocumento_BankBoston.ReciboEscolar: return "4";
                case EnumEspecieDocumento_BankBoston.ReciboAssociacao: return "5";
                case EnumEspecieDocumento_BankBoston.ReciboCondominio: return "6";
                case EnumEspecieDocumento_BankBoston.NotaDebito: return "7";
                case EnumEspecieDocumento_BankBoston.Outros: return "8";
                default: return"0";

            }
        }

        public EnumEspecieDocumento_BankBoston getEnumEspecieByCodigo(string codigo)
        {
            switch (codigo)
            {
                case "2": return EnumEspecieDocumento_BankBoston.DuplicataMercantil;
                case "1": return EnumEspecieDocumento_BankBoston.DuplicataServico;
                case "3": return EnumEspecieDocumento_BankBoston.NotaSeguro;
                case "4": return EnumEspecieDocumento_BankBoston.ReciboEscolar;
                case "5": return EnumEspecieDocumento_BankBoston.ReciboAssociacao;
                case "6": return EnumEspecieDocumento_BankBoston.ReciboCondominio;
                case "7": return EnumEspecieDocumento_BankBoston.NotaDebito;
                case "8": return EnumEspecieDocumento_BankBoston.Outros;
                default: return EnumEspecieDocumento_BankBoston.Outros;
            }
        }

        private void carregar(string Codigo)
        {
            try
            {
                this.Banco = new Banco_BankBoston();

                switch (getEnumEspecieByCodigo(Codigo))
                {
                    case  EnumEspecieDocumento_BankBoston.DuplicataMercantil:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.DuplicataMercantil);
                        this.Sigla = "DM";
                        this.Especie = "Duplicata mercantil";
                        break;
                    case EnumEspecieDocumento_BankBoston.DuplicataServico:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.DuplicataServico);
                        this.Sigla = "DS";
                        this.Especie = "Duplicata de serviço";
                        break;
                    case EnumEspecieDocumento_BankBoston.NotaSeguro:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.NotaSeguro);
                        this.Sigla = "NS";
                        this.Especie = "Nota de seguro";
                        break;
                    case EnumEspecieDocumento_BankBoston.ReciboEscolar:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.ReciboEscolar);
                        this.Sigla = "RE";
                        this.Especie = "Reciboescolar";
                        break;
                    case EnumEspecieDocumento_BankBoston.ReciboAssociacao:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.ReciboAssociacao);
                        this.Sigla = "RS";
                        this.Especie = "Recibo Associação";
                        break;
                    case EnumEspecieDocumento_BankBoston.ReciboCondominio:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.ReciboCondominio);
                        this.Sigla = "RC";
                        this.Especie = "Contrato";
                        break;
                    case EnumEspecieDocumento_BankBoston.NotaDebito:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.NotaDebito);
                        this.Sigla = "ND";
                        this.Especie = "Nota débito";
                        break;
                    case EnumEspecieDocumento_BankBoston.Outros:
                        this.Codigo = getCodigoEspecieByEnum(EnumEspecieDocumento_BankBoston.Outros);
                        this.Sigla = "OT";
                        this.Especie = "Outros";
                        break;
                    default:
                        this.Codigo = "0";
                        this.Especie = "( Selecione )";
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao carregar objeto", ex);
            }
        }

        public static EspeciesDocumento CarregaTodas()
        {
            EspeciesDocumento especiesDocumento = new EspeciesDocumento();
            EspecieDocumento_BankBoston ed = new EspecieDocumento_BankBoston();
            foreach (EnumEspecieDocumento_BankBoston item in Enum.GetValues(typeof(EnumEspecieDocumento_BankBoston)))
                especiesDocumento.Add(new EspecieDocumento_BankBoston(ed.getCodigoEspecieByEnum(item)));

            return especiesDocumento;
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'core_ext/hash/deep_merge'
require 'core_ext/hash/deep_symbolize_keys'
require 'core_ext/object/false'
require 'erb'
require 'rbconfig'

require 'travis/build/addons'
require 'travis/build/appliances'
require 'travis/build/errors'
require 'travis/build/git'
require 'travis/build/helpers'
require 'travis/build/stages'

require 'travis/build/script/android'
require 'travis/build/script/c'
require 'travis/build/script/clojure'
require 'travis/build/script/cpp'
require 'travis/build/script/crystal'
require 'travis/build/script/csharp'
require 'travis/build/script/d'
require 'travis/build/script/dart'
require 'travis/build/script/erlang'
require 'travis/build/script/elixir'
require 'travis/build/script/go'
require 'travis/build/script/groovy'
require 'travis/build/script/generic'
require 'travis/build/script/haskell'
require 'travis/build/script/haxe'
require 'travis/build/script/julia'
require 'travis/build/script/nix'
require 'travis/build/script/node_js'
require 'travis/build/script/objective_c'
require 'travis/build/script/perl'
require 'travis/build/script/perl6'
require 'travis/build/script/php'
require 'travis/build/script/pure_java'
require 'travis/build/script/python'
require 'travis/build/script/r'
require 'travis/build/script/ruby'
require 'travis/build/script/rust'
require 'travis/build/script/scala'
require 'travis/build/script/smalltalk'
require 'travis/build/script/shared/directory_cache'

module Travis
  module Build
    class Script
      TEMPLATES_PATH = File.expand_path('../templates', __FILE__)
      DEFAULTS = {}

      class << self
        def defaults
          Git::DEFAULTS.merge(self::DEFAULTS)
        end
      end

      include Module.new { Stages::STAGES.map(&:name).flatten.each { |stage| define_method(stage) {} } }
      include Appliances, DirectoryCache, Deprecation, Template

      attr_reader :sh, :data, :options, :validator, :addons, :stages
      attr_accessor :setup_cache_has_run_for

      def initialize(data)
        @data = Data.new({ config: self.class.defaults }.deep_merge(data.deep_symbolize_keys))
        @options = {}

        @sh = Shell::Builder.new
        @addons = Addons.new(self, sh, self.data, config)
        @stages = Stages.new(self, sh, config)
        @setup_cache_has_run_for = {}
      end

      def compile(ignore_taint = false)
        Shell.generate(sexp, ignore_taint)
      rescue Travis::Shell::Generator::TaintedOutput => to
        raise to
      rescue Exception => e
        event = Travis::Build.config.sentry_dsn.empty? ? nil : Raven.capture_exception(e)

        unless Travis::Build.config.dump_backtrace.empty?
          Travis::Build.logger.error(e)
          Travis::Build.logger.error(e.backtrace)
        end

        show_compile_error_msg(e, event)
      end

      def sexp
        run
        sh.to_sexp
      end

      def cache_slug_keys
        plain_env_vars = Array((config[:env] || []).dup).delete_if {|env| env.start_with? 'SECURE '}

        [
          'cache',
          config[:os],
          config[:dist],
          config[:osx_image],
          OpenSSL::Digest::SHA256.hexdigest(plain_env_vars.sort.join('='))
        ]
      end

      def cache_slug
        cache_slug_keys.compact.join('-')
      end

      def archive_url_for(bucket, version, lang = self.class.name.split('::').last.downcase, ext = 'bz2')
        file_name = "#{[lang, version].compact.join("-")}.tar.#{ext}"
        sh.if "$(uname) = 'Linux'" do
          sh.raw "travis_host_os=$(lsb_release -is | tr 'A-Z' 'a-z')"
          sh.raw "travis_rel_version=$(lsb_release -rs)"
        end
        sh.elif "$(uname) = 'Darwin'" do
          sh.raw "travis_host_os=osx"
          sh.raw "travis_rel=$(sw_vers -productVersion)"
          sh.raw "travis_rel_version=${travis_rel%*.*}"
        end
        "archive_url=https://s3.amazonaws.com/#{bucket}/binaries/${travis_host_os}/${travis_rel_version}/$(uname -m)/#{file_name}"
      end

      def debug_build_via_api?
        ! data.debug_options.empty?
      end

      private

        def config
          data.config
        end

        def debug
          if debug_build_via_api?
            sh.echo "Debug build initiated by #{data.debug_options[:created_by]}", ansi: :yellow
            if debug_quiet?
              sh.raw "travis_debug --quiet"
            else
              sh.raw "travis_debug"
            end

            sh.echo
            sh.echo "All remaining steps, including caching and deploy, will be skipped.", ansi: :yellow
          end
        end

        def run
          stages.run if apply :validate
          sh.raw template('footer.sh')
          # apply :deprecations
        end

        def header
          sh.raw(
            template(
              'header.sh',
              build_dir: BUILD_DIR,
              app_host: app_host,
              internal_ruby_regex: Travis::Build.config.internal_ruby_regex.untaint,
              root: '/',
              home: HOME_DIR
            ), pos: 0
          )
        end

        def configure
          apply :set_x
          apply :show_system_info
          apply :rm_riak_source
          apply :fix_rwky_redis
          apply :wait_for_network
          apply :update_apt_keys
          apply :fix_hhvm_source
          apply :update_mongo_arch
          apply :fix_container_based_trusty
          apply :fix_sudo_enabled_trusty
          apply :update_glibc
          apply :update_libssl
          apply :clean_up_path
          apply :fix_resolv_conf
          apply :fix_etc_hosts
          apply :fix_mvn_settings_xml
          apply :no_ipv6_localhost
          apply :fix_etc_mavenrc
          apply :etc_hosts_pinning
          apply :fix_wwdr_certificate
          apply :put_localhost_first
          apply :home_paths
          apply :disable_initramfs
          apply :disable_ssh_roaming
          apply :debug_tools
          apply :npm_registry
          apply :rvm_use
          apply :rm_oraclejdk8_symlink
          apply :enable_i386
          apply :update_rubygems
          apply :ensure_path_components
          apply :redefine_curl
          apply :nonblock_pipe
          apply :apt_get_update
        end

        def setup_filter
          apply :no_world_writable_dirs
          apply :setup_filter
        end

        def checkout
          apply :checkout
        end

        def export
          apply :env
        end

        def prepare
          apply :services
          apply :fix_ps4 # TODO if this is to fix an rvm issue (as the specs say) then should this go to Rvm instead?
        end

        def disable_sudo
          apply :disable_sudo
        end

        def reset_state
          if debug_build_via_api?
            raise "Debug payload does not contain 'previous_state' value." unless previous_state = data.debug_options[:previous_state]

            sh.echo
            sh.echo "This is a debug build. The build result is reset to its previous value, \\\"#{previous_state}\\\".", ansi: :yellow

            case previous_state
            when "passed"
              sh.export 'TRAVIS_TEST_RESULT', '0', echo: false
            when "failed"
              sh.export 'TRAVIS_TEST_RESULT', '1', echo: false
            when "errored"
              sh.raw 'travis_terminate 2'
            end
          end
        end

        def config_env_vars
          @config_env_vars ||= Build::Env::Config.new(data, config)
          Array(@config_env_vars.data[:env])
        end

        def host_os
          case RbConfig::CONFIG["host_os"]
          when /^(?i:linux)/
            '$(lsb_release -is | tr "A-Z" "a-z")'
          when /^(?i:darwin)/
            'osx'
          end
        end

        def rel_version
          case RbConfig::CONFIG["host_os"]
          when /^(?i:linux)/
            '$(lsb_release -rs)'
          when /^(?i:darwin)/
            '${$(sw_vers -productVersion)%*.*}'
          end
        end

        def debug_quiet?
          debug_build_via_api? && data.debug_options[:quiet]
        end

        def debug_enabled?
          Travis::Build.config.enable_debug_tools == '1'
        end

        def app_host
          @app_host ||= Travis::Build.config.app_host.to_s.strip.untaint
        end

        def error_message_ary(exception, event)
          if event
            contact_msg = ", or contact us at support@travis-ci.com"
            if event.id
              contact_msg << " with the error ID: #{event.id}"
            end
          else
            contact_msg = ""
          end

          if exception.is_a? Travis::Build::CompilationError
            msg = [
              exception.message
            ]
            doc_path = exception.doc_path
          else
            msg = [
              "Unfortunately, we do not know much about this error."
            ]
            doc_path = ''
          end

          [
            "",
            "There was an error in the .travis.yml file from which we could not recover.\n",
            *msg,
            "",
            "Please review https://docs.travis-ci.com#{doc_path}#{contact_msg}"
          ]
        end

        def show_compile_error_msg(exception, event)
          @sh = Shell::Builder.new
          error_message_ary(exception, event).each { |line| sh.raw "echo -e \"\033[31;1m#{line}\033[0m\"" }
          sh.raw "exit 2"
          Shell.generate(sh.to_sexp)
        end
    end
  end
end


text:
module Runner
  class ConcurrencyHandlerError < StandardError
  end

  module Concurrency
    module Helper
      def concurrency(method = Runner.default_spawn_method, options = {}, &block)
        # Make sure we can constantize handler.
        # Raise handler error if flag is set
        # else fall back to default fork
        begin
          klass = "Runner::Concurrency::Concurrency#{method.to_s.classify}".constantize
        rescue => e
          raise Runner::ConcurrencyHandlerError, "Unable to load class Concurrency#{method.to_s.classify} which was specified as concurrency handler.\n#{e}" if Runner.raise_on_concurrency_handler_error
          # Fall back to default fork
          klass = ConcurrencyFork
        end

        concurrency_handler = klass.new(options)
        concurrency_handler.run(&block)
      end
    end

    class ConcurrencyThread
      def run(&block)
        Thread.abort_on_exception = Runner.thread_abort_on_exception
        thread = Thread.new do
          block.call
        end
        thread.run
      end
    end

    class ConcurrencyFork
      def run(&block)
        child = fork do
          block.call
        end

        Process.detach(child)
      end
    end

    class ConcurrencyYield
      def run(&block)
        block.call
      end
    end
  end
end


text:
'use strict'

module.exports = Object.freeze({
  beforeValidate (user, options) {
    // console.log(`[hook] beforeValidate called: ${JSON.stringify(user)}`)
  },
  afterValidate (user, options) {
    // console.log(`[hook] afterValidate called: ${JSON.stringify(user)}`)
  },
  beforeCreate (user, options) {
    // console.log(`[hook] beforeCreate called: ${JSON.stringify(user)}`)
  },
  beforeDestroy (user, options) {
    // console.log(`[hook] beforeDestroy called: ${JSON.stringify(user)}`)
  },
  beforeUpdate (user, options) {
    // console.log(`[hook] beforeUpdate called: ${JSON.stringify(user)}`)
  },
  afterCreate (user, options) {
    // console.log(`[hook] afterCreate called: ${JSON.stringify(user)}`)
  },
  afterDestroy (user, options) {
    // console.log(`[hook] afterDestroy called: ${JSON.stringify(user)}`)
  },
  afterUpdate (user, options) {
    // console.log(`[hook] afterUpdate called: ${JSON.stringify(user)}`)
  }
})


text:
package com.indexer.hellotaxi.app.pref;

/**
 * Created by yemonkyaw on 6/19/14.
 */

import android.content.SharedPreferences;

public class StringPreference {
  private final SharedPreferences msharedPreferences;
  private final String mkey;
  private final String defaultValue;

  public StringPreference(SharedPreferences sharedPreferences, String key) {
    this(sharedPreferences, key, null);
  }

  public StringPreference(SharedPreferences preferences, String key, String defaultValue) {
    this.msharedPreferences = preferences;
    this.mkey = key;
    this.defaultValue = defaultValue;
  }

  public SharedPreferences getMsharedPreferences() {
    return msharedPreferences;
  }

  public String getMkey() {
    return mkey;
  }

  public String getDefaultValue() {
    return defaultValue;
  }
}


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page

class FlowRevisionList(ListResource):

    def __init__(self, version, sid):
        """
        Initialize the FlowRevisionList

        :param Version version: Version that contains the resource
        :param sid: The unique string that identifies the resource

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList
        """
        super(FlowRevisionList, self).__init__(version)

        # Path Solution
        self._solution = {'sid': sid, }
        self._uri = '/Flows/{sid}/Revisions'.format(**self._solution)

    def stream(self, limit=None, page_size=None):
        """
        Streams FlowRevisionInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param int limit: Upper limit for the number of records to return. stream()
                          guarantees to never return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, stream() will attempt to read the
                              limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance]
        """
        limits = self._version.read_limits(limit, page_size)

        page = self.page(page_size=limits['page_size'], )

        return self._version.stream(page, limits['limit'])

    def list(self, limit=None, page_size=None):
        """
        Lists FlowRevisionInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param int limit: Upper limit for the number of records to return. list() guarantees
                          never to return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, list() will attempt to read the limit
                              with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance]
        """
        return list(self.stream(limit=limit, page_size=page_size, ))

    def page(self, page_token=values.unset, page_number=values.unset,
             page_size=values.unset):
        """
        Retrieve a single page of FlowRevisionInstance records from the API.
        Request is executed immediately

        :param str page_token: PageToken provided by the API
        :param int page_number: Page Number, this value is simply for client state
        :param int page_size: Number of records to return, defaults to 50

        :returns: Page of FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage
        """
        data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })

        response = self._version.page(method='GET', uri=self._uri, params=data, )

        return FlowRevisionPage(self._version, response, self._solution)

    def get_page(self, target_url):
        """
        Retrieve a specific page of FlowRevisionInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage
        """
        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return FlowRevisionPage(self._version, response, self._solution)

    def get(self, revision):
        """
        Constructs a FlowRevisionContext

        :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        """
        return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, )

    def __call__(self, revision):
        """
        Constructs a FlowRevisionContext

        :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        """
        return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Studio.V2.FlowRevisionList>'

class FlowRevisionPage(Page):

    def __init__(self, version, response, solution):
        """
        Initialize the FlowRevisionPage

        :param Version version: Version that contains the resource
        :param Response response: Response from the API
        :param sid: The unique string that identifies the resource

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage
        """
        super(FlowRevisionPage, self).__init__(version, response)

        # Path Solution
        self._solution = solution

    def get_instance(self, payload):
        """
        Build an instance of FlowRevisionInstance

        :param dict payload: Payload response from the API

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance
        """
        return FlowRevisionInstance(self._version, payload, sid=self._solution['sid'], )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Studio.V2.FlowRevisionPage>'

class FlowRevisionContext(InstanceContext):

    def __init__(self, version, sid, revision):
        """
        Initialize the FlowRevisionContext

        :param Version version: Version that contains the resource
        :param sid: The SID that identifies the resource to fetch
        :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        """
        super(FlowRevisionContext, self).__init__(version)

        # Path Solution
        self._solution = {'sid': sid, 'revision': revision, }
        self._uri = '/Flows/{sid}/Revisions/{revision}'.format(**self._solution)

    def fetch(self):
        """
        Fetch the FlowRevisionInstance

        :returns: The fetched FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance
        """
        payload = self._version.fetch(method='GET', uri=self._uri, )

        return FlowRevisionInstance(
            self._version,
            payload,
            sid=self._solution['sid'],
            revision=self._solution['revision'],
        )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Studio.V2.FlowRevisionContext {}>'.format(context)

class FlowRevisionInstance(InstanceResource):

    class Status(object):
        DRAFT = "draft"
        PUBLISHED = "published"

    def __init__(self, version, payload, sid, revision=None):
        """
        Initialize the FlowRevisionInstance

        :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance
        """
        super(FlowRevisionInstance, self).__init__(version)

        # Marshaled Properties
        self._properties = {
            'sid': payload.get('sid'),
            'account_sid': payload.get('account_sid'),
            'friendly_name': payload.get('friendly_name'),
            'definition': payload.get('definition'),
            'status': payload.get('status'),
            'revision': deserialize.integer(payload.get('revision')),
            'commit_message': payload.get('commit_message'),
            'valid': payload.get('valid'),
            'errors': payload.get('errors'),
            'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
            'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
            'url': payload.get('url'),
        }

        # Context
        self._context = None
        self._solution = {'sid': sid, 'revision': revision or self._properties['revision'], }

    @property
    def _proxy(self):
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions.  All instance actions are proxied to the context

        :returns: FlowRevisionContext for this FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext
        """
        if self._context is None:
            self._context = FlowRevisionContext(
                self._version,
                sid=self._solution['sid'],
                revision=self._solution['revision'],
            )
        return self._context

    @property
    def sid(self):
        """
        :returns: The unique string that identifies the resource
        :rtype: unicode
        """
        return self._properties['sid']

    @property
    def account_sid(self):
        """
        :returns: The SID of the Account that created the resource
        :rtype: unicode
        """
        return self._properties['account_sid']

    @property
    def friendly_name(self):
        """
        :returns: The string that you assigned to describe the Flow
        :rtype: unicode
        """
        return self._properties['friendly_name']

    @property
    def definition(self):
        """
        :returns: JSON representation of flow definition
        :rtype: dict
        """
        return self._properties['definition']

    @property
    def status(self):
        """
        :returns: The status of the Flow
        :rtype: FlowRevisionInstance.Status
        """
        return self._properties['status']

    @property
    def revision(self):
        """
        :returns: The latest revision number of the Flow's definition
        :rtype: unicode
        """
        return self._properties['revision']

    @property
    def commit_message(self):
        """
        :returns: Description of change made in the revision
        :rtype: unicode
        """
        return self._properties['commit_message']

    @property
    def valid(self):
        """
        :returns: Boolean if the flow definition is valid
        :rtype: bool
        """
        return self._properties['valid']

    @property
    def errors(self):
        """
        :returns: List of error in the flow definition
        :rtype: list[dict]
        """
        return self._properties['errors']

    @property
    def date_created(self):
        """
        :returns: The ISO 8601 date and time in GMT when the resource was created
        :rtype: datetime
        """
        return self._properties['date_created']

    @property
    def date_updated(self):
        """
        :returns: The ISO 8601 date and time in GMT when the resource was last updated
        :rtype: datetime
        """
        return self._properties['date_updated']

    @property
    def url(self):
        """
        :returns: The absolute URL of the resource
        :rtype: unicode
        """
        return self._properties['url']

    def fetch(self):
        """
        Fetch the FlowRevisionInstance

        :returns: The fetched FlowRevisionInstance
        :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance
        """
        return self._proxy.fetch()

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Studio.V2.FlowRevisionInstance {}>'.format(context)


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>Welcome Username</title>

      Please enter your name : <input type="text" @keyup.enter="username">

      Welcome again : {{ welcomeValue }}
      <button @click="deleteUser">{{deleteUserText}}</button>
      {{deleteUserState}}


text:
<?php
namespace Sphec;

/**
 * The control class for building specifications.
 *
 * @author Kirk Bowers
 */
abstract class Runnable {
  // All member variables variables are prefixed with an underscore to protect against
  // name clashes when a consumer of this utility creates "local" member variables in
  // the scope of an example (during `before` blocks).
  public    $_label;
  protected $_block;
  protected $_indent;
  protected $_parent;

  public    $_expector;

  function __construct($label, $block, $indent = '', $parent = NULL) {
    $this->_label = $label;
    $this->_block = $block;
    $this->_indent = $indent;
    $this->_parent = $parent;
  }

  public function get_full_name() {
    $result = '';
    if ($this->_parent) {
      $result = $this->_parent->get_full_name() . ' ';
    }

    return $result . $this->_label;
  }

  abstract public function run();
}


text:
"""Compute modes of a rectangular Si strip waveguide on top of oxide. Note that \
you should only pay attention, here, to the guided modes, which are the modes \
whose frequency falls under the light line -- that is, frequency < beta / 1.45, \
where 1.45 is the SiO2 index.

Since there's no special lengthscale here, you can just
use microns. In general, if you use units of x, the frequencies
output are equivalent to x/lambda# so here, the frequencies will be
output as um/lambda, e.g. 1.5um would correspond to the frequency
1/1.5 = 0.6667.

"""
import pickle
from functools import partial
from typing import Dict

import meep as mp
import numpy as np
from meep import mpb

from gdsfactory.pdk import get_modes_path
from gdsfactory.simulation.disable_print import disable_print, enable_print
from gdsfactory.simulation.get_sparameters_path import get_kwargs_hash
from gdsfactory.simulation.modes.get_mode_solver_coupler import get_mode_solver_coupler
from gdsfactory.simulation.modes.get_mode_solver_rib import get_mode_solver_rib
from gdsfactory.simulation.modes.types import Mode

mpb.Verbosity(0)

def find_modes_waveguide(
    tol: float = 1e-6,
    wavelength: float = 1.55,
    mode_number: int = 1,
    parity=mp.NO_PARITY,
    cache: bool = True,
    overwrite: bool = False,
    single_waveguide: bool = True,
    **kwargs,
) -> Dict[int, Mode]:
    """Computes mode effective and group index for a rectangular waveguide.

    single_waveguide=True

    ::

          __________________________
          |
          |
          |         width
          |     <---------->
          |      ___________   _ _ _
          |     |           |       |
        sz|_____|  ncore    |_______|
          |                         | wg_thickness
          |slab_thickness    nslab  |
          |_________________________|
          |
          |        nclad
          |__________________________
          <------------------------>
                        sy

    single_waveguide=False

    ::

          _____________________________________________________
          |
          |
          |         widths[0]                 widths[1]
          |     <---------->     gaps[0]    <---------->
          |      ___________ <-------------> ___________      _
          |     |           |               |           |     |
        sz|_____|  ncore    |_______________|           |_____|
          |                                                   | wg_thickness
          |slab_thickness        nslab                        |
          |___________________________________________________|
          |
          |<--->                                         <--->
          |ymargin               nclad                   ymargin
          |____________________________________________________
          <--------------------------------------------------->
                                   sy

    Args:
        mode_solver: function that returns mpb.ModeSolver.
        tol: tolerance when finding modes.
        wavelength: wavelength in um.
        mode_number: mode order of the first mode.
        parity: mp.ODD_Y mp.EVEN_X for TE, mp.EVEN_Y for TM.
        cache: directory path to cache modes. None disables the file cache.
        overwrite: forces simulating again.
        kwargs: waveguide settings.

    Keyword Args:
        wg_width: wg_width (um).
        wg_thickness: wg height (um).
        slab_thickness: thickness for the waveguide slab.
        ncore: core material refractive index.
        nclad: clad material refractive index.
        sy: simulation region width (um).
        sz: simulation region height (um).
        resolution: resolution (pixels/um).
        nmodes: number of modes to compute.

    Keyword Args:
        wg_width: wg_width (um) for the symmetric case.
        gap: for the case of only two waveguides.
        wg_widths: list or tuple of waveguide widths.
        gaps: list or tuple of waveguide gaps.
        wg_thickness: wg height (um).
        slab_thickness: thickness for the waveguide slab.
        ncore: core material refractive index.
        nclad: clad material refractive index.
        nslab: Optional slab material refractive index. Defaults to ncore.
        ymargin: margin in y.
        sz: simulation region thickness (um).
        resolution: resolution (pixels/um).
        nmodes: number of modes.
        sidewall_angles: waveguide sidewall angle (radians),
            tapers from wg_width at top of slab, upwards, to top of waveguide.

    Returns: Dict[mode_number, Mode]

    compute mode_number lowest frequencies as a function of k. Also display
    "parities", i.e. whether the mode is symmetric or anti_symmetric
    through the y=0 and z=0 planes.
    mode_solver.run(mpb.display_yparities, mpb.display_zparities)

    Above, we outputted the dispersion relation: frequency (omega) as a
    function of wavevector kx (beta). Alternatively, you can compute
    beta for a given omega -- for example, you might want to find the
    modes and wavevectors at a fixed wavelength of 1.55 microns. You
    can do that using the find_k function:

    """
    modes = {}
    mode_solver = (
        get_mode_solver_rib(**kwargs)
        if single_waveguide
        else get_mode_solver_coupler(**kwargs)
    )
    nmodes = mode_solver.nmodes
    omega = 1 / wavelength

    h = get_kwargs_hash(
        wavelength=wavelength,
        parity=parity,
        single_waveguide=single_waveguide,
        **kwargs,
    )

    if cache:
        cache_path = get_modes_path()
        cache_path.mkdir(exist_ok=True, parents=True)
        filepath = cache_path / f"{h}_{mode_number}.pkl"

        if filepath.exists() and not overwrite:
            for index, i in enumerate(range(mode_number, mode_number + nmodes)):
                filepath = cache_path / f"{h}_{index}.pkl"
                mode = pickle.loads(filepath.read_bytes())
                modes[i] = mode
            return modes

    # Output the x component of the Poynting vector for mode_number bands at omega
    disable_print()
    k = mode_solver.find_k(
        parity,
        omega,
        mode_number,
        mode_number + nmodes,
        mp.Vector3(1),
        tol,
        omega * 2.02,
        omega * 0.01,
        omega * 10,
        # mpb.output_poynting_x,
        mpb.display_yparities,
        mpb.display_group_velocities,
    )
    enable_print()
    neff = np.array(k) * wavelength

    # vg = mode_solver.compute_group_velocities()
    # vg = vg[0]
    # ng = 1 / np.array(vg)

    for index, i in enumerate(range(mode_number, mode_number + nmodes)):
        Ei = mode_solver.get_efield(i)
        Hi = mode_solver.get_hfield(i)
        y_num = np.shape(Ei[:, :, 0, 0])[0]
        z_num = np.shape(Ei[:, :, 0, 0])[1]

        modes[i] = Mode(
            mode_number=i,
            neff=neff[index],
            wavelength=wavelength,
            E=Ei,
            H=Hi,
            eps=mode_solver.get_epsilon().T,
            y=np.linspace(
                -1 * mode_solver.info["sy"] / 2.0,
                mode_solver.info["sy"] / 2.0,
                y_num,
            ),
            z=np.linspace(
                -1 * mode_solver.info["sz"] / 2.0,
                mode_solver.info["sz"] / 2.0,
                z_num,
            ),
        )
        if cache:
            filepath = cache_path / f"{h}_{index}.pkl"
            filepath.write_bytes(pickle.dumps(modes[i]))

    return modes

find_modes_coupler = partial(find_modes_waveguide, single_waveguide=False)

if __name__ == "__main__":
    m = find_modes_waveguide(wg_width=0.5)
    print(m)

    m1 = m[1]

    # print(np.shape(m1.y))
    # print(np.shape(m1.z))
    # print(np.shape(m1.E[:, :, 0, 1]))

    # tol: float = 1e-6
    # wavelength: float = 1.55
    # mode_number: int = 1
    # parity = mp.NO_PARITY
    # mode_solver = get_mode_solver_rib()
    # nmodes = mode_solver.nmodes
    # omega = 1 / wavelength

    # # Output the x component of the Poynting vector for mode_number bands at omega
    # k = mode_solver.find_k(
    #     parity,
    #     omega,
    #     mode_number,
    #     mode_number + nmodes,
    #     mp.Vector3(1),
    #     tol,
    #     omega * 2.02,
    #     omega * 0.01,
    #     omega * 10,
    #     mpb.output_poynting_x,
    #     mpb.display_yparities,
    #     mpb.display_group_velocities,
    # )
    # enable_print()
    # vg = mode_solver.compute_group_velocities()
    # vg0 = vg[0]
    # neff = np.array(k) * wavelength
    # ng = 1 / np.array(vg0)

    # modes = {
    #     i: Mode(
    #         mode_number=i,
    #         neff=neff[index],
    #         solver=mode_solver,
    #         wavelength=wavelength,
    #     )
    #     for index, i in enumerate(range(mode_number, mode_number + nmodes))
    # }


text:
package net.bubble.persistence.framework.engine;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import net.bubble.persistence.framework.BubbleEntity;
import net.bubble.persistence.framework.mybatis.config.EnableBubbleRepositories;
import net.bubble.persistence.framework.mybatis.plugin.interceptor.PaginationInterceptor;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author shiwen_xiao<xiaosw@msn.cn>
 * @since 2015年2月1日
 */
@Configuration
@EnableTransactionManagement
@EnableBubbleRepositories(basePackages = "net.bubble.persistence.**.repositories")
public class BubbleMyBatisEngine implements ResourceLoaderAware {

	private ResourceLoader resourceLoader;

	private DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	private String dialect;

	public void setDialect(String dialect) {
		this.dialect = dialect;
	}

	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(dataSource);
		sessionFactory.setTypeAliasesPackage("net.bubble.persistence.**.entities");
		sessionFactory.setTypeAliasesSuperType(BubbleEntity.class);
		sessionFactory.setMapperLocations(getResources("classpath*:config/mybatis/mapper/**/*Mapper.xml"));
		Interceptor[] interceptors = new Interceptor[1];
		interceptors[0] = paginationInterceptor();
		sessionFactory.setPlugins(interceptors);
		Properties properties = new Properties();
		properties.setProperty("dialect", dialect);
		sessionFactory.setConfigurationProperties(properties);
		return sessionFactory.getObject();
	}

	@Bean
	@Scope("prototype")
	public SqlSessionTemplate sqlSessionTemplate() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory(), ExecutorType.BATCH);
	}

	@Bean
	public Interceptor paginationInterceptor() {
		return new PaginationInterceptor();
	}

	/*@Bean
	MapperScannerConfigurer mapperScannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setSqlSessionTemplateBeanName("sqlSessionTemplate");
		mapperScannerConfigurer.setBasePackage("net.bubble.persistence.**.repositories");
		mapperScannerConfigurer.setMarkerInterface(MybatisBubbleRepository.class);
		return mapperScannerConfigurer;
	}*/

	private Resource[] getResources(String packagePath) throws IOException {
		ResourcePatternResolver resourceResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
		Resource[] resources = resourceResolver.getResources(packagePath);
		return resources;
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

}


text:
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.

Write a function to determine if the starting player can guarantee a win.

### Example:
```
Input: s = "++++"
Output: true
Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+".
```
### Follow up:
Derive your algorithm's runtime complexity.

## Solution
The recursion is I make a move and give my opponent the string after flipping and he can't make any move.

To improve and save any unnecessary recusive calls, memorize the pattern, canWin result in a map. 48ms -> 8ms in C++

#GOOGL

#Backtracking #Dynamic Programming

#Similar questions [#293e](../p293e/README.md) [#294m](../p294m/README.md)


text:
require 'spec_helper'

describe "Welcome" do

  let(:user) { FactoryGirl.create(:user) }

  before do
    login_as user
  end

  it "includes a welcome message" do
    get root_path
    response.body.should include "Welcome to Cartoque"
  end

  it "includes stats about applications" do
    Application.create!(name: "app-01")
    Application.create!(name: "app-02")
    get root_path
    response.body.should include "2 applications"
  end
end


text:
package de.uni_stuttgart.iaas.bpel_d.algorithm.analysis;

/**
 * Analyze expressions
 * @author Sebastian Breier
 *
 */
public class Expression {

	/* -- currently not used --
	public static boolean containsNot(Expression exp) {
		// FIXME: No idea what conditions/expressions look like right now
		System.err.println(">containsNot STUB: exp: " + exp);
		return false;
	}
	*/

}


text:
describe RuboCop::Cop::Lint::EnsureReturn do
  subject(:cop) { described_class.new }

  it 'registers an offense for return in ensure' do
    inspect_source(cop, <<-END.strip_indent)
      begin
        something
      ensure
        file.close
        return
      end
    END
    expect(cop.offenses.size).to eq(1)
  end

  it 'does not register an offense for return outside ensure' do
    inspect_source(cop, <<-END.strip_indent)
      begin
        something
        return
      ensure
        file.close
      end
    END
    expect(cop.offenses).to be_empty
  end

  it 'does not check when ensure block has no body' do
    expect do
      inspect_source(cop, <<-END.strip_indent)
        begin
          something
        ensure
        end
      END
    end.not_to raise_exception
  end
end


text:
title: Telerik.Web.UI.TreeListExpandCollapseEventArgs
page_title: Telerik.Web.UI.TreeListExpandCollapseEventArgs
description: Telerik.Web.UI.TreeListExpandCollapseEventArgs
---

# Telerik.Web.UI.TreeListExpandCollapseEventArgs

A base class representing the event args passed when Telerik.Web.UI.RadTreeList fires the ItemCommand event with an ExpandCollapse command.

## Inheritance Hierarchy

* System.Object
* System.EventArgs
* System.Web.UI.WebControls.CommandEventArgs
* Telerik.Web.UI.TreeListCommandEventArgs
* Telerik.Web.UI.TreeListExpandCollapseEventArgs

## Properties

###  Item `TreeListItem`

The item in which the command was triggered.

###  EventSource `Object`

Gets the control which was responsible for firing the event.

###  Canceled `Boolean`

Gets or sets a value indicating whether the current command is cancelled.

## Methods

###  ExecuteCommand

Forces the control to execute the ExpandCollapse command.

#### Parameters

#### source `System.Object`

The RadTreeList object.

#### Returns

`System.Void`

###  ExecuteCommand

Forces the execution of the command that triggered the event.

#### Parameters

#### source `System.Object`

The owner RadTreeList object

#### Returns

`System.Void`


text:
<?php

namespace FTR\WebBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * FTR\WebBundle\Entity\Building_type
 *
 * @ORM\Table(name="building_type")
 * @ORM\Entity(repositoryClass="FTR\WebBundle\Repository\Building_typeRepository")
 */
class Building_type
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $type_name
     *
     * @ORM\Column(name="type_name", type="string", length=255)
     */
    private $type_name;

    /**
     * @var boolean $deleted
     *
     * @ORM\Column(name="deleted", type="boolean", nullable="true")
     */
    private $deleted;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set type_name
     *
     * @param string $typeName
     */
    public function setTypeName($typeName)
    {
        $this->type_name = $typeName;
    }

    /**
     * Get type_name
     *
     * @return string
     */
    public function getTypeName()
    {
        return $this->type_name;
    }

    /**
     * Set deleted
     *
     * @param boolean $deleted
     */
    public function setDeleted($deleted)
    {
        $this->deleted = $deleted;
    }

    /**
     * Get deleted
     *
     * @return boolean
     */
    public function getDeleted()
    {
        return $this->deleted;
    }
}


text:
// <copyright file="SqlServerEventStoreTests.cs" company="dddlib contributors">
//  Copyright (c) dddlib contributors. All rights reserved.
// </copyright>

namespace dddlib.Persistence.Tests.Integration
{
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Transactions;
    using dddlib.Persistence.SqlServer;
    using dddlib.Tests.Sdk;
    using FluentAssertions;
    using Xunit;

    public class SqlServerEventStoreTests : Integration.Database
    {
        public SqlServerEventStoreTests(SqlServerFixture fixture)
            : base(fixture)
        {
        }

        [Fact]
        public void TrySaveSingleEvent()
        {
            // arrange
            var eventStore = new SqlServerEventStore(this.ConnectionString);
            var streamId = Guid.NewGuid();
            var events = new[]
            {
                new Event { Id = 1, Value = "One" },
            };

            string commitState;
            string actualCommitState;

            // act
            eventStore.CommitStream(streamId, events, Guid.NewGuid(), null, out commitState);
            var actualEvents = eventStore.GetStream(streamId, 0, out actualCommitState);

            // assert
            actualEvents.Count().Should().Be(1);
            actualEvents.Single().Should().BeOfType<Event>();
            actualEvents.Cast<Event>().Single().ShouldBeEquivalentTo(events[0]);
            actualCommitState.Should().Be(commitState);
        }

        [Fact]
        public void TrySaveMultipleEvents()
        {
            // arrange
            var eventStore = new SqlServerEventStore(this.ConnectionString);
            var streamId = Guid.NewGuid();
            var events = new[]
            {
                new Event { Id = 1, Value = "One" },
                new Event { Id = 2, Value = "Two" },
            };

            string commitState;
            string actualCommitState;

            // act
            eventStore.CommitStream(streamId, events, Guid.NewGuid(), null, out commitState);
            var actualEvents = eventStore.GetStream(streamId, 0, out actualCommitState);

            // assert
            actualEvents.Count().Should().Be(2);
            actualEvents.First().Should().BeOfType<Event>();
            actualEvents.Last().Should().BeOfType<Event>();
            actualEvents.Cast<Event>().First().ShouldBeEquivalentTo(events[0]);
            actualEvents.Cast<Event>().Last().ShouldBeEquivalentTo(events[1]);
            actualCommitState.Should().Be(commitState);
        }

        [Fact]
        public void TrySaveEventsInMultipleCommits()
        {
            // arrange
            var eventStore = new SqlServerEventStore(this.ConnectionString);
            var streamId = Guid.NewGuid();
            var events1 = new[] { new Event { Id = 1, Value = "One" } };
            var events2 = new[] { new Event { Id = 2, Value = "Two" } };

            string firstCommitState;
            string secondCommitState;
            string actualCommitState;

            // act
            eventStore.CommitStream(streamId, events1, Guid.NewGuid(), null, out firstCommitState);
            eventStore.CommitStream(streamId, events2, Guid.NewGuid(), firstCommitState, out secondCommitState);
            var actualEvents = eventStore.GetStream(streamId, 0, out actualCommitState);

            // assert
            actualEvents.Count().Should().Be(2);
            actualEvents.First().Should().BeOfType<Event>();
            actualEvents.Last().Should().BeOfType<Event>();
            actualEvents.Cast<Event>().First().ShouldBeEquivalentTo(events1[0]);
            actualEvents.Cast<Event>().Last().ShouldBeEquivalentTo(events2[0]);
            actualCommitState.Should().Be(secondCommitState);
        }

        [Fact]
        public void TrySaveEventsForMultipleStreams()
        {
            // arrange
            var eventStore = new SqlServerEventStore(this.ConnectionString);
            var stream1Id = Guid.NewGuid();
            var stream2Id = Guid.NewGuid();
            var events1 = new[] { new Event { Id = 1, Value = "One" } };
            var events2 = new[] { new Event { Id = 2, Value = "Two" } };

            string stream1CommitState;
            string stream2CommitState;
            string actualStream1CommitState;
            string actualStream2CommitState;

            // act
            eventStore.CommitStream(stream1Id, events1, Guid.NewGuid(), null, out stream1CommitState);
            eventStore.CommitStream(stream2Id, events2, Guid.NewGuid(), null, out stream2CommitState);
            var stream1Events = eventStore.GetStream(stream1Id, 0, out actualStream1CommitState);
            var stream2Events = eventStore.GetStream(stream2Id, 0, out actualStream2CommitState);

            // assert
            stream1Events.Count().Should().Be(1);
            stream1Events.Single().Should().BeOfType<Event>();
            stream1Events.Cast<Event>().Single().ShouldBeEquivalentTo(events1[0]);
            actualStream1CommitState.Should().Be(stream1CommitState);
            stream2Events.Count().Should().Be(1);
            stream2Events.Single().Should().BeOfType<Event>();
            stream2Events.Cast<Event>().Single().ShouldBeEquivalentTo(events2[0]);
            actualStream2CommitState.Should().Be(stream2CommitState);
        }

        [Fact]
        public void ExpectClientSideConcurrencyException()
        {
            // arrange
            var eventStore = new SqlServerEventStore(this.ConnectionString);
            var streamId = Guid.NewGuid();
            var events1 = new[] { new Event { Id = 1, Value = "One" } };
            var events2 = new[] { new Event { Id = 1, Value = "AnotherOne" } };

            string commitState;
            eventStore.CommitStream(streamId, events1, Guid.NewGuid(), null, out commitState);

            // act
            Action action = () => eventStore.CommitStream(streamId, events2, Guid.NewGuid(), null, out commitState);

            // assert
            action.ShouldThrow<ConcurrencyException>();
        }

        [Fact]
        public void ExpectServerSideConcurrencyException()
        {
            // arrange
            var eventStore = new SqlServerEventStore(this.ConnectionString);
            var streamId = Guid.NewGuid();
            var events = new[] { new Event { Id = 1, Value = "One" } };

            string commitState;

            using (new TransactionScope(TransactionScopeOption.RequiresNew))
            using (var connection = new SqlConnection(this.ConnectionString))
            using (var command = connection.CreateCommand())
            {
                command.CommandType = CommandType.Text;
                command.CommandText = @"EXEC tempdb..sp_getapplock @Resource = @StreamId, @LockMode = 'Exclusive', @LockTimeout = 1000;";
                command.Parameters.Add("@StreamId", SqlDbType.UniqueIdentifier).Value = streamId;

                // NOTE (Cameron): This will cause SQL Server to acquire the same application lock as the commit attempt below.
                connection.Open();
                command.ExecuteNonQuery();

                // act
                Action action = () => eventStore.CommitStream(streamId, events, Guid.NewGuid(), null, out commitState);

                // assert
                action.ShouldThrow<ConcurrencyException>();
            }
        }

        private class Event
        {
            public int Id { get; set; }

            public string Value { get; set; }
        }
    }
}


text:
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        return recursiveBuild(preorder, 0, preorder.size(), inorder, 0, inorder.size());
    }

private:
    TreeNode *recursiveBuild(vector<int> &preorder, int pre_b, int pre_e, vector<int> &inorder, int in_b, int in_e) {
        if (pre_b >= pre_e)
            return nullptr;
        int root_val = preorder[pre_b];
        int in_root = in_b;
        for (; in_root < in_e; in_root++) {
            if (inorder[in_root] == root_val)
                break;
        }
        int pre_left = pre_b + 1;
        int pre_right = pre_left + in_root - in_b;
        TreeNode *root = new TreeNode(root_val);
        root->left = recursiveBuild(preorder, pre_left, pre_right,
                                    inorder, in_b, in_root);
        root->right = recursiveBuild(preorder, pre_right, pre_e,
                                     inorder, in_root + 1, in_e);
        return root;
    }
};


text:
/*
 * It is advised not to edit the smartadmin_production.css
 * as this will override any changes you make in the
 * later versions of this theme.
 *
 * We advise that you use use this CSS to override
 * SmartAdmin styles.
 *
 * Rename the stylesheet to whatever your liking so it will stay
 * unique to you with each update of SmartAdmin.
 */

/*
 * INDEX
 *
 * - HTML
 * - BODY
 * - CUSTOM STYLES
 */

::-webkit-input-placeholder { color: #e4e3e3 !important; }
::-moz-placeholder { color: #e4e3e3 !important; }
:-moz-placeholder { color: #e4e3e3 !important; }
:-ms-input-placeholder { color: #e4e3e3 !important; }
input:-moz-placeholder { color: #e4e3e3 !important;  }

.strong
{
	font-weight: bold !important;
}

.required
{
	color: #f00;
}

.modal-header
{
    background: rgba(248,248,248,.9);
}

.modal-title
{
    font-weight: bold;
}

.smart-form table.dataTable .label
{
    display: inline;
    padding: .2em .6em .3em;
    font-size: 75%;
    font-weight: 700;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: .25em;
}

#dt_webmodules_method_wrapper
{
    border: 1px solid #ccc;
    margin-bottom: 20px;
}

#dt_webmodules_method_wrapper .dt-toolbar-footer
{
    padding: 7px;
}

#dt_webmodules_method_length,
#dt_webmodules_method_filter label
{
    margin: 7px;
}

#dt_webmodules_method_wrapper .dataTables_filter .input-group-addon {
    width: 16px;
    float: left;
    height: 16px;
}

fieldset#webmodules_method
{
    padding: 0px !important;
}

section.button-clone
{
    float: right !important;
    padding-left: 13px !important;
}

.row_method hr
{
    border-top: 1px solid #969696 !important;
}

fieldset#webmodules_method section
{
    padding-left: 14px;
    padding-right: 14px;
}

fieldset#webmodules_method div.row_method .row
{
    padding-left: 14px;
    padding-right: 14px;
    padding-top: 14px;
}

fieldset#webmodules_method .row_method:first-of-type
{
    border-top: 1px solid #969696 !important;
}

div.row_method:nth-child(odd)
{
    background-color: #fff;
}

div.row_method:nth-child(even)
{
    background-color: #f9f9f9;
}

fieldset#webmodules_method div.row_method .row section > .row,
fieldset#webmodules_method div.row_method .row + .row
{
    padding-top: 0px;
}

fieldset#webmodules_method .row_method:last-child
{
    border-bottom: none !important;
}

.dd3-handle
{
    width: 5px;
}

.dd3-content
{
    padding: 0px 10px 0px 0px;
}

.smart-accordion-default.panel-group .panel-title a
{
    padding: 7px 5px 7px 40px;
}

#accordion-modules.smart-accordion-default.panel-group .panel-title a
{
    padding-left: 15px !important;
}

#accordion-modules.smart-accordion-default.panel-group .panel-body ul
{
    list-style: none;
}

#accordion-modules.smart-accordion-default.panel-group .panel-body ul li
{
    padding: 4px 6px 3px 5px;
    margin-bottom: 5px;
    line-height: 23px;
}

#accordion-modules.smart-accordion-default.panel-group .panel-body ul li:hover
{
    background-color: #f9f9f9;
}

#accordion-modules.smart-accordion-default .panel-default>.panel-heading
{
    background-color: #ebebeb;
}

#accordion-modules.smart-accordion-default .panel-default>.panel-heading:hover
{
    background-color: #cacaca;
}

.dd-list .dd-list
{
    padding-left: 36px;
}

.dd3-item>button
{
    margin-left: 0px;
}

#wid-id-webmenu-index-menu-0 .smart-form #nestable ol.dd-list li.dd-item.dd3-item .dd3-content
{
    padding: 0px !important;
}


text:
% Orbits the camera around a 3D plot and writes a movie.
%
% i.kuprov@outlook.com

function write_movie(file_name)

% Open the video writer object
writerObj=VideoWriter(file_name,'MPEG-4');
open(writerObj);

% Orbit the camera
for n=1:360

    % Grab the frame
    writeVideo(writerObj,getframe(gcf));
    pause(0.05); camorbit(1,0);

end

% Close the writer object
close(writerObj);

end

% Love is [...] friendship inspired by beauty.
%
% Marcus Tullius Cicero


text:
A little addon to have good error stack traces in Firefox.

# Make it work

To have this working:

1. Get [cfx](https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/getting-started-with-cfx.html)
1. run `cfx xpi` at the root of the directory
1. Install the add-on from files (In Firefox: file -> open -> (pick the xpi file))
1. Enable the addon by clicking the checkbox in the devtools options panel
1. Open the [test/index.html](./test/index.html) file, open your console, click `run`, notice the stack trace with arguments

# Licence

[MIT](./licence)


text:
module Cinemastar
  module Client
    VERSION = "0.0.1"
  end
end


text:
!> @ingroup quick_sort_recursive_dec
!>
!> @brief
!> Run a recursive three way quick sort on a vector of double precision values.
!>
!> @details
!> Run a decending on a vector of double precision values to sort them in the specified order.The vector of intergers map is permuted in the same way that the vector vec is permuted to be sorted. It is important that map be at least as long as vec.
!>
!> @param vec
!> The vector double precision values to be sorted.
!>
!> @param map
!> Vector of intergers which is permuted in the same way that vec is permuted. If map is a vector of values 1 to N, where N is the length of vec, than, map is the map from vec's original value to vec's final value after the sort.
!>
!> @warning
!> The length of map is not checked within this subroutine. If the length of vec is larger than the length of map, than this subroutine may attempt to access elements outside of map.
!>
!> @author Arin R. Bratt
!> @date 11/07/2014
pure subroutine quick_sort_recursive_dec_map_dble(vec,map)
  ! Arguments
  double precision, intent(inout) :: vec(:)
  integer, intent(inout) :: map(:)

  ! Variables
  integer :: low
  integer :: high
  integer :: low_eq
  integer :: high_eq
  double precision :: pivot
  double precision :: temp

  ! Go to interchange sort if list is small
  if (size(vec,1) <= max_interchange_sort_size) then
     call interchange_sort_dec_map_dble(vec,map)
  else
     ! Initilize values
     low = 1
     high = size(vec,1)
     low_eq = 1
     high_eq = size(vec,1)

     ! Build pivot
     pivot = (vec(low) + vec(high)) / 2
     if ( vec(low) < vec(high)) then
        call swap(vec(low),vec(high))
        call swap(map(low),map(high))
     end if

     ! Main loop with three way partition
     do
        ! Find pivot points
        do
           low = low + 1
           if (.not. pivot < vec(low)) exit
        end do
        do
           high = high - 1
           if (.not. vec(high) < pivot .or. high == 1) exit
        end do

        ! Exit if they are on the wrong side of the pivot
        if (low >= high) exit

        ! Run main quick sort swap
        call swap(vec(low),vec(high))
        call swap(map(low),map(high))

        ! Check for if values are equal to pivot, if so swap
        if (.not. vec(high) < pivot) then
           call swap(vec(high),vec(high_eq))
           call swap(map(high),map(high_eq))
           high_eq = high_eq - 1
        end if

        if (.not. pivot < vec(low)) then
           call swap(vec(low),vec(low_eq))
           call swap(map(low),map(low_eq))
           low_eq = low_eq + 1
        end if
     end do
     high = low - 1

     ! Move equals to the middle
     do while(1 < low_eq)
        low_eq = low_eq - 1
        call swap(vec(low_eq),vec(high))
        call swap(map(low_eq),map(high))
        high = high - 1
     end do

     do while(high_eq < size(vec,1))
        high_eq = high_eq + 1
        call swap(vec(high_eq),vec(low))
        call swap(map(high_eq),map(low))
        low = low + 1
     end do

     ! Recursive calls
     if (size(vec,1) - low > high - 1) then
        if (high > 1) call quick_sort_recursive_dec_map_dble(vec(:high),map(:high))
        if (low < size(vec,1)) call quick_sort_recursive_dec_map_dble(vec(low:),map(low:))
     else
        if (low < size(vec,1)) call quick_sort_recursive_dec_map_dble(vec(low:),map(low:))
        if (high > 1) call quick_sort_recursive_dec_map_dble(vec(:high),map(:high))
     end if
  end if
end subroutine quick_sort_recursive_dec_map_dble