text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "define.h"
#include "API.h"
#include "control.h"
#include "typedef.h"
#include "structs.h"
#include "tuning_parameters.h"
#ifdef FIXED_POINT
#include "main_FIX.h"
#else
#include "main_FLP.h"
#endif

/***************************************/
/* Read control structure from encoder */
/***************************************/
static opus_int silk_QueryEncoder(                      /* O    Returns error code                              */
    const void                      *encState,          /* I    State                                           */
    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
);

/****************************************/
/* Encoder functions                    */
/****************************************/

opus_int silk_Get_Encoder_Size(                         /* O    Returns error code                              */
    opus_int                        *encSizeBytes       /* O    Number of bytes in SILK encoder state           */
)
{
    opus_int ret = SILK_NO_ERROR;

    *encSizeBytes = sizeof( silk_encoder );

    return ret;
}

/*************************/
/* Init or Reset encoder */
/*************************/
opus_int silk_InitEncoder(                              /* O    Returns error code                              */
    void                            *encState,          /* I/O  State                                           */
    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
)
{
    silk_encoder *psEnc;
    opus_int n, ret = SILK_NO_ERROR;

    psEnc = (silk_encoder *)encState;

    /* Reset encoder */
    silk_memset( psEnc, 0, sizeof( silk_encoder ) );
    for( n = 0; n < ENCODER_NUM_CHANNELS; n++ ) {
        if( ret += silk_init_encoder( &psEnc->state_Fxx[ n ] ) ) {
            silk_assert( 0 );
        }
    }

    psEnc->nChannelsAPI = 1;
    psEnc->nChannelsInternal = 1;

    /* Read control structure */
    if( ret += silk_QueryEncoder( encState, encStatus ) ) {
        silk_assert( 0 );
    }

    return ret;
}

/***************************************/
/* Read control structure from encoder */
/***************************************/
static opus_int silk_QueryEncoder(                      /* O    Returns error code                              */
    const void                      *encState,          /* I    State                                           */
    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
)
{
    opus_int ret = SILK_NO_ERROR;
    silk_encoder_state_Fxx *state_Fxx;
    silk_encoder *psEnc = (silk_encoder *)encState;

    state_Fxx = psEnc->state_Fxx;

    encStatus->nChannelsAPI              = psEnc->nChannelsAPI;
    encStatus->nChannelsInternal         = psEnc->nChannelsInternal;
    encStatus->API_sampleRate            = state_Fxx[ 0 ].sCmn.API_fs_Hz;
    encStatus->maxInternalSampleRate     = state_Fxx[ 0 ].sCmn.maxInternal_fs_Hz;
    encStatus->minInternalSampleRate     = state_Fxx[ 0 ].sCmn.minInternal_fs_Hz;
    encStatus->desiredInternalSampleRate = state_Fxx[ 0 ].sCmn.desiredInternal_fs_Hz;
    encStatus->payloadSize_ms            = state_Fxx[ 0 ].sCmn.PacketSize_ms;
    encStatus->bitRate                   = state_Fxx[ 0 ].sCmn.TargetRate_bps;
    encStatus->packetLossPercentage      = state_Fxx[ 0 ].sCmn.PacketLoss_perc;
    encStatus->complexity                = state_Fxx[ 0 ].sCmn.Complexity;
    encStatus->useInBandFEC              = state_Fxx[ 0 ].sCmn.useInBandFEC;
    encStatus->useDTX                    = state_Fxx[ 0 ].sCmn.useDTX;
    encStatus->useCBR                    = state_Fxx[ 0 ].sCmn.useCBR;
    encStatus->internalSampleRate        = silk_SMULBB( state_Fxx[ 0 ].sCmn.fs_kHz, 1000 );
    encStatus->allowBandwidthSwitch      = state_Fxx[ 0 ].sCmn.allow_bandwidth_switch;
    encStatus->inWBmodeWithoutVariableLP = state_Fxx[ 0 ].sCmn.fs_kHz == 16 && state_Fxx[ 0 ].sCmn.sLP.mode == 0;

    return ret;
}

/**************************/
/* Encode frame with Silk */
/**************************/
/* Note: if prefillFlag is set, the input must contain 10 ms of audio, irrespective of what                     */
/* encControl->payloadSize_ms is set to                                                                         */
opus_int silk_Encode(                                   /* O    Returns error code                              */
    void                            *encState,          /* I/O  State                                           */
    silk_EncControlStruct           *encControl,        /* I    Control status                                  */
    const opus_int16                *samplesIn,         /* I    Speech sample input vector                      */
    opus_int                        nSamplesIn,         /* I    Number of samples in input vector               */
    ec_enc                          *psRangeEnc,        /* I/O  Compressor data structure                       */
    opus_int32                      *nBytesOut,         /* I/O  Number of bytes in payload (input: Max bytes)   */
    const opus_int                  prefillFlag         /* I    Flag to indicate prefilling buffers no coding   */
)
{
    opus_int   n, i, nBits, flags, tmp_payloadSize_ms = 0, tmp_complexity = 0, ret = 0;
    opus_int   nSamplesToBuffer, nBlocksOf10ms, nSamplesFromInput = 0;
    opus_int   speech_act_thr_for_switch_Q8;
    opus_int32 TargetRate_bps, MStargetRates_bps[ 2 ], channelRate_bps, LBRR_symbol, sum;
    silk_encoder *psEnc = ( silk_encoder * )encState;
    opus_int16 buf[ MAX_FRAME_LENGTH_MS * MAX_API_FS_KHZ ];
    opus_int transition, curr_block, tot_blocks;

    psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded = psEnc->state_Fxx[ 1 ].sCmn.nFramesEncoded = 0;

    /* Check values in encoder control structure */
    if( ( ret = check_control_input( encControl ) != 0 ) ) {
        silk_assert( 0 );
        return ret;
    }

    encControl->switchReady = 0;

    if( encControl->nChannelsInternal > psEnc->nChannelsInternal ) {
        /* Mono -> Stereo transition: init state of second channel and stereo state */
        ret += silk_init_encoder( &psEnc->state_Fxx[ 1 ] );
        silk_memset( psEnc->sStereo.pred_prev_Q13, 0, sizeof( psEnc->sStereo.pred_prev_Q13 ) );
        silk_memset( psEnc->sStereo.sSide, 0, sizeof( psEnc->sStereo.sSide ) );
        psEnc->sStereo.mid_side_amp_Q0[ 0 ] = 0;
        psEnc->sStereo.mid_side_amp_Q0[ 1 ] = 1;
        psEnc->sStereo.mid_side_amp_Q0[ 2 ] = 0;
        psEnc->sStereo.mid_side_amp_Q0[ 3 ] = 1;
        psEnc->sStereo.width_prev_Q14 = 0;
        psEnc->sStereo.smth_width_Q14 = SILK_FIX_CONST( 1, 14 );
        if( psEnc->nChannelsAPI == 2 ) {
            silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state, &psEnc->state_Fxx[ 0 ].sCmn.resampler_state, sizeof( silk_resampler_state_struct ) );
            silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.In_HP_State,     &psEnc->state_Fxx[ 0 ].sCmn.In_HP_State,     sizeof( psEnc->state_Fxx[ 1 ].sCmn.In_HP_State ) );
        }
    }

    transition = (encControl->payloadSize_ms != psEnc->state_Fxx[ 0 ].sCmn.PacketSize_ms) || (psEnc->nChannelsInternal != encControl->nChannelsInternal);

    psEnc->nChannelsAPI = encControl->nChannelsAPI;
    psEnc->nChannelsInternal = encControl->nChannelsInternal;

    nBlocksOf10ms = silk_DIV32( 100 * nSamplesIn, encControl->API_sampleRate );
    tot_blocks = ( nBlocksOf10ms > 1 ) ? nBlocksOf10ms >> 1 : 1;
    curr_block = 0;
    if( prefillFlag ) {
        /* Only accept input length of 10 ms */
        if( nBlocksOf10ms != 1 ) {
            ret = SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
            silk_assert( 0 );
            return ret;
        }
        /* Reset Encoder */
        for( n = 0; n < encControl->nChannelsInternal; n++ ) {
            if( (ret = silk_init_encoder( &psEnc->state_Fxx[ n ] ) ) != 0 ) {
                silk_assert( 0 );
            }
        }
        tmp_payloadSize_ms = encControl->payloadSize_ms;
        encControl->payloadSize_ms = 10;
        tmp_complexity = encControl->complexity;
        encControl->complexity = 0;
        for( n = 0; n < encControl->nChannelsInternal; n++ ) {
            psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
            psEnc->state_Fxx[ n ].sCmn.prefillFlag = 1;
        }
    } else {
        /* Only accept input lengths that are a multiple of 10 ms */
        if( nBlocksOf10ms * encControl->API_sampleRate != 100 * nSamplesIn || nSamplesIn < 0 ) {
            ret = SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
            silk_assert( 0 );
            return ret;
        }
        /* Make sure no more than one packet can be produced */
        if( 1000 * (opus_int32)nSamplesIn > encControl->payloadSize_ms * encControl->API_sampleRate ) {
            ret = SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
            silk_assert( 0 );
            return ret;
        }
    }

    TargetRate_bps = silk_RSHIFT32( encControl->bitRate, encControl->nChannelsInternal - 1 );
    for( n = 0; n < encControl->nChannelsInternal; n++ ) {
        /* Force the side channel to the same rate as the mid */
        opus_int force_fs_kHz = (n==1) ? psEnc->state_Fxx[0].sCmn.fs_kHz : 0;
        if( ( ret = silk_control_encoder( &psEnc->state_Fxx[ n ], encControl, TargetRate_bps, psEnc->allowBandwidthSwitch, n, force_fs_kHz ) ) != 0 ) {
            silk_assert( 0 );
            return ret;
        }
        if( psEnc->state_Fxx[n].sCmn.first_frame_after_reset || transition ) {
            for( i = 0; i < psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket; i++ ) {
                psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ] = 0;
            }
        }
        psEnc->state_Fxx[ n ].sCmn.inDTX = psEnc->state_Fxx[ n ].sCmn.useDTX;
    }
    silk_assert( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 0 ].sCmn.fs_kHz == psEnc->state_Fxx[ 1 ].sCmn.fs_kHz );

    /* Input buffering/resampling and encoding */
    while( 1 ) {
        nSamplesToBuffer  = psEnc->state_Fxx[ 0 ].sCmn.frame_length - psEnc->state_Fxx[ 0 ].sCmn.inputBufIx;
        nSamplesToBuffer  = silk_min( nSamplesToBuffer, 10 * nBlocksOf10ms * psEnc->state_Fxx[ 0 ].sCmn.fs_kHz );
        nSamplesFromInput = silk_DIV32_16( nSamplesToBuffer * psEnc->state_Fxx[ 0 ].sCmn.API_fs_Hz, psEnc->state_Fxx[ 0 ].sCmn.fs_kHz * 1000 );
        /* Resample and write to buffer */
        if( encControl->nChannelsAPI == 2 && encControl->nChannelsInternal == 2 ) {
            opus_int id = psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded;
            for( n = 0; n < nSamplesFromInput; n++ ) {
                buf[ n ] = samplesIn[ 2 * n ];
            }
            /* Making sure to start both resamplers from the same state when switching from mono to stereo */
            if( psEnc->nPrevChannelsInternal == 1 && id==0 ) {
               silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state, &psEnc->state_Fxx[ 0 ].sCmn.resampler_state, sizeof(psEnc->state_Fxx[ 1 ].sCmn.resampler_state));
            }

            ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
                &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
            psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;

            nSamplesToBuffer  = psEnc->state_Fxx[ 1 ].sCmn.frame_length - psEnc->state_Fxx[ 1 ].sCmn.inputBufIx;
            nSamplesToBuffer  = silk_min( nSamplesToBuffer, 10 * nBlocksOf10ms * psEnc->state_Fxx[ 1 ].sCmn.fs_kHz );
            for( n = 0; n < nSamplesFromInput; n++ ) {
                buf[ n ] = samplesIn[ 2 * n + 1 ];
            }
            ret += silk_resampler( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state,
                &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );

            psEnc->state_Fxx[ 1 ].sCmn.inputBufIx += nSamplesToBuffer;
        } else if( encControl->nChannelsAPI == 2 && encControl->nChannelsInternal == 1 ) {
            /* Combine left and right channels before resampling */
            for( n = 0; n < nSamplesFromInput; n++ ) {
                sum = samplesIn[ 2 * n ] + samplesIn[ 2 * n + 1 ];
                buf[ n ] = (opus_int16)silk_RSHIFT_ROUND( sum,  1 );
            }
            ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
                &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
            /* On the first mono frame, average the results for the two resampler states  */
            if( psEnc->nPrevChannelsInternal == 2 && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == 0 ) {
               ret += silk_resampler( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state,
                   &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
               for( n = 0; n < psEnc->state_Fxx[ 0 ].sCmn.frame_length; n++ ) {
                  psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx+n+2 ] =
                        silk_RSHIFT(psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx+n+2 ]
                                  + psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx+n+2 ], 1);
               }
            }
            psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
        } else {
            silk_assert( encControl->nChannelsAPI == 1 && encControl->nChannelsInternal == 1 );
            silk_memcpy(buf, samplesIn, nSamplesFromInput*sizeof(opus_int16));
            ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
                &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
            psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
        }

        samplesIn  += nSamplesFromInput * encControl->nChannelsAPI;
        nSamplesIn -= nSamplesFromInput;

        /* Default */
        psEnc->allowBandwidthSwitch = 0;

        /* Silk encoder */
        if( psEnc->state_Fxx[ 0 ].sCmn.inputBufIx >= psEnc->state_Fxx[ 0 ].sCmn.frame_length ) {
            /* Enough data in input buffer, so encode */
            silk_assert( psEnc->state_Fxx[ 0 ].sCmn.inputBufIx == psEnc->state_Fxx[ 0 ].sCmn.frame_length );
            silk_assert( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 1 ].sCmn.inputBufIx == psEnc->state_Fxx[ 1 ].sCmn.frame_length );

            /* Deal with LBRR data */
            if( psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == 0 && !prefillFlag ) {
                /* Create space at start of payload for VAD and FEC flags */
                opus_uint8 iCDF[ 2 ] = { 0, 0 };
                iCDF[ 0 ] = 256 - silk_RSHIFT( 256, ( psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket + 1 ) * encControl->nChannelsInternal );
                ec_enc_icdf( psRangeEnc, 0, iCDF, 8 );

                /* Encode any LBRR data from previous packet */
                /* Encode LBRR flags */
                for( n = 0; n < encControl->nChannelsInternal; n++ ) {
                    LBRR_symbol = 0;
                    for( i = 0; i < psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket; i++ ) {
                        LBRR_symbol |= silk_LSHIFT( psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ], i );
                    }
                    psEnc->state_Fxx[ n ].sCmn.LBRR_flag = LBRR_symbol > 0 ? 1 : 0;
                    if( LBRR_symbol && psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket > 1 ) {
                        ec_enc_icdf( psRangeEnc, LBRR_symbol - 1, silk_LBRR_flags_iCDF_ptr[ psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket - 2 ], 8 );
                    }
                }

                /* Code LBRR indices and excitation signals */
                for( i = 0; i < psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket; i++ ) {
                    for( n = 0; n < encControl->nChannelsInternal; n++ ) {
                        if( psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ] ) {
                            opus_int condCoding;

                            if( encControl->nChannelsInternal == 2 && n == 0 ) {
                                silk_stereo_encode_pred( psRangeEnc, psEnc->sStereo.predIx[ i ] );
                                /* For LBRR data there's no need to code the mid-only flag if the side-channel LBRR flag is set */
                                if( psEnc->state_Fxx[ 1 ].sCmn.LBRR_flags[ i ] == 0 ) {
                                    silk_stereo_encode_mid_only( psRangeEnc, psEnc->sStereo.mid_only_flags[ i ] );
                                }
                            }
                            /* Use conditional coding if previous frame available */
                            if( i > 0 && psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i - 1 ] ) {
                                condCoding = CODE_CONDITIONALLY;
                            } else {
                                condCoding = CODE_INDEPENDENTLY;
                            }
                            silk_encode_indices( &psEnc->state_Fxx[ n ].sCmn, psRangeEnc, i, 1, condCoding );
                            silk_encode_pulses( psRangeEnc, psEnc->state_Fxx[ n ].sCmn.indices_LBRR[i].signalType, psEnc->state_Fxx[ n ].sCmn.indices_LBRR[i].quantOffsetType,
                                psEnc->state_Fxx[ n ].sCmn.pulses_LBRR[ i ], psEnc->state_Fxx[ n ].sCmn.frame_length );
                        }
                    }
                }

                /* Reset LBRR flags */
                for( n = 0; n < encControl->nChannelsInternal; n++ ) {
                    silk_memset( psEnc->state_Fxx[ n ].sCmn.LBRR_flags, 0, sizeof( psEnc->state_Fxx[ n ].sCmn.LBRR_flags ) );
                }
            }

            silk_HP_variable_cutoff( psEnc->state_Fxx );

            /* Total target bits for packet */
            nBits = silk_DIV32_16( silk_MUL( encControl->bitRate, encControl->payloadSize_ms ), 1000 );
            /* Subtract half of the bits already used */
            if( !prefillFlag ) {
                nBits -= ec_tell( psRangeEnc ) >> 1;
            }
            /* Divide by number of uncoded frames left in packet */
            nBits = silk_DIV32_16( nBits, psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket - psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded );
            /* Convert to bits/second */
            if( encControl->payloadSize_ms == 10 ) {
                TargetRate_bps = silk_SMULBB( nBits, 100 );
            } else {
                TargetRate_bps = silk_SMULBB( nBits, 50 );
            }
            /* Subtract fraction of bits in excess of target in previous packets */
            TargetRate_bps -= silk_DIV32_16( silk_MUL( psEnc->nBitsExceeded, 1000 ), BITRESERVOIR_DECAY_TIME_MS );
            /* Never exceed input bitrate */
            TargetRate_bps = silk_LIMIT( TargetRate_bps, encControl->bitRate, 5000 );

            /* Convert Left/Right to Mid/Side */
            if( encControl->nChannelsInternal == 2 ) {
                silk_stereo_LR_to_MS( &psEnc->sStereo, &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ 2 ], &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ 2 ],
                    psEnc->sStereo.predIx[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ], &psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ],
                    MStargetRates_bps, TargetRate_bps, psEnc->state_Fxx[ 0 ].sCmn.speech_activity_Q8, encControl->toMono,
                    psEnc->state_Fxx[ 0 ].sCmn.fs_kHz, psEnc->state_Fxx[ 0 ].sCmn.frame_length );
                if( psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] == 0 ) {
                    /* Reset side channel encoder memory for first frame with side coding */
                    if( psEnc->prev_decode_only_middle == 1 ) {
                        silk_memset( &psEnc->state_Fxx[ 1 ].sShape,               0, sizeof( psEnc->state_Fxx[ 1 ].sShape ) );
                        silk_memset( &psEnc->state_Fxx[ 1 ].sPrefilt,             0, sizeof( psEnc->state_Fxx[ 1 ].sPrefilt ) );
                        silk_memset( &psEnc->state_Fxx[ 1 ].sCmn.sNSQ,            0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.sNSQ ) );
                        silk_memset( psEnc->state_Fxx[ 1 ].sCmn.prev_NLSFq_Q15,   0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.prev_NLSFq_Q15 ) );
                        silk_memset( &psEnc->state_Fxx[ 1 ].sCmn.sLP.In_LP_State, 0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.sLP.In_LP_State ) );
                        psEnc->state_Fxx[ 1 ].sCmn.prevLag                 = 100;
                        psEnc->state_Fxx[ 1 ].sCmn.sNSQ.lagPrev            = 100;
                        psEnc->state_Fxx[ 1 ].sShape.LastGainIndex         = 10;
                        psEnc->state_Fxx[ 1 ].sCmn.prevSignalType          = TYPE_NO_VOICE_ACTIVITY;
                        psEnc->state_Fxx[ 1 ].sCmn.sNSQ.prev_gain_Q16      = 65536;
                        psEnc->state_Fxx[ 1 ].sCmn.first_frame_after_reset = 1;
                    }
                    silk_encode_do_VAD_Fxx( &psEnc->state_Fxx[ 1 ] );
                } else {
                    psEnc->state_Fxx[ 1 ].sCmn.VAD_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] = 0;
                }
                if( !prefillFlag ) {
                    silk_stereo_encode_pred( psRangeEnc, psEnc->sStereo.predIx[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] );
                    if( psEnc->state_Fxx[ 1 ].sCmn.VAD_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] == 0 ) {
                        silk_stereo_encode_mid_only( psRangeEnc, psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] );
                    }
                }
            } else {
                /* Buffering */
                silk_memcpy( psEnc->state_Fxx[ 0 ].sCmn.inputBuf, psEnc->sStereo.sMid, 2 * sizeof( opus_int16 ) );
                silk_memcpy( psEnc->sStereo.sMid, &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.frame_length ], 2 * sizeof( opus_int16 ) );
            }
            silk_encode_do_VAD_Fxx( &psEnc->state_Fxx[ 0 ] );

            /* Encode */
            for( n = 0; n < encControl->nChannelsInternal; n++ ) {
                opus_int maxBits, useCBR;

                /* Handling rate constraints */
                maxBits = encControl->maxBits;
                if( tot_blocks == 2 && curr_block == 0 ) {
                    maxBits = maxBits * 3 / 5;
                } else if( tot_blocks == 3 ) {
                    if( curr_block == 0 ) {
                        maxBits = maxBits * 2 / 5;
                    } else if( curr_block == 1 ) {
                        maxBits = maxBits * 3 / 4;
                    }
                }
                useCBR = encControl->useCBR && curr_block == tot_blocks - 1;

                if( encControl->nChannelsInternal == 1 ) {
                    channelRate_bps = TargetRate_bps;
                } else {
                    channelRate_bps = MStargetRates_bps[ n ];
                    if( n == 0 && MStargetRates_bps[ 1 ] > 0 ) {
                        useCBR = 0;
                        /* Give mid up to 1/2 of the max bits for that frame */
                        maxBits -= encControl->maxBits / ( tot_blocks * 2 );
                    }
                }

                if( channelRate_bps > 0 ) {
                    opus_int condCoding;

                    silk_control_SNR( &psEnc->state_Fxx[ n ].sCmn, channelRate_bps );

                    /* Use independent coding if no previous frame available */
                    if( psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded - n <= 0 ) {
                        condCoding = CODE_INDEPENDENTLY;
                    } else if( n > 0 && psEnc->prev_decode_only_middle ) {
                        /* If we skipped a side frame in this packet, we don't
                           need LTP scaling; the LTP state is well-defined. */
                        condCoding = CODE_INDEPENDENTLY_NO_LTP_SCALING;
                    } else {
                        condCoding = CODE_CONDITIONALLY;
                    }
                    if( ( ret = silk_encode_frame_Fxx( &psEnc->state_Fxx[ n ], nBytesOut, psRangeEnc, condCoding, maxBits, useCBR ) ) != 0 ) {
                        silk_assert( 0 );
                    }
                }
                psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
                psEnc->state_Fxx[ n ].sCmn.inputBufIx = 0;
                psEnc->state_Fxx[ n ].sCmn.nFramesEncoded++;
            }
            psEnc->prev_decode_only_middle = psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded - 1 ];

            /* Insert VAD and FEC flags at beginning of bitstream */
            if( *nBytesOut > 0 && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket) {
                flags = 0;
                for( n = 0; n < encControl->nChannelsInternal; n++ ) {
                    for( i = 0; i < psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket; i++ ) {
                        flags  = silk_LSHIFT( flags, 1 );
                        flags |= psEnc->state_Fxx[ n ].sCmn.VAD_flags[ i ];
                    }
                    flags  = silk_LSHIFT( flags, 1 );
                    flags |= psEnc->state_Fxx[ n ].sCmn.LBRR_flag;
                }
                if( !prefillFlag ) {
                    ec_enc_patch_initial_bits( psRangeEnc, flags, ( psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket + 1 ) * encControl->nChannelsInternal );
                }

                /* Return zero bytes if all channels DTXed */
                if( psEnc->state_Fxx[ 0 ].sCmn.inDTX && ( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 1 ].sCmn.inDTX ) ) {
                    *nBytesOut = 0;
                }

                psEnc->nBitsExceeded += *nBytesOut * 8;
                psEnc->nBitsExceeded -= silk_DIV32_16( silk_MUL( encControl->bitRate, encControl->payloadSize_ms ), 1000 );
                psEnc->nBitsExceeded  = silk_LIMIT( psEnc->nBitsExceeded, 0, 10000 );

                /* Update flag indicating if bandwidth switching is allowed */
                speech_act_thr_for_switch_Q8 = silk_SMLAWB( SILK_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ),
                    SILK_FIX_CONST( ( 1 - SPEECH_ACTIVITY_DTX_THRES ) / MAX_BANDWIDTH_SWITCH_DELAY_MS, 16 + 8 ), psEnc->timeSinceSwitchAllowed_ms );
                if( psEnc->state_Fxx[ 0 ].sCmn.speech_activity_Q8 < speech_act_thr_for_switch_Q8 ) {
                    psEnc->allowBandwidthSwitch = 1;
                    psEnc->timeSinceSwitchAllowed_ms = 0;
                } else {
                    psEnc->allowBandwidthSwitch = 0;
                    psEnc->timeSinceSwitchAllowed_ms += encControl->payloadSize_ms;
                }
            }

            if( nSamplesIn == 0 ) {
                break;
            }
        } else {
            break;
        }
        curr_block++;
    }

    psEnc->nPrevChannelsInternal = encControl->nChannelsInternal;

    encControl->allowBandwidthSwitch = psEnc->allowBandwidthSwitch;
    encControl->inWBmodeWithoutVariableLP = psEnc->state_Fxx[ 0 ].sCmn.fs_kHz == 16 && psEnc->state_Fxx[ 0 ].sCmn.sLP.mode == 0;
    encControl->internalSampleRate = silk_SMULBB( psEnc->state_Fxx[ 0 ].sCmn.fs_kHz, 1000 );
    encControl->stereoWidth_Q14 = encControl->toMono ? 0 : psEnc->sStereo.smth_width_Q14;
    if( prefillFlag ) {
        encControl->payloadSize_ms = tmp_payloadSize_ms;
        encControl->complexity = tmp_complexity;
        for( n = 0; n < encControl->nChannelsInternal; n++ ) {
            psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
            psEnc->state_Fxx[ n ].sCmn.prefillFlag = 0;
        }
    }

    return ret;
}


text:
class CreateUrls < ActiveRecord::Migration
  def change
    create_table :urls do |t|
      t.string   :url
      t.string   :code

      t.timestamps
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.taobao.tddl.rule.model.sqljep;

/**
 * <pre>
 * AND节点 ,在实际的SQL中,实际上是类似
 * [Comparative]              [comparative]
 *          \                  /
 *            \               /
 *             [ComparativeAnd]
 * 类似这样的节点出现
 * </pre>
 *
 * @author shenxun
 */
public class ComparativeAND extends ComparativeBaseList {

    public ComparativeAND(int function, Comparable<?> value){
        super(function, value);
    }

    public ComparativeAND(){
    }

    public ComparativeAND(Comparative item){
        super(item);
    }

    protected String getRelation() {
        return " and ";
    }

}


text:
import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom'
import base64url from 'base64url';

export class TreeNode extends PureComponent {
    static displayName = TreeNode.name;

    constructor(props) {
        super(props);
        this.state = { children: [], isCollapsed: true };
        this.toggleTreeNode = this.toggleTreeNode.bind(this);
        this.handleDrillIntoClick = this.handleDrillIntoClick.bind(this);
    }

    handleDrillIntoClick(d) {

        var drillType = '/api/drillinto/exclusive?'
        if (d === 'i') {
            drillType = '/api/drillinto/inclusive?';
        }

        fetch(drillType + TreeNode.constructAPICacheKeyFromRouteKey(this.props.routeKey) + '&name=' + this.props.callTreeNodeId + '&path=' + this.props.node.path, { method: 'GET', headers: { 'Content-Type': 'application/json' } })
        .then(res => res.json())
        .then(data => {
            var newRouteKey = JSON.parse(base64url.decode(this.props.routeKey, "utf8"));
            newRouteKey.k = data;
            window.location.href = '/ui/hotspots/' + base64url.encode(JSON.stringify(newRouteKey));
        });
    }

    toggleTreeNode() {
        if (this.state.isCollapsed) {
            this.expandTreeNode();
        }
        else {
            this.collapseTreeNode();
        }
    }

    collapseTreeNode() {
        this.setState({ children: [], isCollapsed: true });
    }

    expandTreeNode() {
        fetch('/api/callerchildren?' + TreeNode.constructAPICacheKeyFromRouteKey(this.props.routeKey) + '&name=' + this.props.callTreeNodeId + '&path=' + this.props.node.path, { method: 'GET', headers: { 'Content-Type': 'application/json' } })
            .then(res => res.json())
            .then(data => { this.setState({ children: data, isCollapsed: false }); });
    }

    static constructAPICacheKeyFromRouteKey(r) {
        var routeKey = JSON.parse(base64url.decode(r, "utf8"));
        return 'filename=' + routeKey.a + '&stackType=' + routeKey.b + '&pid=' + routeKey.c + '&start=' + base64url.encode(routeKey.d, "utf8") + '&end=' + base64url.encode(routeKey.e, "utf8") + '&groupPats=' + base64url.encode(routeKey.f, "utf8") + '&foldPats=' + base64url.encode(routeKey.g, "utf8") + '&incPats=' + base64url.encode(routeKey.h, "utf8") + '&excPats=' + base64url.encode(routeKey.i, "utf8") + '&foldPct=' + routeKey.j + '&drillIntoKey=' + routeKey.k;
    }

    static renderTreeNode(routeKey, node, indent, callTreeNodeId, children, isCollapsed, toggleTreeNode, obj) {
        return (
            <React.Fragment>

                    {node.hasChildren && <button className="btn btn-secondary btn-tiny" onClick={toggleTreeNode}>{isCollapsed ? "+" : "-"}</button>} <Link to={`/ui/callers/${routeKey}/${node.base64EncodedId}`}>{node.name}</Link>
                    {node.exclusiveMetricPercent}%
                    <button onClick={() => obj.handleDrillIntoClick('e')}>{node.exclusiveCount}</button>
                    {node.inclusiveMetricPercent}%
                    <button onClick={() => obj.handleDrillIntoClick('i')}>{node.inclusiveCount}</button>
                    {node.exclusiveFoldedMetric}
                    {node.inclusiveMetricByTimeString}
                    {node.firstTimeRelativeMSec}
                    {node.lastTimeRelativeMSec}

                {children.map(child => <TreeNode key={`${child.base64EncodedId}`} routeKey={routeKey} node={child} indent={indent + 10} callTreeNodeId={callTreeNodeId}></TreeNode>)}
            </React.Fragment>
        );
    }

    render() {
        return TreeNode.renderTreeNode(this.props.routeKey, this.props.node, this.props.indent, this.props.callTreeNodeId, this.state.children, this.state.isCollapsed, this.toggleTreeNode, this);
    }
}


text:
import unittest

from katas.kyu_7.area_of_a_circle import circleArea

class CircleAreaTestCase(unittest.TestCase):
    def test_equals(self):
        self.assertEqual(circleArea(43.2673), 5881.25)

    def test_equals_2(self):
        self.assertEqual(circleArea(68), 14526.72)

    def test_false(self):
        self.assertFalse(circleArea(-1485.86))

    def test_false_2(self):
        self.assertFalse(circleArea(0))

    def test_false_3(self):
        self.assertFalse(circleArea('number'))


text:
using System;
using GraphQL.Types;

namespace GraphQL.Tests
{
    public class StarWarsSchema : Schema
    {
        public StarWarsSchema(Func<Type, GraphType> resolveType)
            : base(resolveType)
        {
            Query = (ObjectGraphType)resolveType(typeof (StarWarsQuery));
        }
    }
}


text:
package com.amazonaws.services.costexplorer.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.costexplorer.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CoverageNormalizedUnitsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CoverageNormalizedUnitsMarshaller {

    private static final MarshallingInfo<String> ONDEMANDNORMALIZEDUNITS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OnDemandNormalizedUnits").build();
    private static final MarshallingInfo<String> RESERVEDNORMALIZEDUNITS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReservedNormalizedUnits").build();
    private static final MarshallingInfo<String> TOTALRUNNINGNORMALIZEDUNITS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TotalRunningNormalizedUnits").build();
    private static final MarshallingInfo<String> COVERAGENORMALIZEDUNITSPERCENTAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CoverageNormalizedUnitsPercentage").build();

    private static final CoverageNormalizedUnitsMarshaller instance = new CoverageNormalizedUnitsMarshaller();

    public static CoverageNormalizedUnitsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CoverageNormalizedUnits coverageNormalizedUnits, ProtocolMarshaller protocolMarshaller) {

        if (coverageNormalizedUnits == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(coverageNormalizedUnits.getOnDemandNormalizedUnits(), ONDEMANDNORMALIZEDUNITS_BINDING);
            protocolMarshaller.marshall(coverageNormalizedUnits.getReservedNormalizedUnits(), RESERVEDNORMALIZEDUNITS_BINDING);
            protocolMarshaller.marshall(coverageNormalizedUnits.getTotalRunningNormalizedUnits(), TOTALRUNNINGNORMALIZEDUNITS_BINDING);
            protocolMarshaller.marshall(coverageNormalizedUnits.getCoverageNormalizedUnitsPercentage(), COVERAGENORMALIZEDUNITSPERCENTAGE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
function Disable-CFirewallStatefulFtp
{
    <#
    .SYNOPSIS
    Disables the `StatefulFtp` Windows firewall setting.

    .DESCRIPTION
    Uses the `netsh` command to disable the `StatefulFtp` Windows firewall setting.

    If the firewall isn't configurable, writes an error and returns without making any changes.

    .LINK
    Assert-CFirewallConfigurable

    .EXAMPLE
    Disable-CFirewallStatefulFtp

    Disables the `StatefulFtp` Windows firewall setting.
    #>
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
    )

    Set-StrictMode -Version 'Latest'

    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    if( -not (Assert-CFirewallConfigurable) )
    {
        return
    }

    Invoke-ConsoleCommand -Target 'firewall' `
                          -Action 'disabling stateful FTP' `
                          -ScriptBlock {
        netsh advfirewall set global StatefulFtp disable
    }
}


text:
package org.killbill.billing.beatrix.integration;

import java.math.BigDecimal;
import java.util.Collection;

import org.joda.time.DateTime;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.PriceListSet;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.entitlement.api.DefaultEntitlement;
import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.subscription.api.user.SubscriptionBaseBundle;
import org.killbill.billing.util.config.PaymentConfig;

import com.google.inject.Inject;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {

    @Inject
    private PaymentConfig paymentConfig;

    private Account account;
    private SubscriptionBaseBundle bundle;
    private String productName;
    private BillingPeriod term;
    private String planSetName;

    @Override
    @BeforeMethod(groups = "slow")
    public void beforeMethod() throws Exception {
        super.beforeMethod();
        account = createAccountWithNonOsgiPaymentMethod(getAccountData(25));
        assertNotNull(account);
        productName = "Shotgun";
        term = BillingPeriod.MONTHLY;
        planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
    }

    @Test(groups = "slow")
    public void testAutoPayOff() throws Exception {
        clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
        add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);

        final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE);
        assertNotNull(bpEntitlement);

        Collection<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 1);

        busHandler.pushExpectedEvents(NextEvent.PHASE);
        busHandler.pushExpectedEvents(NextEvent.INVOICE);
        clock.addDays(40); // After trial

        assertListenerStatus();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertEquals(cur.getBalance(), cur.getChargedAmount());
        }

        remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
        addDelayBceauseOfLackOfCorrectSynchro();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertTrue(cur.getBalance().compareTo(BigDecimal.ZERO) == 0);
            assertTrue(cur.getPaidAmount().compareTo(cur.getChargedAmount()) == 0);
        }
        assertListenerStatus();
    }

    @Test(groups = "slow")
    public void testAutoPayOffWithPaymentFailure() throws Exception {
        clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
        add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);

        final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE);
        assertNotNull(bpEntitlement);

        Collection<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 1);

        busHandler.pushExpectedEvents(NextEvent.PHASE);
        busHandler.pushExpectedEvents(NextEvent.INVOICE);
        clock.addDays(40); // After trial

        assertListenerStatus();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertEquals(cur.getBalance(), cur.getChargedAmount());
        }

        paymentPlugin.makeNextPaymentFailWithError();
        remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.PAYMENT_ERROR, NextEvent.INVOICE_PAYMENT_ERROR);
        addDelayBceauseOfLackOfCorrectSynchro();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertEquals(cur.getBalance(), cur.getChargedAmount());
        }
        assertListenerStatus();

        int nbDaysBeforeRetry = paymentConfig.getPaymentFailureRetryDays().get(0);

        // MOVE TIME FOR RETRY TO HAPPEN
        busHandler.pushExpectedEvents(NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
        clock.addDays(nbDaysBeforeRetry + 1);
        assertListenerStatus();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertTrue(cur.getBalance().compareTo(BigDecimal.ZERO) == 0);
            assertTrue(cur.getPaidAmount().compareTo(cur.getChargedAmount()) == 0);
        }
        assertListenerStatus();

    }

    @Test(groups = "slow")
    public void testAutoPayOffWithPaymentFailureOn_AUTO_PAY_OFF() throws Exception {
        clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
        add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);

        final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE);
        assertNotNull(bpEntitlement);

        Collection<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 1);

        // CREATE FIRST NON NULL INVOICE + FIRST PAYMENT/ATTEMPT -> AUTO_PAY_OFF
        busHandler.pushExpectedEvents(NextEvent.PHASE);
        busHandler.pushExpectedEvents(NextEvent.INVOICE);
        clock.addDays(31); // After trial
        assertListenerStatus();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertEquals(cur.getBalance(), cur.getChargedAmount());
        }

        // NOW SET PLUGIN TO THROW FAILURES
        paymentPlugin.makeNextPaymentFailWithError();
        remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.PAYMENT_ERROR, NextEvent.INVOICE_PAYMENT_ERROR);
        addDelayBceauseOfLackOfCorrectSynchro();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertEquals(cur.getBalance(), cur.getChargedAmount());
        }
        assertListenerStatus();

        // RE-ADD AUTO_PAY_OFF to ON
        int nbDaysBeforeRetry = paymentConfig.getPaymentFailureRetryDays().get(0);
        add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);

        // MOVE TIME FOR RETRY TO HAPPEN -> WILL BE DISCARDED SINCE AUTO_PAY_OFF IS SET
        clock.addDays(nbDaysBeforeRetry + 1);
        assertListenerStatus();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        assertEquals(invoices.size(), 2);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertEquals(cur.getBalance(), cur.getChargedAmount());
        }
        // We want to give some time for the retry to fail before we start clearing the state
        addDelayBceauseOfLackOfCorrectSynchro();

        // REMOVE AUTO_PAY_OFF -> WILL SCHEDULE A PAYMENT_RETRY
        paymentPlugin.clear();
        remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
        addDelayBceauseOfLackOfCorrectSynchro();

        invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), callContext);
        for (Invoice cur : invoices) {
            if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            assertTrue(cur.getBalance().compareTo(BigDecimal.ZERO) == 0);
            assertTrue(cur.getPaidAmount().compareTo(cur.getChargedAmount()) == 0);
        }
        assertListenerStatus();

    }

    private void addDelayBceauseOfLackOfCorrectSynchro() {
        // TODO When removing the tag, the payment system will schedule retries for payments that are in non terminal state
        // The issue is that at this point we know the event went on the bus but we don't know if the listener in payment completed
        // so we add some delay to ensure that it had time to complete. Failure to do so introduces some flakiness in the test because the clock
        // is moved right after that, and so payment may see the new value.
        //
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ignore) {
        }
    }
}


text:
/* eslint-env es6, eslint-disable no-var, prefer-arrow-callback */
/*eslint strict: [2, "never"]*/
module.exports = config => {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: "",

        // How long will Karma wait for a message from a browser before disconnecting from it (in ms).
        browserNoActivityTimeout: 2000000,

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ["openui5", "qunit"],

        // list of files / patterns to load in the browser
        files: [
            { pattern: "src/**", included: false, served: true, watched: false, nocache: false },
            "test/**/allTests.js",
            { pattern: "test/**/*.*", included: false, served: true }
        ],

        // In case an absolute URL is used at some point of the code, a proxy configuration is required.
        proxies: {
            "/src/": "/base/src/",
            "/test/": "/base/test/"
        },

        // test results reporter to use
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["progress", "coverage", "coveralls"],

        // source files, that you wanna generate coverage for
        // do not include tests or libraries
        // (these files will be instrumented by Istanbul)
        preprocessors: {
            "src/**/!(markerclusterer).js": ["coverage"]
        },

        // Configuration of coverage reporter
        // check coverage thresholds
        // output summary to the CLI
        // output lcov for coveralls
        coverageReporter: {
            check: {
                global: {
                    statements: 60,
                    branches: 60,
                    functions: 60,
                    lines: 60,
                    excludes: []
                }
            },
            dir: "reports/coverage",
            subdir: function() {
                return "";
            },
            reporters: [{
                type: "text-summary"
            }, {
                type: "html",
                subdir: "html"
            }, {
                type: "lcovonly",
                subdir: "lcov"
            }]
        },

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ["PhantomJS_custom"], //"Chrome"], "ChromeDebugging"],

        // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
        phantomjsLauncher: {
            exitOnResourceError: false
        },

        // you can define custom flags
        customLaunchers: {
            "PhantomJS_custom": {
                base: "PhantomJS",
                options: {
                    viewportSize: {
                        width: 1440,
                        height: 900
                    },
                    customHeaders: {
                        DNT: "1"
                    },
                    windowName: "my-window",
                    settings: {
                        webSecurityEnabled: false,
                        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36"
                    }
                },
                flags: ["--load-images=true", "--debug=false", "--disk-cache=false"],
                debug: true
            },
            "ChromeDebugging": {
                base: "Chrome",
                flags: ["--remote-debugging-port=9333"]
            }
        },

        openui5: {
            path: "https://openui5.hana.ondemand.com/resources/sap-ui-core.js",
            useMockServer: false
        },

        // How the client should execute the test, like run in an iframe, capture the console and so on.
        client: {
            captureConsole: true,
            clearContext: true,
            useIframe: false,
            qunit: {
                showUI: true,
                testTimeout: 15000,
                // autostart: false,
                autoload: false
            },
            openui5: {
                config: {
                    // theme: "sap_belize",
                    libs: "sap.m, openui5.googlemaps",
                    // compatVersion: "edge",
                    // frameOptions: "allow",
                    // preload: "async",
                    // animation: "false",
                    debug: "false",
                    resourceroots: {
                        "openui5.googlemaps": "/src/",
                        "test.unit": "/test/openui5/googlemaps/qunit"
                    }
                }
            }
        },

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_ERROR,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        hostname: "127.0.0.1",

        port: 9876
    });
};


text:
d3.combobox = function() {
    var event = d3.dispatch('accept'),
        data = [],
        suggestions = [],
        minItems = 2;

    var fetcher = function(val, cb) {
        cb(data.filter(function(d) {
            return d.value
                .toString()
                .toLowerCase()
                .indexOf(val.toLowerCase()) !== -1;
        }));
    };

    var combobox = function(input) {
        var idx = -1,
            container = d3.select(document.body)
                .selectAll('div.combobox')
                .filter(function(d) { return d === input.node(); }),
            shown = !container.empty();

        input
            .classed('combobox-input', true)
            .on('focus.typeahead', focus)
            .on('blur.typeahead', blur)
            .on('keydown.typeahead', keydown)
            .on('keyup.typeahead', keyup)
            .on('input.typeahead', change)
            .each(function() {
                var parent = this.parentNode,
                    sibling = this.nextSibling;

                var caret = d3.select(parent).selectAll('.combobox-caret')
                    .filter(function(d) { return d === input.node(); })
                    .data([input.node()]);

                caret.enter().insert('div', function() { return sibling; })
                    .attr('class', 'combobox-caret');

                caret
                    .on('mousedown', function () {
                        // prevent the form element from blurring. it blurs
                        // on mousedown
                        d3.event.stopPropagation();
                        d3.event.preventDefault();
                        if (!shown) {
                            input.node().focus();
                            fetch('', render);
                        } else {
                            hide();
                        }
                    });
            });

        function focus() {
            fetch(value(), render);
        }

        function blur() {
            window.setTimeout(hide, 150);
        }

        function show() {
            if (!shown) {
                container = d3.select(document.body)
                    .insert('div', ':first-child')
                    .datum(input.node())
                    .attr('class', 'combobox')
                    .style({
                        position: 'absolute',
                        display: 'block',
                        left: '0px'
                    })
                    .on('mousedown', function () {
                        // prevent moving focus out of the text field
                        d3.event.preventDefault();
                    });

                d3.select(document.body)
                    .on('scroll.combobox', render, true);

                shown = true;
            }
        }

        function hide() {
            if (shown) {
                idx = -1;
                container.remove();

                d3.select(document.body)
                    .on('scroll.combobox', null);

                shown = false;
            }
        }

        function keydown() {
           switch (d3.event.keyCode) {
               // backspace, delete
               case 8:
               case 46:
                   input.on('input.typeahead', function() {
                       idx = -1;
                       render();
                       var start = input.property('selectionStart');
                       input.node().setSelectionRange(start, start);
                       input.on('input.typeahead', change);
                   });
                   break;
               // tab
               case 9:
                   container.selectAll('a.selected').each(event.accept);
                   break;
               // return
               case 13:
                   d3.event.preventDefault();
                   break;
               // up arrow
               case 38:
                   nav(-1);
                   d3.event.preventDefault();
                   break;
               // down arrow
               case 40:
                   nav(+1);
                   d3.event.preventDefault();
                   break;
           }
           d3.event.stopPropagation();
        }

        function keyup() {
            switch (d3.event.keyCode) {
                // escape
                case 27:
                    hide();
                    break;
                // return
                case 13:
                    container.selectAll('a.selected').each(event.accept);
                    hide();
                    break;
            }
        }

        function change() {
            fetch(value(), function() {
                autocomplete();
                render();
            });
        }

        function nav(dir) {
            idx = Math.max(Math.min(idx + dir, suggestions.length - 1), 0);
            input.property('value', suggestions[idx].value);
            render();
            ensureVisible();
        }

        function value() {
            var value = input.property('value'),
                start = input.property('selectionStart'),
                end = input.property('selectionEnd');

            if (start && end) {
                value = value.substring(0, start);
            }

            return value;
        }

        function fetch(v, cb) {
            fetcher.call(input, v, function(_) {
                suggestions = _;
                cb();
            });
        }

        function autocomplete() {
            var v = value();

            idx = -1;

            if (!v) return;

            for (var i = 0; i < suggestions.length; i++) {
                if (suggestions[i].value.toLowerCase().indexOf(v.toLowerCase()) === 0) {
                    var completion = v + suggestions[i].value.substr(v.length);
                    idx = i;
                    input.property('value', completion);
                    input.node().setSelectionRange(v.length, completion.length);
                    return;
                }
            }
        }

        function render() {
            if (suggestions.length >= minItems && document.activeElement === input.node()) {
                show();
            } else {
                hide();
                return;
            }

            var options = container
                .selectAll('a.combobox-option')
                .data(suggestions, function(d) { return d.value; });

            options.enter().append('a')
                .attr('class', 'combobox-option')
                .text(function(d) { return d.value; });

            options
                .attr('title', function(d) { return d.title; })
                .classed('selected', function(d, i) { return i == idx; })
                .on('mouseover', select)
                .on('click', accept)
                .order();

            options.exit()
                .remove();

            var rect = input.node().getBoundingClientRect();

            container.style({
                'left': rect.left + 'px',
                'width': rect.width + 'px',
                'top': rect.height + rect.top + 'px'
            });
        }

        function select(d, i) {
            idx = i;
            render();
        }

        function ensureVisible() {
            var node = container.selectAll('a.selected').node();
            if (node) node.scrollIntoView();
        }

        function accept(d) {
            if (!shown) return;
            input
                .property('value', d.value)
                .trigger('change');
            event.accept(d);
            hide();
        }
    };

    combobox.fetcher = function(_) {
        if (!arguments.length) return fetcher;
        fetcher = _;
        return combobox;
    };

    combobox.data = function(_) {
        if (!arguments.length) return data;
        data = _;
        return combobox;
    };

    combobox.minItems = function(_) {
        if (!arguments.length) return minItems;
        minItems = _;
        return combobox;
    };

    return d3.rebind(combobox, event, 'on');
};


text:
/// <reference path="fourslash.ts" />

// @newline: LF
// @Filename: a.ts
////interface IFoo {
////    bar(this: IFoo): void;
////}
////const obj: IFoo = {
////    /*1*/
////}

verify.completions({
    marker: "1",
    preferences: {
        includeCompletionsWithInsertText: true,
        includeCompletionsWithSnippetText: true,
        includeCompletionsWithObjectLiteralMethodSnippets: true,
        useLabelDetailsInCompletionEntries: true,
    },
    includes: [
        {
            name: "bar",
            sortText: completion.SortText.ObjectLiteralProperty(completion.SortText.LocationPriority, "bar"),
            insertText: undefined,
        },
        {
            name: "bar",
            sortText: completion.SortText.SortBelow(
                completion.SortText.ObjectLiteralProperty(completion.SortText.LocationPriority, "bar")),
            source: completion.CompletionSource.ObjectLiteralMethodSnippet,
            isSnippet: true,
            insertText: "bar() {\n    $0\n},",
            labelDetails: {
                detail: "()",
            },
        },
    ],
});


text:
declare module Intl {

    export interface SupportedLocalesOfOptions {
        localeMatcher?: string;
    }

    export interface CollatorOptions {
        localeMatcher?: string;
        usage?: string;
        sensitivity?: string;
        ignorePunctuation?: boolean;
        numeric?: boolean;
        caseFirst?: string;
    }

    export class Collator {
        constructor(locales?: string, options?: CollatorOptions);
        constructor(locales?: string[], options?: CollatorOptions);
        static supportedLocalesOf(locales: string, options?: SupportedLocalesOfOptions): string[];
        static supportedLocalesOf(locales: string[], options?: SupportedLocalesOfOptions): string[];
        compare(string1: string, string2: string): number;
        resolvedOptions(): {
            locale: string;
            usage: string;
            sensitivity: string;
            ignorePunctuation: boolean;
            collation: string;
            numeric: boolean;
            caseFirst: string;
        };
    }

    export interface DateTimeFormatOptions {
        localeMatcher?: string;
        timeZone?: string;
        hour12?: boolean;
        formatMatcher?: boolean;
    }

    export class DateTimeFormat {
        constructor(locales?: string, options?: DateTimeFormatOptions);
        constructor(locales?: string[], options?: DateTimeFormatOptions);
        static supportedLocalesOf(locales: string, options?: SupportedLocalesOfOptions): string[];
        static supportedLocalesOf(locales: string[], options?: SupportedLocalesOfOptions): string[];
        format(date: Date): string;
        resolvedOptions(): {
            locale: string;
            calendar: string;
            numberingSystem: string;
            timeZone: string;
            hour12?: boolean;
            weekday?: string;
            era?: string;
            year?: string;
            month?: string;
            day?: string;
            hour?: string;
            minute?: string;
            second?: string;
            timeZoneName?: string;
        };
    }

    export interface NumberFormatOptions {
        localeMatcher?: string;
        style?: string;
        currency?: string;
        currencyDisplay?: string;
        useGrouping?: boolean;
        minimumIntegerDigits?: number;
        minimumFractionDigits?: number;
        maximumFractionDigits?: number;
        minimumSignificantDigits?: number;
        maximumSignificantDigits?: number;
    }

    export class NumberFormat {
        constructor(locales?: string, options?: NumberFormatOptions);
        constructor(locales?: string[], options?: NumberFormatOptions);
        static supportedLocalesOf(locales: string, options?: SupportedLocalesOfOptions): string[];
        static supportedLocalesOf(locales: string[], options?: SupportedLocalesOfOptions): string[];
        format(n: number): string;
        resolvedOptions(): {
            locale: string;
            numberingSystem: string;
            style: string;
            useGrouping: boolean;
            currency?: string;
            currencyDisplay?: string;
            minimumIntegerDigits?: number;
            minimumFractionDigits?: number;
            maximumFractionDigits?: number;
            minimumSignificantDigits?: number;
            maximumSignificantDigits?: number;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<info:toolkitInfoModel xmlns:common="http://www.ibm.com/xmlns/prod/streams/spl/common" xmlns:info="http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo">
  <info:identity>
    <info:name>com.ibm.streamsx.health.sample.patientmonitoring.rules</info:name>
    <info:description></info:description>
    <info:version>1.0.0</info:version>
    <info:requiredProductVersion>4.2.0.0</info:requiredProductVersion>
  </info:identity>
  <info:dependencies>
    <info:toolkit>
      <common:name>com.ibm.streams.rulescompiler</common:name>
      <common:version>1.0.0</common:version>
    </info:toolkit>
    <info:toolkit>
      <common:name>com.ibm.streamsx.health.ingest</common:name>
      <common:version>[1.0.0,2.0.0)</common:version>
    </info:toolkit>
  </info:dependencies>
</info:toolkitInfoModel>


text:
In this project, we implement the following binary search trees:

* Simple Binary Search Tree
* Splay Tree

These programs were written for self-study. Few functions have not been
implemented yet.

## Interesting stuff

In addition to **recursive** implementations of in-order, pre-order
and post-order tree traversal and tree destruction, we also provide
**non-recursive** implementations.

Note that in these non-recursive implementations, we do not use
a _Stack_, which is a common method for non-recursive implementations.
Instead, we use a node property `visited` which is a boolean variable.
This removes the overhead of maintaining a _Stack_.

## Usage

To compile the programs, you will need [CMake](http://www.cmake.org/) and
a [C++ compiler](http://gcc.gnu.org/).

The steps are as follows:

    $ git clone https://github.com/gyaikhom/binary-search-trees.git
    $ cd binary-search-trees
    $ mkdir build
    $ cd build
    $ cmake -G "Unix Makefiles" ..
    $ make
    $ ./testBinarySearchTrees


text:
<?php

namespace MadeYourDay\RockSolidCustomElements\Form;

use Contao\Widget;
use MadeYourDay\RockSolidCustomElements\Element\CustomElement;
use MadeYourDay\RockSolidCustomElements\Model\DummyModel;

/**
 * Custom form widget
 *
 * @author Martin Auswöger <martin@madeyourday.net>
 */
class CustomWidget extends Widget
{
	protected $blnSubmitInput = true;

	/**
	 * @var string Template
	 */
	protected $strTemplate = 'form_rsce_plain';

	/**
	 * @var CustomElement
	 */
	protected $customElement;

	/**
	 * {@inheritdoc}
	 */
	public function __construct($data = null)
	{
		if (!empty($data['class'])) {
			$data['cssID'] = serialize(array('', $data['class']));
		}

		$this->customElement = new CustomElement(new DummyModel(null, (array) $data));

		parent::__construct($data);
	}

	/**
	 * {@inheritdoc}
	 */
	public function generate()
	{
		$cssID = $this->customElement->cssID;
		$cssID[1] = (isset($cssID[1]) ? $cssID[1] . ' ' : '') . $this->class;
		$this->customElement->cssID = $cssID;

		$this->customElement->value = $this->value;

		foreach ([
			'hasErrors',
			'getErrors',
			'getErrorAsString',
			'getErrorsAsString',
			'getErrorAsHTML',
			'getAttributes',
			'getAttribute',
		] as $methodName) {
			$this->customElement->$methodName = function() use($methodName) {
				return call_user_func_array([$this, $methodName], func_get_args());
			};
		}

		return $this->customElement->generate();
	}

}


text:
trait T : Sized {}
fn f<Y: ?Sized + T>() {
//~^ERROR incompatible bounds on `Y`, bound `T` does not allow unsized type
}

pub fn main() {
}


text:
package com.inamik.text.tables.grid;

import com.inamik.text.tables.Cell;
import com.inamik.text.tables.GridTable;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public final class Util
{
    public static void print(GridTable g) {
        print(g, System.out);
    }

    public static void print(GridTable g, OutputStream out) {
        print(g, new PrintWriter(out));
    }

    public static void print(GridTable g, Writer out) {
        print(g, new PrintWriter(out));
    }

    public static void print(GridTable g, PrintWriter out) {
        // Apply final padding to ensure grid prints properly
        //
        g = g
            .apply(Cell.Functions.TOP_ALIGN)
            .apply(Cell.Functions.LEFT_ALIGN)
            ;

        // Convert the grid to a cell
        // then iterate over the lines and print
        //
        for (String line: g.toCell()) {
            out.println(line);
        }
    }

    public static String asString(GridTable g) {
        StringWriter out = new StringWriter();
        print(g, out);
        return out.toString();
    }

}


text:
package uk.gov.gchq.gaffer.schemabuilder.serialisation;

import com.fasterxml.jackson.databind.ObjectMapper;

import uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

/**
 * A {@link javax.ws.rs.ext.ContextResolver} implementation to provide a default
 * {@link com.fasterxml.jackson.databind.ObjectMapper} for converting objects to
 * JSON.
 */
@Provider
public class RestJsonProvider implements ContextResolver<ObjectMapper> {
    public final ObjectMapper mapper;

    public RestJsonProvider() {
        this.mapper = createMapper();
    }

    @Override
    public ObjectMapper getContext(final Class<?> aClass) {
        return mapper;
    }

    protected ObjectMapper createMapper() {
        return JSONSerialiser.createDefaultMapper();
    }
}


text:
#define	TRACE	0

static SCORE TraceBackDimer(  const SCORE *DPM_, const SCORE *DPD_, const SCORE *DPI_,
  const char *TBM_, const char *TBD_, const char *TBI_,
  unsigned uLengthA, unsigned uLengthB, PWPath &Path);

static const char *LocalScoreToStr(SCORE s)
	{
	static char str[16];
	if (MINUS_INFINITY == s)
		return "     *";
	sprintf(str, "%6.3g", s);
	return str;
	}

#if	TRACE
static void ListDP(const SCORE *DPM_, const ProfPos *PA, const ProfPos *PB,
  unsigned uPrefixCountA, unsigned uPrefixCountB)
	{
	Log("        ");
	for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
		{
		char c = ' ';
		if (uPrefixLengthB > 0)
			c = ConsensusChar(PB[uPrefixLengthB - 1]);
		Log(" %4u:%c", uPrefixLengthB, c);
		}
	Log("\n");
	for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA)
		{
		char c = ' ';
		if (uPrefixLengthA > 0)
			c = ConsensusChar(PA[uPrefixLengthA - 1]);
		Log("%4u:%c  ", uPrefixLengthA, c);
		for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
			Log(" %s", LocalScoreToStr(DPM(uPrefixLengthA, uPrefixLengthB)));
		Log("\n");
		}
	}

static void ListTB(const char *TBM_, const ProfPos *PA, const ProfPos *PB,
  unsigned uPrefixCountA, unsigned uPrefixCountB)
	{
	Log("        ");
	for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
		Log("%2d", uPrefixLengthB);
	Log("\n");
	Log("        ");
	for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
		{
		char c = ' ';
		if (uPrefixLengthB > 0)
			c = ConsensusChar(PB[uPrefixLengthB - 1]);
		Log(" %c", c);
		}
	Log("\n");
	for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA)
		{
		char c = ' ';
		if (uPrefixLengthA > 0)
			c = ConsensusChar(PA[uPrefixLengthA - 1]);
		Log("%4u:%c  ", uPrefixLengthA, c);
		for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
			Log(" %c", TBM(uPrefixLengthA, uPrefixLengthB));
		Log("\n");
		}
	}
#endif // TRACE

static ProfPos PPTerm;
static bool InitializePPTerm()
	{
	PPTerm.m_bAllGaps = false;
	PPTerm.m_LL = 1;
	PPTerm.m_LG = 0;
	PPTerm.m_GL = 0;
	PPTerm.m_GG = 0;
	PPTerm.m_fOcc = 1;
	return true;
	}
static bool PPTermInitialized = InitializePPTerm();

static SCORE ScoreProfPosDimerLE(const ProfPos &PPA, const ProfPos &PPB)
	{
	SCORE Score = 0;
	for (unsigned n = 0; n < 20; ++n)
		{
		const unsigned uLetter = PPA.m_uSortOrder[n];
		const FCOUNT fcLetter = PPA.m_fcCounts[uLetter];
		if (0 == fcLetter)
			break;
		Score += fcLetter*PPB.m_AAScores[uLetter];
		}
	if (0 == Score)
		return -2.5;
	SCORE logScore = logf(Score);
	return (SCORE) (logScore*(PPA.m_fOcc * PPB.m_fOcc));
	}

static SCORE ScoreProfPosDimerPSP(const ProfPos &PPA, const ProfPos &PPB)
	{
	SCORE Score = 0;
	for (unsigned n = 0; n < 20; ++n)
		{
		const unsigned uLetter = PPA.m_uSortOrder[n];
		const FCOUNT fcLetter = PPA.m_fcCounts[uLetter];
		if (0 == fcLetter)
			break;
		Score += fcLetter*PPB.m_AAScores[uLetter];
		}
	return Score;
	}

static SCORE ScoreProfPosDimer(const ProfPos &PPA, const ProfPos &PPB)
	{
	switch (g_PPScore)
		{
	case PPSCORE_LE:
		return ScoreProfPosDimerLE(PPA, PPB);

	case PPSCORE_SP:
	case PPSCORE_SV:
		return ScoreProfPosDimerPSP(PPA, PPB);
		}
	Quit("Invalid g_PPScore");
	return 0;
	}

// Global alignment dynamic programming
// This variant optimizes the profile-profile SP score under the
// dimer approximation.
SCORE GlobalAlignDimer(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB,
  unsigned uLengthB, PWPath &Path)
	{
	assert(uLengthB > 0 && uLengthA > 0);

	const unsigned uPrefixCountA = uLengthA + 1;
	const unsigned uPrefixCountB = uLengthB + 1;

// Allocate DP matrices
	const size_t LM = uPrefixCountA*uPrefixCountB;
	SCORE *DPM_ = new SCORE[LM];
	SCORE *DPD_ = new SCORE[LM];
	SCORE *DPI_ = new SCORE[LM];

	char *TBM_ = new char[LM];
	char *TBD_ = new char[LM];
	char *TBI_ = new char[LM];

	DPM(0, 0) = 0;
	DPD(0, 0) = MINUS_INFINITY;
	DPI(0, 0) = MINUS_INFINITY;

	TBM(0, 0) = 'S';
	TBD(0, 0) = '?';
	TBI(0, 0) = '?';

	DPM(1, 0) = MINUS_INFINITY;
	DPD(1, 0) = GapScoreMD(PA[0], PPTerm);
	DPI(1, 0) = MINUS_INFINITY;

	TBM(1, 0) = '?';
	TBD(1, 0) = 'S';
	TBI(1, 0) = '?';

	DPM(0, 1) = MINUS_INFINITY;
	DPD(0, 1) = MINUS_INFINITY;
	DPI(0, 1) = GapScoreMI(PPTerm, PB[0]);

	TBM(0, 1) = '?';
	TBD(0, 1) = '?';
	TBI(0, 1) = 'S';

// Empty prefix of B is special case
	for (unsigned uPrefixLengthA = 2; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA)
		{
	// M=LetterA+LetterB, impossible with empty prefix
		DPM(uPrefixLengthA, 0) = MINUS_INFINITY;
		TBM(uPrefixLengthA, 0) = '?';

	// D=LetterA+GapB
		DPD(uPrefixLengthA, 0) = DPD(uPrefixLengthA - 1, 0) +
		  GapScoreDD(PA[uPrefixLengthA - 1], PPTerm);
		TBD(uPrefixLengthA, 0) = 'D';

	// I=GapA+LetterB, impossible with empty prefix
		DPI(uPrefixLengthA, 0) = MINUS_INFINITY;
		TBI(uPrefixLengthA, 0) = '?';
		}

// Empty prefix of A is special case
	for (unsigned uPrefixLengthB = 2; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
		{
	// M=LetterA+LetterB, impossible with empty prefix
		DPM(0, uPrefixLengthB) = MINUS_INFINITY;
		TBM(0, uPrefixLengthB) = '?';

	// D=LetterA+GapB, impossible with empty prefix
		DPD(0, uPrefixLengthB) = MINUS_INFINITY;
		TBD(0, uPrefixLengthB) = '?';

	// I=GapA+LetterB
		DPI(0, uPrefixLengthB) = DPI(0, uPrefixLengthB - 1) +
		  GapScoreII(PPTerm, PB[uPrefixLengthB - 1]);
		TBI(0, uPrefixLengthB) = 'I';
		}

// ============
// Main DP loop
// ============
	for (unsigned uPrefixLengthB = 1; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB)
		{
		const ProfPos &PPB = PB[uPrefixLengthB - 1];
		for (unsigned uPrefixLengthA = 1; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA)
			{
			const ProfPos &PPA = PA[uPrefixLengthA - 1];
			{
		// Match M=LetterA+LetterB
			SCORE scoreLL = ScoreProfPosDimer(PPA, PPB);

			SCORE scoreMM = DPM(uPrefixLengthA-1, uPrefixLengthB-1) + GapScoreMM(PPA, PPB);
			SCORE scoreDM = DPD(uPrefixLengthA-1, uPrefixLengthB-1) + GapScoreDM(PPA, PPB);
			SCORE scoreIM = DPI(uPrefixLengthA-1, uPrefixLengthB-1) + GapScoreIM(PPA, PPB);

			SCORE scoreBest = scoreMM;
			char c = 'M';
			if (scoreDM > scoreBest)
				{
				scoreBest = scoreDM;
				c = 'D';
				}
			if (scoreIM > scoreBest)
				{
				scoreBest = scoreIM;
				c = 'I';
				}

			DPM(uPrefixLengthA, uPrefixLengthB) = scoreBest + scoreLL;
			TBM(uPrefixLengthA, uPrefixLengthB) = c;
			}
			{
		// Delete D=LetterA+GapB
			SCORE scoreMD = DPM(uPrefixLengthA-1, uPrefixLengthB) + GapScoreMD(PPA, PPB);
			SCORE scoreDD = DPD(uPrefixLengthA-1, uPrefixLengthB) + GapScoreDD(PPA, PPB);
			SCORE scoreID = DPI(uPrefixLengthA-1, uPrefixLengthB) + GapScoreID(PPA, PPB);

			SCORE scoreBest = scoreMD;
			char c = 'M';
			if (scoreDD > scoreBest)
				{
				scoreBest = scoreDD;
				c = 'D';
				}
			if (scoreID > scoreBest)
				{
				scoreBest = scoreID;
				c = 'I';
				}

			DPD(uPrefixLengthA, uPrefixLengthB) = scoreBest;
			TBD(uPrefixLengthA, uPrefixLengthB) = c;
			}
			{
		// Insert I=GapA+LetterB
			SCORE scoreMI = DPM(uPrefixLengthA, uPrefixLengthB-1) + GapScoreMI(PPA, PPB);
			SCORE scoreDI = DPD(uPrefixLengthA, uPrefixLengthB-1) + GapScoreDI(PPA, PPB);
			SCORE scoreII = DPI(uPrefixLengthA, uPrefixLengthB-1) + GapScoreII(PPA, PPB);

			SCORE scoreBest = scoreMI;
			char c = 'M';
			if (scoreDI > scoreBest)
				{
				scoreBest = scoreDI;
				c = 'D';
				}
			if (scoreII > scoreBest)
				{
				scoreBest = scoreII;
				c = 'I';
				}

			DPI(uPrefixLengthA, uPrefixLengthB) = scoreBest;
			TBI(uPrefixLengthA, uPrefixLengthB) = c;
			}
			}
		}

#if TRACE
	Log("DPM:\n");
	ListDP(DPM_, PA, PB, uPrefixCountA, uPrefixCountB);
	Log("DPD:\n");
	ListDP(DPD_, PA, PB, uPrefixCountA, uPrefixCountB);
	Log("DPI:\n");
	ListDP(DPI_, PA, PB, uPrefixCountA, uPrefixCountB);
	Log("TBM:\n");
	ListTB(TBM_, PA, PB, uPrefixCountA, uPrefixCountB);
	Log("TBD:\n");
	ListTB(TBD_, PA, PB, uPrefixCountA, uPrefixCountB);
	Log("TBI:\n");
	ListTB(TBI_, PA, PB, uPrefixCountA, uPrefixCountB);
#endif

	SCORE Score = TraceBackDimer(DPM_, DPD_, DPI_, TBM_, TBD_, TBI_,
	  uLengthA, uLengthB, Path);

#if	TRACE
	Log("GlobalAlignDimer score = %.3g\n", Score);
#endif

	delete[] DPM_;
	delete[] DPD_;
	delete[] DPI_;

	delete[] TBM_;
	delete[] TBD_;
	delete[] TBI_;

	return Score;
	}

static SCORE TraceBackDimer(  const SCORE *DPM_, const SCORE *DPD_, const SCORE *DPI_,
  const char *TBM_, const char *TBD_, const char *TBI_,
  unsigned uLengthA, unsigned uLengthB, PWPath &Path)
	{
	const unsigned uPrefixCountA = uLengthA + 1;

	unsigned uPrefixLengthA = uLengthA;
	unsigned uPrefixLengthB = uLengthB;

	char cEdge = 'M';
	SCORE scoreMax = DPM(uLengthA, uLengthB);
	if (DPD(uLengthA, uLengthB) > scoreMax)
		{
		scoreMax = DPD(uLengthA, uLengthB);
		cEdge = 'D';
		}
	if (DPI(uLengthA, uLengthB) > scoreMax)
		{
		scoreMax = DPI(uLengthA, uLengthB);
		cEdge = 'I';
		}

	for (;;)
		{
		if (0 == uPrefixLengthA && 0 == uPrefixLengthB)
			break;

		PWEdge Edge;
		Edge.cType = cEdge;
		Edge.uPrefixLengthA = uPrefixLengthA;
		Edge.uPrefixLengthB = uPrefixLengthB;
		Path.PrependEdge(Edge);

#if TRACE
		Log("PLA=%u PLB=%u Edge=%c\n", uPrefixLengthA, uPrefixLengthB, cEdge);
#endif
		switch (cEdge)
			{
		case 'M':
			assert(uPrefixLengthA > 0 && uPrefixLengthB > 0);
			cEdge = TBM(uPrefixLengthA, uPrefixLengthB);
			--uPrefixLengthA;
			--uPrefixLengthB;
			break;
		case 'D':
			assert(uPrefixLengthA > 0);
			cEdge = TBD(uPrefixLengthA, uPrefixLengthB);
			--uPrefixLengthA;
			break;
		case 'I':
			assert(uPrefixLengthB > 0);
			cEdge = TBI(uPrefixLengthA, uPrefixLengthB);
			--uPrefixLengthB;
			break;
		default:
			Quit("Invalid edge PLA=%u PLB=%u %c", uPrefixLengthA, uPrefixLengthB, cEdge);
			}
		}
#if	TRACE
	Path.LogMe();
#endif
	return scoreMax;
	}


text:
require 'test_helper'

ActiveForm::Element::Builder::create :some_snippet do |builder, elem|

  builder.h1('A preset element')
  builder.p('Just an example of what you can do...')

end

class TestBuilderElement < Test::Unit::TestCase

  def test_element_to_html
    elem = ActiveForm::Element::Builder.new :elem, :html => 'raw html string'
    assert_equal %|raw html string\n|, elem.to_html

    elem = ActiveForm::Element::Builder.new :elem do |builder, e|
      builder.div('built with block')
    end
    assert_equal %|
built with block
\n|, elem.to_html

    elem = ActiveForm::Element::Builder.new :elem, :html => 'raw html string and builder block' do |builder, e|
      builder.div(e.value)
    end
    assert_equal %|
raw html string and builder block
\n|, elem.to_html
  end

  def test_build_html
    form = ActiveForm::compose :form do |f|
      f.html :named do |builder, e|
        builder.h1('My Pretty form')
        builder.dl {
          e.container.get_elements_of_type(:text).each do |e|
            builder.dt(e.label)
            builder.dd(e.value)
          end
        }
      end
      f.text_element :name
      f.text_element :city
      f.html { |builder, e| builder.hr }
    end
    form.values = { :name => 'Fred', :city => 'Bedrock' }
    expected = %|<form action="#form" class="active_form" id="form" method="post">

My Pretty form

Name

Fred

City

Bedrock

  <input class="elem_text" id="form_name" name="form[name]" size="30" type="text" value="Fred"/>
  <input class="elem_text" id="form_city" name="form[city]" size="30" type="text" value="Bedrock"/>

</form>\n|
    assert_equal expected, form.to_html
  end

  def test_add_raw_string
    form = ActiveForm::compose :form
    form << '
My Form
'
    form.text_element :name
    form << '
'
    expected = %|<form action="#form" class="active_form" id="form" method="post">

My Form

  <input class="elem_text" id="form_name" name="form[name]" size="30" type="text"/>

</form>\n|
    assert_equal expected, form.to_html
  end

  def test_add_predefined_html_snippet_element
    form = ActiveForm::compose :form
    form.some_snippet_element
    expected = %|<form action="#form" class="active_form" id="form" method="post">

A preset element

Just an example of what you can do...

</form>\n|
    assert_equal expected, form.to_html
  end

end


text:
using System;
using NUnit.Framework;

namespace Apache.NMS.Test
{
	[TestFixture]
	public class ProducerTest : NMSTestSupport
	{
        [Test]
        public void TestProducerSendToNullDestinationWithoutDefault()
        {
            using(IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using(ISession session = connection.CreateSession())
                {
                    IMessageProducer producer = session.CreateProducer(null);

                    try
                    {
                        producer.Send(null, session.CreateTextMessage("Message"));
                        Assert.Fail("Producer should have thrown an NotSupportedException");
                    }
                    catch(NotSupportedException)
                    {
                    }
                    catch(Exception ex)
                    {
                        Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name);
                    }
                }
            }
        }

        [Test]
        public void TestProducerSendToNullDestinationWithDefault()
        {
            using(IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using(ISession session = connection.CreateSession())
                {
                    IDestination unusedDest = session.CreateTemporaryQueue();

                    IMessageProducer producer = session.CreateProducer(unusedDest);

                    try
                    {
                        producer.Send(null, session.CreateTextMessage("Message"));
                        Assert.Fail("Producer should have thrown an InvalidDestinationException");
                    }
                    catch(InvalidDestinationException)
                    {
                    }
                    catch(Exception ex)
                    {
                        Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name);
                    }
                }
            }
        }

		[Test]
		public void TestProducerSendToNonDefaultDestination()
		{
            using(IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using(ISession session = connection.CreateSession())
                {
					IDestination unusedDest = session.CreateTemporaryQueue();
					IDestination usedDest = session.CreateTemporaryQueue();

					IMessageProducer producer = session.CreateProducer(unusedDest);

                    try
                    {
					    producer.Send(usedDest, session.CreateTextMessage("Message"));
                        Assert.Fail("Producer should have thrown an NotSupportedException");
                    }
                    catch(NotSupportedException)
                    {
                    }
                    catch(Exception ex)
                    {
                        Assert.Fail("Wrong Exception Type Thrown: " + ex.GetType().Name);
                    }
				}
			}
        }
	}
}


text:
(function () {
    'use strict';
    var oContainer = document.getElementById('container'),
        nRows = 1000,
        nColumns = 1000,
        oRow,
        oColumn,
        nIndexRow,
        nIndexColumn;

    function createTable() {
        var nEnd,
            nStart = window.performance.now(),
            oTable = document.createElement('table');

        for (nIndexRow = 0; nIndexRow < nRows; nIndexRow++) {
            oRow = document.createElement('tr');
            oTable.appendChild(oRow);
            for (nIndexColumn = 0; nIndexColumn < nColumns; nIndexColumn++) {
                oColumn = document.createElement('td');
                oColumn.innerHTML = nIndexRow + ':' + nIndexColumn;
                oRow.appendChild(oColumn);
            }
        }
        oContainer.appendChild(oTable);
        nEnd = window.performance.now() - nStart;
        console.log( nEnd );
    }

    document.getElementById('add').addEventListener('click', function () {
        createTable();
    }, false);
}());


text:
namespace Specifications
{
    using Examples;
    using Machine.Specifications;
    using StyleCop.CSharp.MethodVisitors;
    using System;

    [Subject("Methods with Async Modifier")]
    class MethodsWithAsyncModifierMustEndWithAsyncSpecifications : ExamplesBasedSpecifications
    {
        private static readonly Type RuleType = typeof(MethodsWithAsyncModifierMustEndWithAsync);

        private static readonly string FileName = typeof(MethodsWithAsyncModifierMustEndWithAsyncExample).Name;

        It should_warn_when_does_not_have_async_suffix = () =>
            ShouldHaveWarningFor(RuleType, FileName, 7);

        It should_not_warn_when_method_has_async_suffix = () =>
            ShouldNotHaveWarningFor(RuleType, FileName, 12);
    }
}


text:
class Object
  def eigenclass
    class << self; self; end
  end
end


text:
import {readFileSync} from 'fs';
import {join, dirname, relative} from 'path';
import {cwd} from 'process';
import {Cleaner} from './cleaner';
import {Resolver} from './resolver';
import * as async from 'async';
import * as through  from 'through2';
import {Loader, LoaderifyOpts} from './models';

const requireRegex = /require\s*\(['"`](\.[^)]+)['"`]\)/g;

function transform(file: string, opts: LoaderifyOpts) {
    if (!opts) {
        opts = {};
    }
    let patterns = {};
    (opts.loaders || []).forEach((loader: Loader) => {
        let rxp = Cleaner.wildcardToRegex(loader.Pattern);
        patterns[rxp] = loader.Function;
    });
    return through((buf, enc, next) => {
        let chunk = buf.toString('utf8');
        let requires = chunk.match(requireRegex) || [];
        async.eachSeries(requires, (required, cb) => {
            let target = required.replace(requireRegex, '$1');
            let filepath = Resolver.resolveUnKnownExtension(join(dirname(file), target));
            let matcher = relative(cwd(), filepath);
            let match: string;
            for (let ptrn in patterns) {
                if (patterns.hasOwnProperty(ptrn)) {
                    let pattern = new RegExp(ptrn);
                    if (pattern.test(matcher)) {
                        match = ptrn;
                        break;
                    }
                }
            }
            if (!match) {
                return cb();
            }
            let callback = patterns[match];
            try {
                let contents = readFileSync(filepath).toString();
                callback(matcher, contents, (abort, results) => {
                    if (!abort) {
                        chunk = chunk.replace(required, results);
                    }
                    return cb();
                });
            } catch (error) {
                return cb(error);
            }
        }, (err) => {
            if (err)  {
                throw err;
            }
            return next(null, chunk);
        });
    });
};

module.exports = transform;