text:
"""
This a Random Multitone Signal Generator module. |br|

It is able to generate *N* multitone random signals according to settings
given by a user. |br|

*Examples*:
    Please go to the *examples/signals* directory for examples on how to use
    the generator. |br|

*Settings*:
    Parameters of the generator described below.

    Take a look on '__parametersDefine' function for more info on the
    parameters.

    Parameters of the generator are attributes of the class which must/can
    be set before the generator run.

    Required parameters:

    - a. **tS** (*float*): time of a signals

    - b. **fR** (*float*): signals' representation sampling frequency

    - c. **fRes** (*float*): tones frequency resolution

    Optional parameters:

    - d. **fMax** (*float*): maximum frequency present in signals [default = 0.4 * fR]

    - e. **fMin** (*float*): minimum allowed frequency present in the spectrum  [default = fRes]

    - f. **nSigs** (*int*): the number of signals to be generated  [default = 1]

    - g. **iSNR** (*float*): level of noise in signals [dB] (SNR)  [default = +int]

    - h. **iP** (*float*): requested power of signals  [default = do not regulate the power]

    - i. **vFrqs** (*Numpy array 1D*): vector with requested frequencies of tones  [default = empty]

    - j. **vAmps** (*Numpy array 1D*): vector with requested amplitudes of tones   [default = empty]

    - k. **vPhs** (*Numpy array 1D*): vector with requested phases of tones        [default = empty]

    - l. **nTones** (*int*): the number of additional tones    [default = 0]

    - m. **iMinAmp** (*float*): min amplitude of a tone present in a signal      [default = 0.1]

    - n. **iGraAmp** (*float*): gradation of a random amplitude of a tone        [default = 0.1]

    - o. **iMaxAmp** (*float*): max amplitude of a tone present in a signal      [default = 1.0]

    - p. **iMinPhs** (*float*): min allowed phase of a tone present in a signal  [default = -179 deg]

    - q. **iGraPhs** (*float*): gradation of a random phase of a tone            [default = 1 deg]

    - r. **iMaxPhs** (*float*): max allowed phase of a tone present in a signal  [default = +180 deg]

    - s. **bMute** (*int*): mute the console output from the generator [default = 0]

*Output*:
    Description of the generator output is below.
    This is the list of attributes of the generator class which are available
    after calling the 'run' method:

    - a. **mSig** (*Numpy array 2D*): Matrix with output signals

    - b. **mSigNN** (*Numpy array 2D*): Matrix with nonnoisy output signals

    - c. **nSmp** (*int*): The number of samples in the signals

    - d. **vTSig** (*Numpy array 1D*): The time vector for the generated signals (name alias vT is available)

    - e. **vP** (*Numpy array 1D*): Power of the signals

    - f. **vPNN** (*Numpy array 1D*): Power of the non noisy signals

    - g. **vPCoef** (*Numpy array 1D*): Power adjustment coefficients

    - h. **mFrqs** (*Numpy array 2D*): Frequencies of tones in the signals

    - i. **mAmps** (*Numpy array 2D*): Amplitudes of tones in the signals

    - j. **mPhs** (*Numpy array 2D*): Phases of tones in the signals

    - k. **mAmPh** (*Numpy array 2D*): Complex matrix with amplitudes/phases of tones

    - l. **fFFTR** (*float*): Signal FFT frequency resolution

*Author*:
    Jacek Pierzchlewski, Aalborg University, Denmark. <jap@es.aau.dk>

*Version*:
    0.1    | 15-MAY-2014 : * Initial version. |br|
    0.2    | 16-MAY-2014 : * Docstrings added. |br|
    0.3    | 19-MAY-2014 : * The main func. divided into smaller functions. |br|
    0.4    | 20-MAY-2014 : * Errors are served by 'raise'. |br|
    0.5    | 20-MAY-2014 : * Docstrings are added to the internal functions. |br|
    0.5r1  | 20-MAY-2014 : * Order of the internal functions was changed. |br|
    1.0    | 20-MAY-2014 : * Version 1.0 released. |br|
    1.0r1  | 21-MAY-2014 : * Error in progress printing is fixed. |br|
    1.0r2  | 21-MAY-2014 : * Error in default random amplitude is fixed. |br|
    1.0r3  | 21-MAY-2014 : * Error in progress printing (if muted) is fixed. |br|
    1.0r4  | 27-MAY-2014 : * Error in the number of given frqs is fixed. |br|
    1.0r5  | 27-MAY-2014 : * Error in the vector with signal time is fixed. |br|
    2.0    | 21-JUL-2015 : * Objectified version (2.0) |br|
    2.0r1  | 18-AUG-2015 : * Adjusted to RxCSobject v1.0 |br|
    2.1    | 02-SEP-2015 : * Max frequency in the spectrum is an optional parameter
                             printing improvements. |br|

*License*:
    BSD 2-Clause
"""

from __future__ import division
import numpy as np
import rxcs

class randMult(rxcs._RxCSobject):

    def __init__(self, *args):
        rxcs._RxCSobject.__init__(self)    # Make it a RxCS object

        self.strRxCSgroup = 'Signal generator'  # Name of group of RxCS modules
        self.strModuleName = 'Random multitone'     # Module name

        self.__parametersDefine()      # Define the parameters

    # Define parameters
    def __parametersDefine(self):

        # Time of the signal [s]
        self.paramAddMan('tS', 'Time of the signal', unit='s')
        self.paramType('tS', (int, float))
        self.paramH('tS', 0)
        self.paramL('tS', np.inf)

        # The signal representation sampling frequency [Hz]
        self.paramAddMan('fR', 'The signal representation sampling frequency', unit='Hz')
        self.paramType('fR', (int, float))
        self.paramH('fR', 0)
        self.paramL('fR', np.inf)

        # The highest possible frequency in the signal [Hz]
        self.paramAddOpt('fMax', 'The highest possible frequency in the signal', unit='Hz', default='$$fR', mul=0.4)
        self.paramType('fMax', (int, float))
        self.paramH('fMax', 0)
        self.paramL('fMax', 'fR', mul=0.5)  # Nyquist principle

        # Signal spectrum resolution [Hz]
        self.paramAddMan('fRes', 'Signal spectrum resolution', unit='Hz')
        self.paramType('fRes', (int, float))
        self.paramH('fRes', 0)
        self.paramL('fRes', np.inf)

        # The minimum frequency of additional tones
        self.paramAddOpt('fMin', 'Minimum frequency of additional tones', default='$$fRes', unit='Hz')
        self.paramType('fMin', (int, float))
        self.paramH('fMin', 0)
        self.paramLE('fMin', 'fMax')

        # The number of signals to be generated
        self.paramAddOpt('nSigs', 'The number of signals to be generated', default=1)
        self.paramType('nSigs', (int))
        self.paramH('nSigs', 0)            # The number of signals must be higher than zero
        self.paramL('nSigs', np.inf)       # ...and lower than infinity

        # Signal noise [dB]
        self.paramAddOpt('iSNR', 'Signal to noise ratio', default=np.inf, unit='dB')
        self.paramType('iSNR', (int, float))

        # Power of signals [W]
        self.paramAddOpt('iP', 'Power of signals', default=np.nan, unit='W')
        self.paramType('iP', (int, float))
        self.paramH('iP', 0)
        self.paramL('iP', np.inf)

        # Vector with given frequencies of signal cosine tones
        self.paramAddOpt('vFrqs', 'Vector with given frequencies of signal cosine tones', default=np.zeros(0), noprint=1)
        self.paramType('vFrqs', np.ndarray)
        strError = 'Frequencies in \'vFrqs\' vector must not be higher than the highest possible in the signal spectrum!'
        self.paramLE('vFrqs', 'fMax', errnote=strError)
        strError = 'Frequencies in the \'vFrqs\' must be higher than 0!'
        self.paramH('vFrqs', 0, errnote=strError)
        strError = 'Frequencies in \'vFrqs\' vector must not be lower than the lowest possible in the signal spectrum!'
        self.paramHE('vFrqs', 'fMin', errnote=strError)
        strError = 'Size of the vector with given frequencies \'vFrqs\' must be equal to size of the vectors \'vAmps\' and \'vPhs\''
        self.paramSizEq('vFrqs', 'vAmps', errnote=strError)
        self.paramSizEq('vFrqs', 'vPhs', errnote=strError)
        self.paramNDimEq('vFrqs', 1)
        strError = 'There are frequencies repeated in the \'vFrqs\' vector!'
        self.paramUnique('vFrqs', errnote=strError)
        self.NaNAllowedEl('vFrqs')

        # Vector with given amplitudes of signal cosine tones
        self.paramAddOpt('vAmps', 'Vector with given amplitudes of signal cosine tones', default=np.zeros(0), noprint=1)
        self.paramType('vAmps', np.ndarray)
        self.paramH('vAmps', 0, errnote='Amplituides of tones must be higher than 0')
        self.paramNDimEq('vAmps', 1)
        self.NaNAllowedEl('vAmps')

        # Vector with given phases of signal cosine tones content
        self.paramAddOpt('vPhs', 'Vector with given phases of signal cosine tones', default=np.zeros(0), noprint=1)
        self.paramType('vPhs', np.ndarray)
        self.paramH('vPhs', -180, errnote='Phases of tones must be higher than -180 [deg]')
        self.paramLE('vPhs', 180, errnote='Phases of tones must be lower or equal to 180 [deg]')
        self.paramNDimEq('vPhs', 1)
        self.NaNAllowedEl('vPhs')

        # The number of additional tones
        self.paramAddOpt('nTones', 'The number of additional tones', default=0)
        self.paramType('nTones', (int))
        self.paramHE('nTones', 0)

        # The boundaries for amplitudes: amplitude min value
        self.paramAddOpt('iMinAmp', 'Minimum value of random amplitudes', default=0.1, unitprefix=' ')
        self.paramType('iMinAmp', (int, float))
        self.paramH('iMinAmp', 0)
        self.paramLE('iMinAmp','iMaxAmp')

        # The boundaries for amplitudes: amplitude gradation
        self.paramAddOpt('iGraAmp', 'Gradation of value of random amplitudes', default=0.1, unitprefix=' ')
        self.paramType('iGraAmp', (int, float))
        self.paramH('iGraAmp', 0)

        # The boundaries for amplitudes: amplitude max value
        self.paramAddOpt('iMaxAmp', 'Maximum value of random amplitudes', default=1.0, unitprefix=' ')
        self.paramType('iMaxAmp', (int, float))
        self.paramH('iMaxAmp', 0)

        # The boundaries for amplitudes: phase min value
        self.paramAddOpt('iMinPhs', 'Minimum value of random phase', default=-179, unitprefix=' ')
        self.paramType('iMinPhs', (int, float))
        self.paramH('iMinPhs',-180)
        self.paramLE('iMinPhs',180)
        self.paramLE('iMinPhs','iMaxPhs')

        # The boundaries for amplitudes: phase gradation
        self.paramAddOpt('iGraPhs', 'Gradation of value of random phase', default=1, unitprefix=' ')
        self.paramType('iGraPhs', (int, float))
        self.paramH('iGraPhs', 0)

        # The boundaries for amplitudes: phase max value
        self.paramAddOpt('iMaxPhs', 'Maximum value of random phase', default=180, unitprefix=' ')
        self.paramType('iMaxPhs', (int, float))
        self.paramH('iMaxPhs',-180)
        self.paramLE('iMaxPhs',180)

        # 'Mute the output' flag
        self.paramAddOpt('bMute', 'Mute the output', noprint=1, default=0)
        self.paramType('bMute', int)           # Must be of int type
        self.paramAllowed('bMute',[0, 1])      # It can be either 1 or 0

    # Run
    def run(self):

        self.parametersCheck()         # Check if all the needed partameters are in place and are correct
        self.parametersPrint()         # Print the values of parameters

        self.engineStartsInfo()  # Info that the engine starts
        self.__engine()          # Run the engine
        self.engineStopsInfo()   # Info that the engine ends
        return self.__dict__     # Return dictionary with the parameters

    # Engine of the function
    def __engine(self):
        self._checkConf()

        # - - - - - - - - - - - - - - - - - - -
        # Signal generation starts here:

        self.mFrqsInx = self._drawFreq(self.vFrqs, self.nTones, self.fMin, self.fMax, self.nSigs, self.fRes)         # Draw frequencies of the signals
        self.mAmps = self._drawAmps(self.vAmps, self.nTones, self.nSigs, self.iMinAmp, self.iGraAmp, self.iMaxAmp)   # Draw amplitudes of the signals
        self.mPhs = self._drawPhases(self.vPhs, self.nTones, self.nSigs, self.iMinPhs, self.iGraPhs, self.iMaxPhs)   # Draw phases of the signals

        # Generate the signals by IFFT
        (mSig, self.mAmPh, self.mFrqs, self.fFFTR) = \
            self._genSigs(self.mFrqsInx, self.mAmps, self.mPhs, self.nSigs, self.tS, self.fR, self.fRes)

        # - - - - - - - - - - - - - - - - - - -

        # Adjust the signal power
        (mSig, vP, self.vPCoef, self.mAmps, self.mAmPh) = self._adjPower(mSig, self.iP, self.mAmps, self.mAmPh)

        # Add the AWGN noise to the signals
        (self.mSigNN, self.vPNN, self.mSig, self.vP) = self._addNoise(mSig, vP, self.iSNR)

        # Generate the time vector for the signal
        self.vTSig = np.arange(self.nSmp) / self.fR
        self.vT = self.vTSig   # Name alias for vTSig is vT

        return

    def _checkConf(self):
        """
        This function checks the configuration of the generator.
        """
        #----------------------------------------------------------------------
        # If the minimum frequency was not given, it is equal to the frequency resolution
        if np.isnan(self.fMin):
            self.fMin = self.fRes

        #----------------------------------------------------------------------
        # Check the lowest possible frequency in the signal vs spectrum
        # resolution
        strErr = 'The lowest possible frequency in the signal is not a multiple '
        strErr = strErr + 'of the signal spectrum resolution'
        if (round(self.fMin/self.fRes) - self.fMin/self.fRes) > 1e-15:
            raise ValueError(strErr)

        #----------------------------------------------------------------------
        # Check the highest possible frequency in the signal vs spectrum
        # resolution
        strErr = 'The highest possible frequency in the signal is not a multiple '
        strErr = strErr + 'of the signal spectrum resolution'
        if (round(self.fMax/self.fRes) - self.fMax/self.fRes) > 1e-15:
            raise ValueError(strErr)

        #----------------------------------------------------------------------
        # Check if there is a space for all the frequencies requested in
        # the signal, both given in the vFrqs vector and requested to be
        # chosen randomly

        # Compute the total number of tones in the max possible spectrum
        nSpectTones = int(self.fMax/self.fRes) - int(self.fMin/self.fRes) + 1

        nFG = self.vFrqs.size          # The number of frequencies given in the vector with frequencies
        nSigTones = nFG + self.nTones  # The total number of tones which will be present in the signal

        strErr = 'The signal spectrum consists of %d tones. ' % (nSpectTones)
        strErr = strErr + 'I can not put there %d [vFrqs] + %d [nTones] tones' \
            % (nFG, self.nTones)
        if nSpectTones < nSigTones:
            raise ValueError(strErr)

        #----------------------------------------------------------------------
        # Check if there is a frequency leackage
        self.nSmp = int(round(self.tS*self.fR))  # Calculate the number of samples in the signals
        fFFTR = self.fR/self.nSmp    # Calculate the FFT frequency resolution

        if abs(round(self.fRes/fFFTR) - self.fRes/fFFTR) > 0:
            strErr = ('Frequency leackage! Signal spectrum resolution can not be ')
            strErr = strErr + ('represented with the current signal parameters!')
            raise ValueError(strErr)

        #----------------------------------------------------------------------
        # Check the vector with given frequencies

        # Check the vector with given frequencies, if it is longer then 0
        if nFG > 0:

            # Create the vector with given and specified frequencies (not np.nan)
            vFrqs_ = self.vFrqs[np.isnan(self.vFrqs) == 0]

            # 1. check resolution of given frequencies:
            if np.abs(np.sum(np.round(vFrqs_/self.fRes) - (vFrqs_/self.fRes))) > 1e-15:
                strErr = ('A frequency given in the vFrqs vector is ')
                strErr = strErr + ('incoherent with the resolution of signal ')
                strErr = strErr + ('spectrum!\n')
                raise ValueError(strErr)

            # Do correction of possible representation errors in the vector with frequencies
            self.vFrqs = np.round(self.vFrqs/self.fRes)*self.fRes

        #----------------------------------------------------------------------
        return

    # =================================================================
    # Draw frequencies of the signals
    # =================================================================
    def _drawFreq(self, vFrqs, nTones, fMin, fMax, nSigs, fRes):
        """
        This function draws frequencies of tones for all the signals
        according to the rules specified by users,

        Args:
            vFrqs (vector):  vector with specified frequencies
            nTones (int):    the number of additional tones
            fMin (int):      the min allowed frequency in the signal spectrum
            fMax (int):      the max allowed frequency in the signal spectrum
            nSigs (int):     the number of signals to be generated
            fRes (int):      signal spectrum resolution
                             (distance between the tones in the spectrum)

        Returns:
            mFrqsInx (matrix):  matrix with frequencies of tones for all
                                the signals (one row - one signal)
                                The frequencies are represented as indices of
                                frequencies from the allowed signal spectrum.

        """

        #----------------------------------------------------------------------
        # Recalculate frequencies to indices of tones in the spectrum

        # Recalculate the vector with frequencies from frequency to index
        # of a frequency in the spectrum
        vFrqsInx = (vFrqs / fRes)

        # Create a vector with GIVEN (not nan) indices of frequencies in the
        # vFrqs vector
        vFrqsInx_ = (vFrqsInx[np.isnan(vFrqsInx) == 0]).astype(int)

        #----------------------------------------------------------------------
        # Create the vector with indices of avaialble frequencies in the spectrum

        # Create a vector with indices of all the available tones in the spectrum
        vSpecInx = np.arange(1, int(fMax/fRes) + 1)

        # Boolean vector which indicates if the frequency is free
        vFreqIsFree = np.ones(int(fMax/fRes)).astype(bool)

        # Mark all the frequencies below min frequency as unavailable
        for inxF in np.arange(int(fMin/fRes)-1):
            vFreqIsFree[inxF] = 0

        # Mark the frequencies taken by vFreq vector as unavailable
        vFreqIsFree[vFrqsInx_ - 1] = 0

        # Create the vector with indices of available frequencies
        vAvailFreqsInx = vSpecInx[vFreqIsFree]

        #----------------------------------------------------------------------
        # Construct a vector with indices of frequencies for all the needed signals

        # Add unknown frequencies of the additional tones to the vFrqsInx vector
        vFrqsInx = np.concatenate((vFrqsInx, np.nan*np.zeros(nTones)))

        # Calculate the number of missing frequencies in the vector with
        # frequencies
        iMissF = len(vFrqsInx) - len(vFrqsInx_)

        # Construct a matrix with indices of frequencies for all the needed signals
        mFrqsInx = np.tile(vFrqsInx, (nSigs, 1))

        #----------------------------------------------------------------------
        # Draw the frequencies
        for inxSig in np.arange(nSigs):

            # Permute all the indices of frequencies in the spectrum
            vPermutedFreqsInx = ((np.random.permutation(vAvailFreqsInx)).T)

            # From the permuted indices of frequencices take as many
            # as it is missing
            vTakenFreqsInx = vPermutedFreqsInx[np.arange(iMissF)]

            # Put the taken indices of frequencies to the matrix with frequency
            # indices for all the signals
            mFrqsInx[inxSig, np.isnan(mFrqsInx[inxSig, :])] = vTakenFreqsInx

        return mFrqsInx

    # =================================================================
    # Draw amplitudes of the signals
    # =================================================================
    def _drawAmps(self, vAmps, nTones, nSigs, iMinAmp, iGraAmp, iMaxAmp):
        """
        This function draws amplitudes of tones for all the signals
        according to the rules specified by users,

        Args:
            vAmps (vector):  vector with specified amplitudes of tones in signals
            nTones (int):    the number of additional tones
            nSigs (int):     the number of signals to be generated
            iMinAmp (int):   min amplitude of a random tone present in a signal
            iGraAmp (int):   gradation of a amplitude of a random tone
            iMaxAmp (int):   max amplitude of a random tone present in a signal

        Returns:
            mAmps (matrix):  matrix with amplitudes of tones for all
                             the signals (one row - one signal)

        """

        # Add unknown amplitudes of the additional tones to the vAmps vector
        vAmps = np.concatenate((vAmps, np.nan*np.zeros(nTones)))

        # Compute the number of missing amplitudes for every signal
        iMissA = (vAmps[np.isnan(vAmps)]).size

        #----------------------------------------------------------------------

        # Compute the number of possible amplitude values
        nAmpVal = np.floor((iMaxAmp - iMinAmp) / iGraAmp) + 1

        #----------------------------------------------------------------------

        # Draw the missing amplitudes for all the signals
        vDrawAmps = \
            iMinAmp + iGraAmp*(np.random.randint(0, nAmpVal, (nSigs*iMissA)))

        # Construct a matrix with amplitudes of tones for all the needed signals
        mAmps = np.tile(vAmps, (nSigs, 1))

        # Put the draw amplitudes to the matrix with amplitudes of tones for
        # all the needed signals
        mAmps[np.isnan(mAmps)] = vDrawAmps

        return mAmps

    # =================================================================
    # Draw phases of the signals
    # =================================================================
    def _drawPhases(self, vPhs, nTones, nSigs, iMinPhs, iGraPhs, iMaxPhs):
        """
        This function draws phases of tones for all the signals
        according to the rules specified by users,

        Args:
            vPhs (vector):   vector with specified phases of tones in signals
            nTones (int):    the number of additional tones
            nSigs (int):     the number of signals to be generated
            iMinPhs (int):   min phase of a random tone present in a signal
            iGraPhs (int):   gradation of a phase of a random tone
            iMaxPhs (int):   max phase of a random tone present in a signal

        Returns:
            mPhs (matrix):   matrix with phases of tones for all
                             the signals (one row - one signal)

        """

        # Add unknown phases of the additional tones to the vAmps vector
        vPhs = np.concatenate((vPhs, np.nan*np.zeros(nTones)))

        # Compute the number of missing phases for every signal
        iMissP = (vPhs[np.isnan(vPhs)]).size

        #----------------------------------------------------------------------

        # Compute the number of possible phase values
        nPhsVal = np.floor((iMaxPhs - iMinPhs)/iGraPhs) + 1

        #----------------------------------------------------------------------

        # Draw the missing phases for all the signals
        vDrawPhs = \
            iMinPhs + iGraPhs*(np.random.randint(0, nPhsVal, (nSigs*iMissP)))

        # Construct a matrix with phases of tones for all the needed signals
        mPhs = np.tile(vPhs, (nSigs, 1))

        # Put the draw phases to the matrix with phases of tones for
        # all the needed signals
        mPhs[np.isnan(mPhs)] = vDrawPhs

        return mPhs

    # =================================================================
    # Generate the signals by IFFT
    # =================================================================
    def _genSigs(self, mFrqsInx, mAmps, mPhs, nSigs, tS, fR, fRes):
        """
        This function generate the multitone signals using the IFFT algorithm.

        Args:
            mFrqsInx (matrix):  matrix with freqs of tones for all the signals
                                (as indices of tones in the allowed spectrum)
            mAmps (matrix):     matrix with amplitudes of tones for all the signals
            mPhs (matrix):      matrix with phases of tones for all the signals
            nSigs (float):      the number of signals
            tS (float):         time of the signals
            fR (float):         signal representation sampling frequency
            fRes (float):       signal spectrum resolution
                                (distance between the tones in the spectrum)

        Returns:
            mSig (matrix):   matrix with signals (one row - one signal)
            mAmPh (float):   complex matrix with amplitudes/phases of tones
            mFrqs (matrix):  matrix with freqs of tones for all the signals
            fFFTR (float):   signal FFT frequency resolution
        """

        # Calculate the number of samples in the signals
        nSmp = int(round(tS*fR))

        # Calculate the FFT frequency resolution
        fFFTR = fR/nSmp

        #----------------------------------------------------------------------

        # Adjust the amplitudes value to the number of points
        mAmpsAdj = mAmps * nSmp/2

        # Change phases into radians
        mPhsRad = mPhs*np.pi/180

        # Generate a one complex matrix for all the signals and its conjugated copy
        mAmPh = mAmpsAdj*np.cos(mPhsRad) + 1j*mAmpsAdj*np.sin(mPhsRad)
        mAmPh_conj = np.conjugate(mAmPh)

        #----------------------------------------------------------------------
        # Put the complex matrix with amplitudes and phases of tones into
        # one matrix dedicated for IFFT

        # Recalculate the matrix with indices of frequencies in the spectrum
        # to real frequencies
        mFrqs = mFrqsInx*fRes

        # Recalculate the matrix with indices of frequencies in the spectrum
        # to indices of frequencies in the IFFT transform
        mIFFTFrqsInx = np.around(mFrqs/fFFTR).astype(int)

        # Allocate the vector for the ifft coefficients for all the signals
        # (one signal in one row)
        mIFFT = np.zeros((nSigs, nSmp)) + 1j*np.zeros((nSigs, nSmp))

        # Put the complex vector with tones values into the IFFT matrix
        for inxSig in np.arange(nSigs):

            # IFFT indices of tones for the current signal
            vInx = mIFFTFrqsInx[inxSig, :]

            # Put the tones for the current signal
            mIFFT[inxSig, vInx] = mAmPh[inxSig, :]

            # IFFT indices of conjugate tones for the current signal
            vInxConj = (nSmp - mIFFTFrqsInx[inxSig, :]).astype(int)

            # Put the conjugate tones for the current signal
            mIFFT[inxSig, vInxConj] = mAmPh_conj[inxSig, :]

        #----------------------------------------------------------------------
        # Generate the signals (perform the IFFT)
        mSig = np.fft.ifftn(mIFFT, axes=[1]).real

        return (mSig, mAmPh, mFrqs, fFFTR)

    # =================================================================
    # Adjust the signal power
    # =================================================================
    def _adjPower(self, mSig, iP, mAmps, mAmPh):
        """
        This function adjustes powers of the generated signals.
        If the requested power of the signals is equal to NaN or inf, then
        the signals are not adjusted.

        Args:
            mSig (matrix):   matrix with signals (one row - one signal)
            iP (float):      requested power of the signals
            mAmps (matrix):  matrix with amplitudes of tones in the signals
            mAmPh (matrix):  complex matrix with amplitudes/phases of tones

        Returns:
            mSig (matrix):   matrix with noisy signals
            vP (vector):     vector with powers of noisy signals
            vPCoef (vector): vector with coefficients which adjsuted the signals
            mAmps (matrix):  matrix with adjusted amplitudes of tones
            mAmPh (matrix):  complex matrix with adjusted amplitudes/phases
        """

        # Get the number of signals and the size of signals (the number of samples)
        (nSigs, nSmp) = mSig.shape

        # Measure the power of the signals
        vP = (np.sum(mSig * mSig, axis=1) / nSmp).reshape(nSigs, 1)

        # Adjust the signal power, if needed
        if not np.isnan(iP) or np.isinf(iP):

            # Compute power adjustments coefficients for the noise signals
            vPCoef = np.sqrt(iP / vP)

            # Adjust the signal power
            mPCoef = np.tile(vPCoef, (1, nSmp))
            mSig = mSig * mPCoef

            # Adjust the reported amplitudes of tones
            (_, nAmps) = mAmps.shape
            mPCoef = np.tile(vPCoef, (1, nAmps))
            mAmps = mAmps * mPCoef
            mAmPh = mAmPh * mPCoef

            # Measure the power of the adjusted signals
            vP = np.sum(mSig*mSig, axis=1) / nSmp

        else:
            # Power adjustment coefficients are equal to 1 (no adjustment)
            vPCoef = np.ones((nSigs, 1))

        return (mSig, vP, vPCoef, mAmps, mAmPh)

    # =================================================================
    # Add the AWGN noise to the signals
    # =================================================================
    def _addNoise(self, mSig, vP, iSNR):
        """
        This function adds noise to the generated signals.
        If the requested level of noise is equal to NaN or inf,
        then no noise is added.

        Args:
            mSig (matrix):   matrix with signals (one row - one signal)
            vP (vector):     vector with powers of signals
            iSNR (float):    wanted level of noise in the signals

        Returns:
            mSigNN (matrix): matrix with non noisy signals
            vPNN (vector):   vector with powers of non noisy signals
            mSig (matrix):   matrix with noisy signals
            vP (vector):     vector with powers of noisy signals
        """

        # Backup the non noisy signals
        mSigNN = mSig.copy()      # Matrix with signals
        vPNN = vP.copy()          # Power of non noisy signals

        # Add the noise, if needed
        if not (np.isnan(iSNR) or np.isinf(iSNR)):

            # Get the number of signals and the size of signals
            # (the number of samples)
            (nSigs, nSmp) = mSig.shape

            # Generate the noise
            mNoise = np.random.randn(nSigs, nSmp)

            # Measure the current powers of the noise signals
            vNoisePReal = (np.sum(mNoise*mNoise, axis=1) / nSmp).reshape(nSigs, 1)

            # Compute the requested noise power for every signal
            vNoiseP = (vP / (10**(iSNR/10))).reshape(nSigs, 1)

            # Compute power adjustments coefficients for the noise signals
            vPNoiseCoef = np.sqrt(vNoiseP / vNoisePReal)

            # Adjust the noise power
            mPNoiseCoef = np.tile(vPNoiseCoef, (1, nSmp))
            mNoise = mPNoiseCoef * mNoise

            # Add the noise to the signals
            mSig = mSig + mNoise

            # Measure the power of the signals
            vP = np.sum(mSig * mSig, axis=1) / nSmp

        return (mSigNN, vPNN, mSig, vP)


text:
package org.wildfly.security.sasl.oauth2;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.AccessController;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;

import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;

import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.wildfly.common.iteration.ByteIterator;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.AuthenticationContextConfigurationClient;
import org.wildfly.security.auth.client.MatchRule;
import org.wildfly.security.auth.realm.token.TokenSecurityRealm;
import org.wildfly.security.auth.realm.token.validator.JwtValidator;
import org.wildfly.security.auth.server.SecurityRealm;
import org.wildfly.security.credential.source.OAuth2CredentialSource;
import org.wildfly.security.sasl.SaslMechanismSelector;
import org.wildfly.security.sasl.test.SaslServerBuilder;
import org.wildfly.security.sasl.util.AbstractSaslParticipant;
import org.wildfly.security.sasl.util.SaslMechanismInformation;

/**
 * @author Pedro Igor
 */
// has dependency on wildfly-elytron-client
public class OAuth2SaslClientV10Test {

    private static final MockWebServer server = new MockWebServer();

    private static final Provider provider = WildFlyElytronSaslOAuth2Provider.getInstance();

    @BeforeClass
    public static void registerProvider() {
        Security.insertProviderAt(provider, 1);
    }

    @AfterClass
    public static void removeProvider() {
        Security.removeProvider(provider.getName());
    }

    @BeforeClass
    public static void onBefore() throws Exception {
        System.setProperty("wildfly.config.url", OAuth2SaslClientV10Test.class.getResource("wildfly-oauth2-test-config-v1_0.xml").toExternalForm());
        server.setDispatcher(createTokenEndpoint());
        server.start(50831);
    }

    @AfterClass
    public static void onAfter() throws Exception {
        server.shutdown();
    }

    @Test
    public void testWithResourceOwnerCredentialsUsingConfiguration() throws Exception {
        URI serverUri = URI.create("protocol://test1.org");
        SaslClient saslClient = createSaslClientFromConfiguration(serverUri);

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        do {
            message = saslClient.evaluateChallenge(message);
            if (message == null) break;
            message = saslServer.evaluateResponse(message);
        } while (message != null);

        assertTrue(saslServer.isComplete());
        assertTrue(saslClient.isComplete());
    }

    @Test
    public void testWithClientCredentialsUsingConfiguration() throws Exception {
        URI serverUri = URI.create("protocol://test2.org");
        SaslClient saslClient = createSaslClientFromConfiguration(serverUri);

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        do {
            message = saslClient.evaluateChallenge(message);
            if (message == null) break;
            message = saslServer.evaluateResponse(message);
        } while (message != null);

        assertTrue(saslServer.isComplete());
        assertTrue(saslClient.isComplete());
    }

    @Test
    public void failedWithBearerTokenFromConfiguration() throws Exception {
        SaslClient saslClient = createSaslClientFromConfiguration(URI.create("protocol://test3.org"));

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        message = saslClient.evaluateChallenge(message);

        message = saslServer.evaluateResponse(message);
        assertFalse(saslServer.isComplete());
        assertEquals("{\"status\":\"invalid_token\"}", ByteIterator.ofBytes(message).asUtf8String().base64Decode().asUtf8String().drainToString());
    }

    @Test
    public void failedInvalidClientCredentialsUsingConfiguration() throws Exception {
        URI serverUri = URI.create("protocol://test4.org");
        SaslClient saslClient = createSaslClientFromConfiguration(serverUri);

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        try {
            do {
                message = saslClient.evaluateChallenge(message);
                if (message == null) break;
                message = saslServer.evaluateResponse(message);
            } while (message != null);
            fail("Expected bad response from server");
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(e.getCause().getMessage().contains("ELY05125"));
        }
    }

    @Test
    public void testWithResourceOwnerCredentials() throws Exception {
        URI serverUri = URI.create("protocol://test5.org");
        SaslClient saslClient = createSaslClientFromConfiguration(serverUri);

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        do {
            message = saslClient.evaluateChallenge(message);
            if (message == null) break;
            message = saslServer.evaluateResponse(message);
        } while (message != null);

        assertTrue(saslServer.isComplete());
        assertTrue(saslClient.isComplete());
    }

    @Test
    public void testWithBearerTokenFromConfiguration() throws Exception {
        SaslClient saslClient = createSaslClientFromConfiguration(URI.create("protocol://test5.org"));

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        do {
            message = saslClient.evaluateChallenge(message);
            if (message == null) break;
            message = saslServer.evaluateResponse(message);
        } while (message != null);

        assertTrue(saslServer.isComplete());
        assertTrue(saslClient.isComplete());
    }

    @Test
    public void failedResourceOwnerCredentialsUsingConfiguration() throws Exception {
        URI serverUri = URI.create("protocol://test6.org");
        AuthenticationContext context = AuthenticationContext.getContextManager().get();
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        AuthenticationConfiguration authenticationConfiguration = contextConfigurationClient.getAuthenticationConfiguration(serverUri, context);
        SaslClient saslClient = contextConfigurationClient.createSaslClient(serverUri, authenticationConfiguration, Arrays.asList(SaslMechanismInformation.Names.OAUTHBEARER));

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        try {
            do {
                message = saslClient.evaluateChallenge(message);
                if (message == null) break;
                message = saslServer.evaluateResponse(message);
            } while (message != null);
            fail("Expected bad response from server");
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(e.getCause().getMessage().contains("ELY09001"));
        }
    }

    @Test
    public void testResourceOwnerCredentialsUsingAPI() throws Exception {
        AuthenticationContext context = AuthenticationContext.empty()
                .with(MatchRule.ALL.matchHost("resourceserver.com"), AuthenticationConfiguration.empty()
                        .useCredentials(OAuth2CredentialSource.builder(new URL("http://localhost:50831/token"))
                                .clientCredentials("elytron-client", "dont_tell_me")
                                .useResourceOwnerPassword("alice", "dont_tell_me")
                                .build())
                        .setSaslMechanismSelector(SaslMechanismSelector.NONE.addMechanism("OAUTHBEARER")));
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        AuthenticationConfiguration configuration = contextConfigurationClient.getAuthenticationConfiguration(URI.create("http://resourceserver.com"), context);
        SaslClient saslClient = contextConfigurationClient.createSaslClient(URI.create("http://resourceserver.com"), configuration, Arrays.asList("OAUTHBEARER"));
        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        do {
            message = saslClient.evaluateChallenge(message);
            if (message == null) break;
            message = saslServer.evaluateResponse(message);
        } while (message != null);

        assertTrue(saslServer.isComplete());
        assertTrue(saslClient.isComplete());
    }

    @Test
    public void failedResourceOwnerCredentialsUsingAPI() throws Exception {
        AuthenticationContext context = AuthenticationContext.empty()
                .with(MatchRule.ALL.matchHost("resourceserver.com"), AuthenticationConfiguration.empty()
                        .useCredentials(OAuth2CredentialSource.builder(new URL("http://localhost:50831/token"))
                                .useResourceOwnerPassword("unknown", "dont_tell_me")
                                .clientCredentials("bad", "bad")
                                .build())
                        .setSaslMechanismSelector(SaslMechanismSelector.NONE.addMechanism("OAUTHBEARER")))
                .with(MatchRule.ALL.matchHost("localhost").matchPort(50831).matchPath("/token"), AuthenticationConfiguration.empty()
                        .useName("elytron_client")
                        .usePassword("dont_tell_me"));
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        AuthenticationConfiguration configuration = contextConfigurationClient.getAuthenticationConfiguration(URI.create("http://resourceserver.com"), context);
        SaslClient saslClient = contextConfigurationClient.createSaslClient(URI.create("http://resourceserver.com"), configuration, Arrays.asList("OAUTHBEARER"));
        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        byte[] message = AbstractSaslParticipant.NO_BYTES;

        try {
            do {
                message = saslClient.evaluateChallenge(message);
                if (message == null) break;
                message = saslServer.evaluateResponse(message);
            } while (message != null);
            fail("Expected bad response from server");
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(e.getCause().getMessage().contains("ELY05125"));
        }
    }

    @Test
    public void testResourceOwnerCredentialsFromExternalCallback() throws Exception {
        URI serverUri = URI.create("protocol://test7.org");
        AuthenticationContext context = AuthenticationContext.getContextManager().get();
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        AuthenticationConfiguration authenticationConfiguration = contextConfigurationClient.getAuthenticationConfiguration(serverUri, context);
        SaslClient saslClient = contextConfigurationClient.createSaslClient(serverUri, authenticationConfiguration, Arrays.asList(SaslMechanismInformation.Names.OAUTHBEARER));

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        AuthenticationContext externalContext = AuthenticationContext.empty().with(MatchRule.ALL.matchHost("localhost"), AuthenticationConfiguration.empty().useCallbackHandler(new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if (callback instanceof NameCallback) {
                        NameCallback.class.cast(callback).setName("alice");
                    } else if (callback instanceof PasswordCallback) {
                        PasswordCallback.class.cast(callback).setPassword("dont_tell_me".toCharArray());
                    } else {
                        throw new RuntimeException("Unexpected callback");
                    }
                }
            }
        }));

        externalContext.run(() -> {
            try {
                byte[] message = AbstractSaslParticipant.NO_BYTES;

                do {
                    message = saslClient.evaluateChallenge(message);
                    if (message == null) break;
                    message = saslServer.evaluateResponse(message);
                } while (message != null);

                assertTrue(saslServer.isComplete());
                assertTrue(saslClient.isComplete());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Test
    public void failedResourceOwnerCredentialsFromExternalCallback() throws Exception {
        URI serverUri = URI.create("protocol://test7.org");
        AuthenticationContext context = AuthenticationContext.getContextManager().get();
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        AuthenticationConfiguration authenticationConfiguration = contextConfigurationClient.getAuthenticationConfiguration(serverUri, context);
        SaslClient saslClient = contextConfigurationClient.createSaslClient(serverUri, authenticationConfiguration, Arrays.asList(SaslMechanismInformation.Names.OAUTHBEARER));

        assertNotNull("OAuth2SaslClient is null", saslClient);

        SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER)
                .setServerName("resourceserver.comn")
                .setProtocol("imap")
                .addRealm("oauth-realm", createSecurityRealmMock())
                .setDefaultRealmName("oauth-realm")
                .build();

        AuthenticationContext externalContext = AuthenticationContext.empty().with(MatchRule.ALL.matchHost("localhost"), AuthenticationConfiguration.empty().useCallbackHandler(new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if (callback instanceof NameCallback) {
                        NameCallback.class.cast(callback).setName("alice");
                    } else if (callback instanceof PasswordCallback) {
                        PasswordCallback.class.cast(callback).setPassword("bad_password".toCharArray());
                    } else {
                        throw new RuntimeException("Unexpected callback");
                    }
                }
            }
        }));

        externalContext.run(() -> {
            byte[] message = AbstractSaslParticipant.NO_BYTES;

            try {
                do {
                    message = saslClient.evaluateChallenge(message);
                    if (message == null) break;
                    message = saslServer.evaluateResponse(message);
                } while (message != null);
                fail("Expected bad response from server");
            } catch (Exception e) {
                e.printStackTrace();
                assertTrue(e.getCause().getMessage().contains("ELY05125"));
            }
        });
    }

    private SecurityRealm createSecurityRealmMock() throws MalformedURLException {
        return TokenSecurityRealm.builder().validator(JwtValidator.builder().build()).principalClaimName("preferred_username").build();
    }

    private static Dispatcher createTokenEndpoint() {
        return new Dispatcher() {
            @Override
            public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException {
                String body = recordedRequest.getBody().readUtf8();
                boolean resourceOwnerCredentials = body.contains("grant_type=password");
                boolean clientCredentials = body.contains("grant_type=client_credentials");

                if (resourceOwnerCredentials
                        && (body.contains("client_id=elytron-client") && body.contains("client_secret=dont_tell_me"))
                        && (body.contains("username=alice") || body.contains("username=jdoe"))
                        && body.contains("password=dont_tell_me")) {
                    JsonObjectBuilder tokenBuilder = Json.createObjectBuilder();

                    tokenBuilder.add("access_token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaXNzIjoiYXV0aC5zZXJ2ZXIiLCJhdWQiOiJmb3JfbWUiLCJleHAiOjE3NjA5OTE2MzUsInByZWZlcnJlZF91c2VybmFtZSI6Impkb2UifQ.SoPW41_mOFnKXdkwVG63agWQ2k09dEnEtTBztnxHN64");

                    return new MockResponse().setBody(tokenBuilder.build().toString());
                } else if (clientCredentials
                        && (body.contains("client_id=elytron-client") && body.contains("client_secret=dont_tell_me"))
                        && !body.contains("username=")) {
                    JsonObjectBuilder tokenBuilder = Json.createObjectBuilder();

                    tokenBuilder.add("access_token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaXNzIjoiYXV0aC5zZXJ2ZXIiLCJhdWQiOiJmb3JfbWUiLCJleHAiOjE3NjA5OTE2MzUsInByZWZlcnJlZF91c2VybmFtZSI6Impkb2UifQ.SoPW41_mOFnKXdkwVG63agWQ2k09dEnEtTBztnxHN64");

                    return new MockResponse().setBody(tokenBuilder.build().toString());
                }

                return new MockResponse().setResponseCode(400);
            }
        };
    }

    private SaslClient createSaslClientFromConfiguration(URI serverUri) throws SaslException {
        AuthenticationContext context = AuthenticationContext.getContextManager().get();
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        AuthenticationConfiguration authenticationConfiguration = contextConfigurationClient.getAuthenticationConfiguration(serverUri, context);
        return contextConfigurationClient.createSaslClient(serverUri, authenticationConfiguration, Arrays.asList(SaslMechanismInformation.Names.OAUTHBEARER));
    }
}

redpajama_set_name: RedPajamaGithub


text:
#!/usr/bin/env node

const puppeteer = require('../..');
const path = require('path');
const SourceFactory = require('./SourceFactory');

const PROJECT_DIR = path.join(__dirname, '..', '..');

const RED_COLOR = '\x1b[31m';
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';

run();

async function run() {
  const startTime = Date.now();

  const sourceFactory = new SourceFactory();
  /** @type {!Array<!Message>} */
  const messages = [];

  // Documentation checks.
  {
    const mdSources = await sourceFactory.readdir(path.join(PROJECT_DIR, 'docs'), '.md');

    const toc = require('./toc');
    messages.push(...await toc(mdSources));

    const preprocessor = require('./preprocessor');
    messages.push(...await preprocessor(mdSources));

    const browser = await puppeteer.launch({args: ['--no-sandbox']});
    const page = await browser.newPage();
    const checkPublicAPI = require('./check_public_api');
    const jsSources = await sourceFactory.readdir(path.join(PROJECT_DIR, 'lib'), '.js');
    messages.push(...await checkPublicAPI(page, mdSources, jsSources));
    await browser.close();
  }

  // Report results.
  const errors = messages.filter(message => message.type === 'error');
  if (errors.length) {
    console.log('DocLint Failures:');
    for (let i = 0; i < errors.length; ++i) {
      let error = errors[i].text;
      error = error.split('\n').join('\n      ');
      console.log(`  ${i + 1}) ${RED_COLOR}${error}${RESET_COLOR}`);
    }
  }
  const warnings = messages.filter(message => message.type === 'warning');
  if (warnings.length) {
    console.log('DocLint Warnings:');
    for (let i = 0; i < warnings.length; ++i) {
      let warning = warnings[i].text;
      warning = warning.split('\n').join('\n      ');
      console.log(`  ${i + 1}) ${YELLOW_COLOR}${warning}${RESET_COLOR}`);
    }
  }
  let clearExit = messages.length === 0;
  if (await sourceFactory.saveChangedSources()) {
    if (clearExit)
      console.log(`${YELLOW_COLOR}Some files were updated.${RESET_COLOR}`);
    clearExit = false;
  }
  console.log(`${errors.length} failures, ${warnings.length} warnings.`);
  const runningTime = Date.now() - startTime;
  console.log(`DocLint Finished in ${runningTime / 1000} seconds`);
  process.exit(clearExit ? 0 : 1);
}


text:
package com.hazelcast.query.impl.getters;

import java.util.ArrayList;
import java.util.List;

/**
 * Represents multiple results from a single attribute extraction.
 *

 * MultiResult is an aggregate of results that is returned if the ValueExtractor returns multiple results due to a
 * reduce operation executed on a hierarchy of values.
 *

 * It sounds counter-intuitive, but a single extraction may return multiple values when arrays or collections are
 * involved.
 *

 * Let's have a look at the following data structure:
 *

 * class Swap {
 *     Leg legs[2];
 * }
 * class Leg {
 *     String currency;
 * }
 *

 *

 * The following extraction of the currency attribute legs[any].currency results in two currencies for each
 * Leg. In order to return both values in one result of the extract operation both currencies are returned in a
 * single MultiResult object where each result contains a name of the currency.
 * It allows the user to operate on multiple "reduced" values as if they were single-values.
 *

 * Let's have a look at the following queries:
 *

 *
leg[1].currency   = 'EUR'

 *
leg[any].currency = 'EUR'

 *

 * In the first query, the extraction will return just one currency, whereas the extraction in the second query will
 * return a MultiResult containing two currencies.
 * During the evaluation of the "=" equals predicate the MultiResult will be "unfolded" and the condition will
 * evaluated against all currencies from the MultiResult. If there is "any" currency that matches the condition the
 * whole predicate will be evaluated to "true" and the matching Swap will be returned.
 * As a result all Swaps will be returned where there's at lease one Leg with EUR currency.
 *

 * Other examples:
 *

 *
legs -> returns one 'single-value' result -> a collection of values

 *
legs[0] -> returns one 'single result' - a Leg object

 *
legs[0].currency -> returns one 'multi value' result - an array of Legs

 *
legs[any] -> returns a MultiResult - that contains a collection of Leg objects

 *
legs[any].currency -> returns a MultiResult - that contains a collection of String objects

 *

 * @param <T> type of the underlying result store in the MultiResult
 */
public class MultiResult<T> {

    private List<T> results;

    /**
     * Indicates that the result of a multi-result evaluation using [any] operator
     * didn't reach any data since the field where the [any] operator is used was null or empty.
     *
     * Allows differentiating whether there is a null value in the MultiResult
     * that is a result of a null or empty target in the expression.
     *
     * For query evaluation the difference is not important - and we need to return null in both cases there.
     * For aggregations it makes a difference and we need this context knowledge there.
     */
    private boolean nullOrEmptyTarget;

    public MultiResult() {
        this.results = new ArrayList<T>();
    }

    public MultiResult(List<T> results) {
        this.results = results;
    }

    /**
     * @param result result to be added to this MultiResult
     */
    public void add(T result) {
        results.add(result);
    }

    public void addNullOrEmptyTarget() {
        if (!nullOrEmptyTarget) {
            // we don't want to store more than one null if we reach a null/empty target
            // it's enough to have one for the query evaluation (it's for null matching)
            nullOrEmptyTarget = true;
            results.add(null);
        }
    }

    /**
     * @return a mutable underlying list of collected results
     */
    public List<T> getResults() {
        return results;
    }

    /**
     * @return true if the MultiResult is empty; false otherwise
     */
    public boolean isEmpty() {
        return results.isEmpty();
    }

    public boolean isNullEmptyTarget() {
        return nullOrEmptyTarget;
    }

    public void setNullOrEmptyTarget(boolean nullOrEmptyTarget) {
        this.nullOrEmptyTarget = nullOrEmptyTarget;
    }

}


text:
#include <stdarg.h>

#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "ddeml.h"
#include "shellapi.h"

#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(shell);

/* String handles */
static HSZ hszProgmanTopic;
static HSZ hszProgmanService;
static HSZ hszAsterisk;
static HSZ hszShell;
static HSZ hszAppProperties;
static HSZ hszFolders;
static HSZ hszGroups;
/* DDE Instance ID */
static DWORD dwDDEInst;

static const char *debugstr_hsz( HSZ hsz )
{
    WCHAR buffer[256];
    if (!DdeQueryStringW( dwDDEInst, hsz, buffer, sizeof(buffer)/sizeof(WCHAR), CP_WINUNICODE ))
        return "<unknown>";
    return debugstr_w( buffer );
}

static inline BOOL Dde_OnConnect(HSZ hszTopic, HSZ hszService)
{
    if ((hszTopic == hszProgmanTopic) && (hszService == hszProgmanService))
        return TRUE;
    if ((hszTopic == hszProgmanTopic) && (hszService == hszAppProperties))
        return TRUE;
    if ((hszTopic == hszShell) && (hszService == hszFolders))
        return TRUE;
    if ((hszTopic == hszShell) && (hszService == hszAppProperties))
        return TRUE;
    return FALSE;
}

static inline void Dde_OnConnectConfirm(HCONV hconv, HSZ hszTopic, HSZ hszService)
{
    TRACE( "%p %s %s\n", hconv, debugstr_hsz(hszTopic), debugstr_hsz(hszService) );
}

static inline BOOL Dde_OnWildConnect(HSZ hszTopic, HSZ hszService)
{
    FIXME("stub\n");
    return FALSE;
}

static inline HDDEDATA Dde_OnRequest(UINT uFmt, HCONV hconv, HSZ hszTopic,
                                     HSZ hszItem)
{
    if (hszTopic == hszProgmanTopic && hszItem == hszGroups && uFmt == CF_TEXT)
    {
        static BYTE groups_data[] = "Accessories\r\nStartup\r\n";
        FIXME( "returning fake program groups list\n" );
        return DdeCreateDataHandle( dwDDEInst, groups_data, sizeof(groups_data), 0, hszGroups, uFmt, 0 );
    }
    else if (hszTopic == hszProgmanTopic && hszItem == hszProgmanService && uFmt == CF_TEXT)
    {
        static BYTE groups_data[] = "\r\n";
        FIXME( "returning empty groups list\n" );
	/* This is a workaround for an application which expects some data
	 * and cannot handle NULL. */
        return DdeCreateDataHandle( dwDDEInst, groups_data, sizeof(groups_data), 0, hszProgmanService, uFmt, 0 );
    }
    FIXME( "%u %p %s %s: stub\n", uFmt, hconv, debugstr_hsz(hszTopic), debugstr_hsz(hszItem) );
    return NULL;
}

static inline DWORD Dde_OnExecute(HCONV hconv, HSZ hszTopic, HDDEDATA hdata)
{
    WCHAR * pszCommand;

    pszCommand = (WCHAR *)DdeAccessData(hdata, NULL);
    if (!pszCommand)
        return DDE_FNOTPROCESSED;

    FIXME("stub: %s %s\n", debugstr_hsz(hszTopic), debugstr_w(pszCommand));

    DdeUnaccessData(hdata);

    return DDE_FNOTPROCESSED;
}

static inline void Dde_OnDisconnect(HCONV hconv)
{
    TRACE( "%p\n", hconv );
}

static HDDEDATA CALLBACK DdeCallback(
    UINT uType,
    UINT uFmt,
    HCONV hconv,
    HSZ hsz1,
    HSZ hsz2,
    HDDEDATA hdata,
    ULONG_PTR dwData1,
    ULONG_PTR dwData2)
{
    switch (uType)
    {
    case XTYP_CONNECT:
        return (HDDEDATA)(DWORD_PTR)Dde_OnConnect(hsz1, hsz2);
    case XTYP_CONNECT_CONFIRM:
        Dde_OnConnectConfirm(hconv, hsz1, hsz2);
        return NULL;
    case XTYP_WILDCONNECT:
        return (HDDEDATA)(DWORD_PTR)Dde_OnWildConnect(hsz1, hsz2);
    case XTYP_REQUEST:
        return Dde_OnRequest(uFmt, hconv, hsz1, hsz2);
    case XTYP_EXECUTE:
        return (HDDEDATA)(DWORD_PTR)Dde_OnExecute(hconv, hsz1, hdata);
    case XTYP_DISCONNECT:
        Dde_OnDisconnect(hconv);
        return NULL;
    default:
        return NULL;
    }
}

/*************************************************************************
 * ShellDDEInit (SHELL32.@)
 *
 * Registers the Shell DDE services with the system so that applications
 * can use them.
 *
 * PARAMS
 *  bInit [I] TRUE to initialize the services, FALSE to uninitialize.
 *
 * RETURNS
 *  Nothing.
 */
void WINAPI ShellDDEInit(BOOL bInit)
{
    TRACE("bInit = %s\n", bInit ? "TRUE" : "FALSE");

    if (bInit)
    {
        static const WCHAR wszProgman[] = {'P','r','o','g','m','a','n',0};
        static const WCHAR wszAsterisk[] = {'*',0};
        static const WCHAR wszShell[] = {'S','h','e','l','l',0};
        static const WCHAR wszAppProperties[] =
            {'A','p','p','P','r','o','p','e','r','t','i','e','s',0};
        static const WCHAR wszFolders[] = {'F','o','l','d','e','r','s',0};
        static const WCHAR wszGroups[] = {'G','r','o','u','p','s',0};

        DdeInitializeW(&dwDDEInst, DdeCallback, CBF_FAIL_ADVISES | CBF_FAIL_POKES, 0);

        hszProgmanTopic = DdeCreateStringHandleW(dwDDEInst, wszProgman, CP_WINUNICODE);
        hszProgmanService = DdeCreateStringHandleW(dwDDEInst, wszProgman, CP_WINUNICODE);
        hszAsterisk = DdeCreateStringHandleW(dwDDEInst, wszAsterisk, CP_WINUNICODE);
        hszShell = DdeCreateStringHandleW(dwDDEInst, wszShell, CP_WINUNICODE);
        hszAppProperties = DdeCreateStringHandleW(dwDDEInst, wszAppProperties, CP_WINUNICODE);
        hszFolders = DdeCreateStringHandleW(dwDDEInst, wszFolders, CP_WINUNICODE);
        hszGroups = DdeCreateStringHandleW(dwDDEInst, wszGroups, CP_WINUNICODE);

        DdeNameService(dwDDEInst, hszFolders, 0, DNS_REGISTER);
        DdeNameService(dwDDEInst, hszProgmanService, 0, DNS_REGISTER);
        DdeNameService(dwDDEInst, hszShell, 0, DNS_REGISTER);
    }
    else
    {
        /* unregister all services */
        DdeNameService(dwDDEInst, 0, 0, DNS_UNREGISTER);

        DdeFreeStringHandle(dwDDEInst, hszFolders);
        DdeFreeStringHandle(dwDDEInst, hszAppProperties);
        DdeFreeStringHandle(dwDDEInst, hszShell);
        DdeFreeStringHandle(dwDDEInst, hszAsterisk);
        DdeFreeStringHandle(dwDDEInst, hszProgmanService);
        DdeFreeStringHandle(dwDDEInst, hszProgmanTopic);

        DdeUninitialize(dwDDEInst);
    }
}


text:
#ifndef __SPARC_PROCESS_HH__
#define __SPARC_PROCESS_HH__

#include <string>
#include <vector>

#include "mem/page_table.hh"
#include "sim/byteswap.hh"
#include "sim/process.hh"

class ObjectFile;

class SparcProcess : public Process
{
  protected:

    const Addr StackBias;

    // The locations of the fill and spill handlers
    Addr fillStart, spillStart;

    SparcProcess(ProcessParams * params, ObjectFile *objFile,
                 Addr _StackBias);

    void initState();

    template<class IntType>
    void argsInit(int pageSize);

  public:

    // Handles traps which request services from the operating system
    virtual void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);

    Addr readFillStart() { return fillStart; }
    Addr readSpillStart() { return spillStart; }

    virtual void flushWindows(ThreadContext *tc) = 0;
    void setSyscallReturn(ThreadContext *tc, SyscallReturn return_value);
};

class Sparc32Process : public SparcProcess
{
  protected:

    Sparc32Process(ProcessParams * params, ObjectFile *objFile)
        : SparcProcess(params, objFile, 0)
    {
        // Set up stack. On SPARC Linux, stack goes from the top of memory
        // downward, less the hole for the kernel address space.
        memState->stackBase = (Addr)0xf0000000ULL;

        // Set up region for mmaps.
        memState->mmapEnd = 0x70000000;
    }

    void initState();

  public:

    void argsInit(int intSize, int pageSize);

    void flushWindows(ThreadContext *tc);

    SparcISA::IntReg getSyscallArg(ThreadContext *tc, int &i);
    /// Explicitly import the otherwise hidden getSyscallArg
    using Process::getSyscallArg;

    void setSyscallArg(ThreadContext *tc, int i, SparcISA::IntReg val);
};

class Sparc64Process : public SparcProcess
{
  protected:

    Sparc64Process(ProcessParams * params, ObjectFile *objFile)
        : SparcProcess(params, objFile, 2047)
    {
        // Set up stack. On SPARC Linux, stack goes from the top of memory
        // downward, less the hole for the kernel address space.
        memState->stackBase = (Addr)0x80000000000ULL;

        // Set up region for mmaps.
        memState->mmapEnd = 0xfffff80000000000ULL;
    }

    void initState();

  public:

    void argsInit(int intSize, int pageSize);

    void flushWindows(ThreadContext *tc);

    SparcISA::IntReg getSyscallArg(ThreadContext *tc, int &i);
    /// Explicitly import the otherwise hidden getSyscallArg
    using Process::getSyscallArg;

    void setSyscallArg(ThreadContext *tc, int i, SparcISA::IntReg val);
};

/* No architectural page table defined for this ISA */
typedef NoArchPageTable ArchPageTable;

#endif // __SPARC_PROCESS_HH__


text:
<?php

namespace IPS\core\modules\front\contact;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Contact Form
 */
class _contact extends \IPS\Dispatcher\Controller
{

	/**
	 * Method
	 *
	 * @return	void
	 */
	protected function manage()
	{
		\IPS\Output::i()->sidebar['enabled'] = FALSE;
		\IPS\Output::i()->bodyClasses[] = 'ipsLayout_minimal';

		$form = new \IPS\Helpers\Form( 'contact', 'send' );
		$form->class = 'ipsForm_vertical';

		$form->add( new \IPS\Helpers\Form\Editor( 'contact_text', NULL, TRUE, array(
				'app'			=> 'core',
				'key'			=> 'Contact',
				'autoSaveKey'	=> 'contact-' . \IPS\Member::loggedIn()->member_id,
				//'minimize'		=> 'x',
		) ) );

		if ( !\IPS\Member::loggedIn()->member_id )
		{
			$form->add( new \IPS\Helpers\Form\Text( 'contact_name', NULL, TRUE ) );
			$form->add( new \IPS\Helpers\Form\Email( 'email_address', NULL, TRUE, array( 'bypassProfanity' => TRUE ) ) );
			if ( \IPS\Settings::i()->bot_antispam_type !== 'none' and \IPS\Settings::i()->guest_captcha )
			{
				$form->add( new \IPS\Helpers\Form\Captcha );
			}

		}

		if ( $values = $form->values() )
		{
			/* Send the message */
			$fromName = ( \IPS\Member::loggedIn()->member_id ) ? \IPS\Member::loggedIn()->name : $values['contact_name'];
			$fromEmail = ( \IPS\Member::loggedIn()->member_id ) ? \IPS\Member::loggedIn()->email : $values['email_address'];

			$mail = \IPS\Email::buildFromTemplate( 'core', 'contact_form', array( \IPS\Member::loggedIn(), $fromName, $fromEmail, $values['contact_text'] ), \IPS\Email::TYPE_TRANSACTIONAL );
			$mail->send( \IPS\Settings::i()->email_in, array(), array(), NULL, $fromName, array( 'Reply-To' => \IPS\Email::encodeHeader( $fromName, ( \IPS\Member::loggedIn()->member_id ? \IPS\Member::loggedIn()->email : $values['email_address'] ) ) ) );

			if( \IPS\Request::i()->isAjax() )
			{
				\IPS\Output::i()->json( 'OK' );
			}

			\IPS\Output::i()->title		= \IPS\Member::loggedIn()->language()->addToStack('message_sent');
			\IPS\Output::i()->output	= \IPS\Theme::i()->getTemplate( 'system' )->contactDone();
		}
		else
		{
			\IPS\Output::i()->title		= \IPS\Member::loggedIn()->language()->addToStack('contact');
			\IPS\Output::i()->output	= \IPS\Theme::i()->getTemplate( 'system' )->contact( $form );
		}

	}
}


text:
from django.template.loader import get_template
from django.core.mail import EmailMessage
from django.conf import settings
import premailer
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib, os
import logging
# we dont want these warnings on our console output (e.g. in test cases)
import cssutils
cssutils.log.setLevel(logging.CRITICAL)

class TextEmail(EmailMessage):
    #content_subtype = 'text/plain'
    pass

class HtmlEmail(EmailMessage):

    content_subtype = 'html'

    def __init__(self, *args, **kwargs):
        template = kwargs.pop('template', 'emailing/base.html')
        context = kwargs.pop('context', dict())

        context['brand_bg'] = settings.EMAIL_BRAND_BG
        context['button_bg'] = settings.EMAIL_BUTTON_BG
        context['body_bg'] = settings.EMAIL_BODY_BG
        context['brand_color'] = settings.EMAIL_BRAND_COLOR
        context['link_color'] = settings.EMAIL_LINK_COLOR
        context['footer_content'] = settings.EMAIL_FOOTER_CONTENT
        context['logo_src'] = settings.EMAIL_LOGO_SRC
        context['logo_href'] = settings.EMAIL_LOGO_HREF
        context['logo_alignment'] = settings.EMAIL_LOGO_ALIGNMENT
        context['logo_alt_text'] = settings.EMAIL_LOGO_ALT_TEXT

        kwargs['body'] = premailer.transform(get_template(template).render(context))

        super(HtmlEmail, self).__init__(*args, **kwargs)

    def send(self, *args, **kwargs):
        kwargs['fail_silently'] = False
        if not settings.DEBUG:
            try:
                super(HtmlEmail, self).send(*args, **kwargs)
            except Exception:
                # this is a fallback trying to ensure that emails are sent out in case something goes
                # wrong with default implementation.
                if settings.FALLBACK_EMAIL != 'webmaster@localhost':
                    fallback_mail = settings.FALLBACK_EMAIL
                else:
                    fallback_mail = settings.SERVER_EMAIL
                smtpObj = smtplib.SMTP('localhost')
                msg = MIMEMultipart('alternative')
                msg.attach(MIMEText(self.body.encode('utf-8'), 'html', 'utf-8'))
                msg['From'] = fallback_mail
                msg['To'] = fallback_mail
                msg['Subject'] = u"Error sending Email from " + str(self.from_email) + " to " + str(self.to) + " in container " + os.environ['CONTAINER_DIR']
                smtpObj.sendmail(fallback_mail, fallback_mail, msg.as_string())
        else:
            super(HtmlEmail, self).send(*args, **kwargs)


text:
from FieldInfo import FieldInfo
from twisted.internet import defer

class SimpleDriver:
    def __init__(self, did, name, updated):
        self.did = did
        self.name = name
        self.updated = updated

    def get_device_fields(self):
        d = defer.Deferred()
        d.callback({})
        return d

    def update_device_field(self, field_name, value):
        def callb(res):
            for field in self.fields:
                if field.Writable and field.Name == field_name and type(field.Value) == type(value):
                    up_func = getattr(self, "update_{0}".format(field_name.lower()))
                    if up_func is None:
                        raise RuntimeError("No method to handle update")
                    return up_func(value)
            raise ValueError("Wrong field passed")
        d = self.get_device_fields()
        d.addCallback(callb)
        return d


text:
package org.camunda.bpm.spring.boot.starter.actuator;

import static java.util.Objects.requireNonNull;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutor;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health.Builder;

public class JobExecutorHealthIndicator extends AbstractHealthIndicator {

  private final JobExecutor jobExecutor;

  public JobExecutorHealthIndicator(final JobExecutor jobExecutor) {
    this.jobExecutor = requireNonNull(jobExecutor);
  }

  @Override
  protected void doHealthCheck(Builder builder) throws Exception {
    boolean active = jobExecutor.isActive();
    if (active) {
      builder = builder.up();
    } else {
      builder = builder.down();
    }
    builder.withDetail("jobExecutor", Details.from(jobExecutor));
  }

  public static class Details {

    private final String name;
    private final String lockOwner;
    private final int lockTimeInMillis;
    private final int maxJobsPerAcquisition;
    private final int waitTimeInMillis;
    private final Set<String> processEngineNames;

    private Details(DetailsBuilder builder) {
      name = builder.name;
      lockOwner = builder.lockOwner;
      lockTimeInMillis = builder.lockTimeInMillis;
      maxJobsPerAcquisition = builder.maxJobsPerAcquisition;
      waitTimeInMillis = builder.waitTimeInMillis;
      processEngineNames = java.util.Collections.unmodifiableSet(new HashSet<String>(builder.processEngineNames));
    }

    public static DetailsBuilder builder() {
      return new DetailsBuilder();
    }

    private static Details from(JobExecutor jobExecutor) {
      final DetailsBuilder builder = Details.builder()
        .name(jobExecutor.getName())
        .lockOwner(jobExecutor.getLockOwner())
        .lockTimeInMillis(jobExecutor.getLockTimeInMillis())
        .maxJobsPerAcquisition(jobExecutor.getMaxJobsPerAcquisition())
        .waitTimeInMillis(jobExecutor.getWaitTimeInMillis());

      for (ProcessEngineImpl processEngineImpl : jobExecutor.getProcessEngines()) {
        builder.processEngineName(processEngineImpl.getName());
      }

      return builder.build();
    }

    public static class DetailsBuilder {

      private String name;
      private String lockOwner;
      private int lockTimeInMillis;
      private int maxJobsPerAcquisition;
      private int waitTimeInMillis;
      private Set<String> processEngineNames;

      DetailsBuilder() {}

      public DetailsBuilder name(String name) {
        this.name = name;
        return this;
      }

      public DetailsBuilder lockOwner(String lockOwner) {
        this.lockOwner = lockOwner;
        return this;
      }

      public DetailsBuilder lockTimeInMillis(int lockTimeInMillis) {
        this.lockTimeInMillis = lockTimeInMillis;
        return this;
      }

      public DetailsBuilder maxJobsPerAcquisition(int maxJobsPerAcquisition) {
        this.maxJobsPerAcquisition = maxJobsPerAcquisition;
        return this;
      }

      public DetailsBuilder waitTimeInMillis(int waitTimeInMillis) {
        this.waitTimeInMillis = waitTimeInMillis;
        return this;
      }

      public DetailsBuilder processEngineName(String processEngineName) {
        if (this.processEngineNames == null) {
          this.processEngineNames = new HashSet<String>();
        }
        this.processEngineNames.add(processEngineName);
        return this;
      }

      public DetailsBuilder processEngineNames(Set<? extends String> processEngineNames) {
        if (this.processEngineNames == null) {
          this.processEngineNames = new HashSet<String>();
        }
        this.processEngineNames.addAll(processEngineNames);
        return this;
      }

      public DetailsBuilder clearProcessEngineNames(Set<? extends String> processEngineNames) {
        if (this.processEngineNames != null) {
          this.processEngineNames.clear();
        }
        return this;
      }

      public Details build() {
        return new Details(this);
      }

    }

    public String getName() {
      return name;
    }

    public String getLockOwner() {
      return lockOwner;
    }

    public int getLockTimeInMillis() {
      return lockTimeInMillis;
    }

    public int getMaxJobsPerAcquisition() {
      return maxJobsPerAcquisition;
    }

    public int getWaitTimeInMillis() {
      return waitTimeInMillis;
    }

    public Set<String> getProcessEngineNames() {
      return processEngineNames;
    }

    @Override
    public String toString() {
      return "Details [name=" + name + ", lockOwner=" + lockOwner + ", lockTimeInMillis="
          + lockTimeInMillis + ", maxJobsPerAcquisition=" + maxJobsPerAcquisition
          + ", waitTimeInMillis=" + waitTimeInMillis + ", processEngineNames=" + processEngineNames
          + "]";
    }

  }

}


text:
package com.gsma.android.oneapi.valuesLogo;

/**
 * Enum about AspectRatio options.
 */
public enum AspectRatio {

	LANDSCAPE("landscape"),
	SQUARE("square");

	private final String value;

	/**
	 * Constructor
	 *
	 * @param value
	 */
	private AspectRatio(String v) {
		value = v;
	}

	/**
	 * Gets the String value.
	 *
	 * @return String value
	 */
	public String value() {
		return value;
	}

	/**
	 * Gets the AspectRatio value from the String value.
	 *
	 * @param value
	 * @return AspectRatio
	 * @throws IllegalArgumentException
	 */
	public static AspectRatio fromValue(String v) {
		for (AspectRatio c : AspectRatio.values()) {
			if (c.value.equalsIgnoreCase(v)) {
				return c;
			}
		}
		throw new IllegalArgumentException(v);
	}

}


text:
#include <aws/ssm/model/AssociationExecution.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SSM
{
namespace Model
{

AssociationExecution::AssociationExecution() :
    m_associationIdHasBeenSet(false),
    m_associationVersionHasBeenSet(false),
    m_executionIdHasBeenSet(false),
    m_statusHasBeenSet(false),
    m_detailedStatusHasBeenSet(false),
    m_createdTimeHasBeenSet(false),
    m_lastExecutionDateHasBeenSet(false),
    m_resourceCountByStatusHasBeenSet(false),
    m_alarmConfigurationHasBeenSet(false),
    m_triggeredAlarmsHasBeenSet(false)
{
}

AssociationExecution::AssociationExecution(JsonView jsonValue) :
    m_associationIdHasBeenSet(false),
    m_associationVersionHasBeenSet(false),
    m_executionIdHasBeenSet(false),
    m_statusHasBeenSet(false),
    m_detailedStatusHasBeenSet(false),
    m_createdTimeHasBeenSet(false),
    m_lastExecutionDateHasBeenSet(false),
    m_resourceCountByStatusHasBeenSet(false),
    m_alarmConfigurationHasBeenSet(false),
    m_triggeredAlarmsHasBeenSet(false)
{
  *this = jsonValue;
}

AssociationExecution& AssociationExecution::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("AssociationId"))
  {
    m_associationId = jsonValue.GetString("AssociationId");

    m_associationIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("AssociationVersion"))
  {
    m_associationVersion = jsonValue.GetString("AssociationVersion");

    m_associationVersionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ExecutionId"))
  {
    m_executionId = jsonValue.GetString("ExecutionId");

    m_executionIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Status"))
  {
    m_status = jsonValue.GetString("Status");

    m_statusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DetailedStatus"))
  {
    m_detailedStatus = jsonValue.GetString("DetailedStatus");

    m_detailedStatusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CreatedTime"))
  {
    m_createdTime = jsonValue.GetDouble("CreatedTime");

    m_createdTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("LastExecutionDate"))
  {
    m_lastExecutionDate = jsonValue.GetDouble("LastExecutionDate");

    m_lastExecutionDateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ResourceCountByStatus"))
  {
    m_resourceCountByStatus = jsonValue.GetString("ResourceCountByStatus");

    m_resourceCountByStatusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("AlarmConfiguration"))
  {
    m_alarmConfiguration = jsonValue.GetObject("AlarmConfiguration");

    m_alarmConfigurationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("TriggeredAlarms"))
  {
    Aws::Utils::Array<JsonView> triggeredAlarmsJsonList = jsonValue.GetArray("TriggeredAlarms");
    for(unsigned triggeredAlarmsIndex = 0; triggeredAlarmsIndex < triggeredAlarmsJsonList.GetLength(); ++triggeredAlarmsIndex)
    {
      m_triggeredAlarms.push_back(triggeredAlarmsJsonList[triggeredAlarmsIndex].AsObject());
    }
    m_triggeredAlarmsHasBeenSet = true;
  }

  return *this;
}

JsonValue AssociationExecution::Jsonize() const
{
  JsonValue payload;

  if(m_associationIdHasBeenSet)
  {
   payload.WithString("AssociationId", m_associationId);

  }

  if(m_associationVersionHasBeenSet)
  {
   payload.WithString("AssociationVersion", m_associationVersion);

  }

  if(m_executionIdHasBeenSet)
  {
   payload.WithString("ExecutionId", m_executionId);

  }

  if(m_statusHasBeenSet)
  {
   payload.WithString("Status", m_status);

  }

  if(m_detailedStatusHasBeenSet)
  {
   payload.WithString("DetailedStatus", m_detailedStatus);

  }

  if(m_createdTimeHasBeenSet)
  {
   payload.WithDouble("CreatedTime", m_createdTime.SecondsWithMSPrecision());
  }

  if(m_lastExecutionDateHasBeenSet)
  {
   payload.WithDouble("LastExecutionDate", m_lastExecutionDate.SecondsWithMSPrecision());
  }

  if(m_resourceCountByStatusHasBeenSet)
  {
   payload.WithString("ResourceCountByStatus", m_resourceCountByStatus);

  }

  if(m_alarmConfigurationHasBeenSet)
  {
   payload.WithObject("AlarmConfiguration", m_alarmConfiguration.Jsonize());

  }

  if(m_triggeredAlarmsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> triggeredAlarmsJsonList(m_triggeredAlarms.size());
   for(unsigned triggeredAlarmsIndex = 0; triggeredAlarmsIndex < triggeredAlarmsJsonList.GetLength(); ++triggeredAlarmsIndex)
   {
     triggeredAlarmsJsonList[triggeredAlarmsIndex].AsObject(m_triggeredAlarms[triggeredAlarmsIndex].Jsonize());
   }
   payload.WithArray("TriggeredAlarms", std::move(triggeredAlarmsJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using Twice.Converters;

namespace Twice.Tests.Converters
{
	[TestClass, ExcludeFromCodeCoverage]
	public class MathConverterTests
	{
		[TestMethod, TestCategory( "Converters" )]
		public void ConvertBackThrowsException()
		{
			// Arrange
			var conv = new MathConverter();

			// Act
			var ex = ExceptionAssert.Catch<NotSupportedException>( () => conv.ConvertBack( null, null, null, null ) );

			// Assert
			Assert.IsNotNull( ex );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void InvalidParameterReturnsUnsetValue()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Add };

			// Act
			var result = conv.Convert( null, null, new object(), null );

			// Assert
			Assert.AreEqual( DependencyProperty.UnsetValue, result );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void InvalidValueReturnsUnsetValue()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Add };

			// Act
			var result = conv.Convert( new object(), null, null, null );

			// Assert
			Assert.AreEqual( DependencyProperty.UnsetValue, result );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void NumbersCanBeAdded()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Add };

			// Act
			var result = conv.Convert( 12.0, null, 3, null );

			// Assert
			Assert.AreEqual( 15.0, result );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void NumbersCanBeDevided()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Divide };

			// Act
			var result = conv.Convert( "10.0", null, "5", null );

			// Assert
			Assert.AreEqual( 2.0, result );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void NumbersCanBeMultiplied()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Multiply };

			// Act
			var result = conv.Convert( 3, null, "2.0", null );

			// Assert
			Assert.AreEqual( 6.0, result );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void NumbersCanBeSubstracted()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Substract };

			// Act
			var result = conv.Convert( "10", null, 3.0, null );

			// Assert
			Assert.AreEqual( 7.0, result );
		}

		[TestMethod, TestCategory( "Converters" )]
		public void UnknownOperationReturnsUnsetValue()
		{
			// Arrange
			var conv = new MathConverter { Operation = MathOperation.Add + 10 };

			// Act
			var result = conv.Convert( 1, null, 2, null );

			// Assert
			Assert.AreEqual( DependencyProperty.UnsetValue, result );
		}
	}
}


text:
package io.seldon.general;

import io.seldon.api.resource.service.PersistenceProvider;
import io.seldon.general.jdo.SqlItemPeer;
import io.seldon.memcache.DogpileHandler;
import io.seldon.memcache.MemCacheKeys;
import io.seldon.memcache.MemCachePeer;
import io.seldon.memcache.SecurityHashPeer;
import io.seldon.memcache.UpdateRetriever;
import io.seldon.recommendation.filters.FilteredItems;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author firemanphil
 *         Date: 18/11/14
 *         Time: 11:49
 */
@Component
public class ItemStorage {

    private static Logger logger = Logger.getLogger( ItemStorage.class.getName() );

    // 5 mins
    private static final int MOST_POPULAR_EXPIRE_TIME = 5 * 60;
    // 15 mins
    private static final int RECENT_ITEMS_EXPIRE_TIME = 15 * 60;
    private static final int MEMCACHE_EXCLUSIONS_EXPIRE_SECS = 30 * 60;
    private final PersistenceProvider provider;
    private final DogpileHandler dogpileHandler;

    @Autowired
    public ItemStorage(PersistenceProvider provider, DogpileHandler dogpileHandler) {
        this.provider = provider;
        this.dogpileHandler = dogpileHandler;
    }

    private String getMostPopularCacheKey(String client,Set<Integer> dimensions, int numItems)
    {
    	return MemCacheKeys.getPopularItems(client, dimensions, numItems);
    }

    public List<SqlItemPeer.ItemAndScore> retrieveMostPopularItemsWithScore(final String client, final int numItems, final Set<Integer> dimensions){
    	return retrieveMostPopularItemsWithScoreImpl(getMostPopularCacheKey(client, dimensions, numItems), client, numItems, dimensions);
    }

    private List<SqlItemPeer.ItemAndScore> retrieveMostPopularItemsWithScoreImpl(final String key,final String client, final int numItems, final Set<Integer> dimensions){

        List<SqlItemPeer.ItemAndScore> retrievedItems = retrieveUsingJSON(key, numItems,
                new UpdateRetriever<List<SqlItemPeer.ItemAndScore>>() {
                    @Override
                    public List<SqlItemPeer.ItemAndScore> retrieve() throws Exception {
                        return provider.getItemPersister(client).retrieveMostPopularItems(numItems, dimensions);
                    }
                }, new TypeReference<List<SqlItemPeer.ItemAndScore>>() {}, MOST_POPULAR_EXPIRE_TIME);

        return retrievedItems==null? Collections.EMPTY_LIST: retrievedItems;
    }

    public FilteredItems retrieveMostPopularItems(final String client, final int numItems, final Set<Integer> dimensions){
    	final String key = getMostPopularCacheKey(client, dimensions, numItems);
    	List<SqlItemPeer.ItemAndScore> retrievedItems = retrieveMostPopularItemsWithScoreImpl(key, client, numItems, dimensions);
    	List<Long> toReturn = new ArrayList<>();
        for (SqlItemPeer.ItemAndScore itemAndScore : retrievedItems){
            toReturn.add(itemAndScore.item);
        }
        return new FilteredItems(toReturn.size() >= numItems ? new ArrayList<>(toReturn).subList(0,numItems) : toReturn, SecurityHashPeer.md5(key));
    }

    public FilteredItems retrieveRecentlyAddedItems(final String client, final int numItems, final Set<Integer> dimensions){
        final String key = MemCacheKeys.getRecentItems(client, dimensions, numItems);
        List<Long> retrievedItems = retrieveUsingJSON(key, numItems, new UpdateRetriever<List<Long>>() {
            @Override
            public List<Long> retrieve() throws Exception {
                return provider.getItemPersister(client).getRecentItemIds(dimensions, numItems, null);
            }
        }, new TypeReference<List<Long>>() {}, RECENT_ITEMS_EXPIRE_TIME);
        return new FilteredItems(retrievedItems==null? Collections.EMPTY_LIST : retrievedItems,SecurityHashPeer.md5(key));
    }

    public FilteredItems retrieveExplicitItems(final String client,final Set<Long> items)

    {
    	final String key = MemCacheKeys.getExplicitItemsIncluderKey(client, items);
    	List<Long> retrievedItems = retrieveUsingJSON(key, items.size(), new UpdateRetriever<List<Long>>() {
            @Override
            public List<Long> retrieve() throws Exception {
                return new ArrayList<Long>(items);
            }
        }, new TypeReference<List<Long>>() {}, RECENT_ITEMS_EXPIRE_TIME);
        return new FilteredItems(retrievedItems==null? Collections.EMPTY_LIST : retrievedItems,SecurityHashPeer.md5(key));
    }

    private <T extends List> T retrieveUsingJSON(String key, int numItemsRequired, UpdateRetriever<T> retriever,
                                                 TypeReference<T> typeRetriever,int expireTime) {
    	final ObjectMapper mapper = new ObjectMapper();
    	T retrievedItems = null;
    	String json = (String) MemCachePeer.get(key);
    	if (json != null)
    	{
    		try
    		{
    			retrievedItems = mapper.readValue(json,typeRetriever);
    		} catch (Exception e1) {
    			logger.error("Failed to parae json "+json,e1);
    		}
    	}
        if (retrievedItems==null || retrievedItems.size() < numItemsRequired) retrievedItems = null;
        T newerRetrievedItems = null;
        try {
            newerRetrievedItems = dogpileHandler.retrieveUpdateIfRequired(key, retrievedItems, retriever, expireTime);
            if(newerRetrievedItems!=null){
            	String result = mapper.writeValueAsString(newerRetrievedItems);
                MemCachePeer.put(key, result, expireTime);
                return newerRetrievedItems;
            }
        } catch (Exception e) {
            logger.warn("Couldn't retrieve items when using dogpile handler" , e);
        }
        return retrievedItems;
    }

    public Set<Long> retrieveIgnoredItems(String client, String clientUserId) {
        // no dogpile handler as this will change regularly and we aren't using the DB

        final String exKey = MemCacheKeys.getExcludedItemsForRecommendations(client, clientUserId);
        Set<Long> ignored =  (Set<Long>) MemCachePeer.get(exKey);
        return ignored==null? Collections.<Long>emptySet() : ignored;
    }

    public void persistIgnoredItems(String client, String clientUserId, Set<Long> ignoredItems){

        final String exKey = MemCacheKeys.getExcludedItemsForRecommendations(client, clientUserId);
        MemCachePeer.put(exKey, ignoredItems, MEMCACHE_EXCLUSIONS_EXPIRE_SECS);
    }
}