text:
//#define USE_LOG SLAndroidLogLevel_Verbose

#include "sles_allinclusive.h"
#include "android/android_AudioSfDecoder.h"

#include <binder/IServiceManager.h>
#include <media/stagefright/foundation/ADebug.h>

#define SIZE_CACHED_HIGH_BYTES 1000000
#define SIZE_CACHED_MED_BYTES   700000
#define SIZE_CACHED_LOW_BYTES   400000

namespace android {

//--------------------------------------------------------------------------------------------------
AudioSfDecoder::AudioSfDecoder(const AudioPlayback_Parameters* params) : GenericPlayer(params),
        mDataSource(0),
        mAudioSource(0),
        mAudioSourceStarted(false),
        mBitrate(-1),
        mDurationUsec(ANDROID_UNKNOWN_TIME),
        mDecodeBuffer(NULL),
        mSeekTimeMsec(0),
        // play event logic depends on the initial time being zero not ANDROID_UNKNOWN_TIME
        mLastDecodedPositionUs(0)
{
    SL_LOGD("AudioSfDecoder::AudioSfDecoder()");
}

AudioSfDecoder::~AudioSfDecoder() {
    SL_LOGD("AudioSfDecoder::~AudioSfDecoder()");
}

void AudioSfDecoder::preDestroy() {
    GenericPlayer::preDestroy();
    SL_LOGD("AudioSfDecoder::preDestroy()");
    {
        Mutex::Autolock _l(mBufferSourceLock);

        if (NULL != mDecodeBuffer) {
            mDecodeBuffer->release();
            mDecodeBuffer = NULL;
        }

        if ((mAudioSource != 0) && mAudioSourceStarted) {
            mAudioSource->stop();
            mAudioSourceStarted = false;
        }
    }
}

//--------------------------------------------------
void AudioSfDecoder::play() {
    SL_LOGD("AudioSfDecoder::play");

    GenericPlayer::play();
    (new AMessage(kWhatDecode, id()))->post();
}

void AudioSfDecoder::getPositionMsec(int* msec) {
    int64_t timeUsec = getPositionUsec();
    if (timeUsec == ANDROID_UNKNOWN_TIME) {
        *msec = ANDROID_UNKNOWN_TIME;
    } else {
        *msec = timeUsec / 1000;
    }
}

//--------------------------------------------------
uint32_t AudioSfDecoder::getPcmFormatKeyCount() const {
    return NB_PCMMETADATA_KEYS;
}

//--------------------------------------------------
bool AudioSfDecoder::getPcmFormatKeySize(uint32_t index, uint32_t* pKeySize) {
    if (index >= NB_PCMMETADATA_KEYS) {
        return false;
    } else {
        *pKeySize = strlen(kPcmDecodeMetadataKeys[index]) +1;
        return true;
    }
}

//--------------------------------------------------
bool AudioSfDecoder::getPcmFormatKeyName(uint32_t index, uint32_t keySize, char* keyName) {
    uint32_t actualKeySize;
    if (!getPcmFormatKeySize(index, &actualKeySize)) {
        return false;
    }
    if (keySize < actualKeySize) {
        return false;
    }
    strncpy(keyName, kPcmDecodeMetadataKeys[index], actualKeySize);
    return true;
}

//--------------------------------------------------
bool AudioSfDecoder::getPcmFormatValueSize(uint32_t index, uint32_t* pValueSize) {
    if (index >= NB_PCMMETADATA_KEYS) {
        *pValueSize = 0;
        return false;
    } else {
        *pValueSize = sizeof(uint32_t);
        return true;
    }
}

//--------------------------------------------------
bool AudioSfDecoder::getPcmFormatKeyValue(uint32_t index, uint32_t size, uint32_t* pValue) {
    uint32_t valueSize = 0;
    if (!getPcmFormatValueSize(index, &valueSize)) {
        return false;
    } else if (size != valueSize) {
        // this ensures we are accessing mPcmFormatValues with a valid size for that index
        SL_LOGE("Error retrieving metadata value at index %d: using size of %d, should be %d",
                index, size, valueSize);
        return false;
    } else {
        android::Mutex::Autolock autoLock(mPcmFormatLock);
        *pValue = mPcmFormatValues[index];
        return true;
    }
}

//--------------------------------------------------
// Event handlers
//  it is strictly verboten to call those methods outside of the event loop

// Initializes the data and audio sources, and update the PCM format info
// post-condition: upon successful initialization based on the player data locator
//    GenericPlayer::onPrepare() was called
//    mDataSource != 0
//    mAudioSource != 0
//    mAudioSourceStarted == true
// All error returns from this method are via notifyPrepared(status) followed by "return".
void AudioSfDecoder::onPrepare() {
    SL_LOGD("AudioSfDecoder::onPrepare()");
    Mutex::Autolock _l(mBufferSourceLock);

    {
    android::Mutex::Autolock autoLock(mPcmFormatLock);
    // Initialize the PCM format info with the known parameters before the start of the decode
    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_BITSPERSAMPLE] = SL_PCMSAMPLEFORMAT_FIXED_16;
    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CONTAINERSIZE] = 16;
    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_ENDIANNESS] = SL_BYTEORDER_LITTLEENDIAN;
    //    initialization with the default values: they will be replaced by the actual values
    //      once the decoder has figured them out
    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = UNKNOWN_NUMCHANNELS;
    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = UNKNOWN_SAMPLERATE;
    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] = UNKNOWN_CHANNELMASK;
    }

    //---------------------------------
    // Instantiate and initialize the data source for the decoder
    sp<DataSource> dataSource;

    switch (mDataLocatorType) {

    case kDataLocatorNone:
        SL_LOGE("AudioSfDecoder::onPrepare: no data locator set");
        notifyPrepared(MEDIA_ERROR_BASE);
        return;

    case kDataLocatorUri:
        dataSource = DataSource::CreateFromURI(mDataLocator.uriRef);
        if (dataSource == NULL) {
            SL_LOGE("AudioSfDecoder::onPrepare(): Error opening %s", mDataLocator.uriRef);
            notifyPrepared(MEDIA_ERROR_BASE);
            return;
        }
        break;

    case kDataLocatorFd:
    {
        // As FileSource unconditionally takes ownership of the fd and closes it, then
        // we have to make a dup for FileSource if the app wants to keep ownership itself
        int fd = mDataLocator.fdi.fd;
        if (mDataLocator.fdi.mCloseAfterUse) {
            mDataLocator.fdi.mCloseAfterUse = false;
        } else {
            fd = ::dup(fd);
        }
        dataSource = new FileSource(fd, mDataLocator.fdi.offset, mDataLocator.fdi.length);
        status_t err = dataSource->initCheck();
        if (err != OK) {
            notifyPrepared(err);
            return;
        }
        break;
    }

    // AndroidBufferQueue data source is handled by a subclass,
    // which does not call up to this method.  Hence, the missing case.
    default:
        TRESPASS();
    }

    //---------------------------------
    // Instantiate and initialize the decoder attached to the data source
    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
    if (extractor == NULL) {
        SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate extractor.");
        notifyPrepared(ERROR_UNSUPPORTED);
        return;
    }

    ssize_t audioTrackIndex = -1;
    bool isRawAudio = false;
    for (size_t i = 0; i < extractor->countTracks(); ++i) {
        sp<MetaData> meta = extractor->getTrackMetaData(i);

        const char *mime;
        CHECK(meta->findCString(kKeyMIMEType, &mime));

        if (!strncasecmp("audio/", mime, 6)) {
            if (isSupportedCodec(mime)) {
                audioTrackIndex = i;

                if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) {
                    isRawAudio = true;
                }
                break;
            }
        }
    }

    if (audioTrackIndex < 0) {
        SL_LOGE("AudioSfDecoder::onPrepare: Could not find a supported audio track.");
        notifyPrepared(ERROR_UNSUPPORTED);
        return;
    }

    sp<MediaSource> source = extractor->getTrack(audioTrackIndex);
    sp<MetaData> meta = source->getFormat();

    // we can't trust the OMXCodec (if there is one) to issue a INFO_FORMAT_CHANGED so we want
    // to have some meaningful values as soon as possible.
    int32_t channelCount;
    bool hasChannelCount = meta->findInt32(kKeyChannelCount, &channelCount);
    int32_t sr;
    bool hasSampleRate = meta->findInt32(kKeySampleRate, &sr);

    // first compute the duration
    off64_t size;
    int64_t durationUs;
    int32_t durationMsec;
    if (dataSource->getSize(&size) == OK
            && meta->findInt64(kKeyDuration, &durationUs)) {
        if (durationUs != 0) {
            mBitrate = size * 8000000ll / durationUs;  // in bits/sec
        } else {
            mBitrate = -1;
        }
        mDurationUsec = durationUs;
        durationMsec = durationUs / 1000;
    } else {
        mBitrate = -1;
        mDurationUsec = ANDROID_UNKNOWN_TIME;
        durationMsec = ANDROID_UNKNOWN_TIME;
    }

    // then assign the duration under the settings lock
    {
        Mutex::Autolock _l(mSettingsLock);
        mDurationMsec = durationMsec;
    }

    // the audio content is not raw PCM, so we need a decoder
    if (!isRawAudio) {
        OMXClient client;
        CHECK_EQ(client.connect(), (status_t)OK);

        source = OMXCodec::Create(
                client.interface(), meta, false /* createEncoder */,
                source);

        if (source == NULL) {
            SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate decoder.");
            notifyPrepared(ERROR_UNSUPPORTED);
            return;
        }

        meta = source->getFormat();
    }

    if (source->start() != OK) {
        SL_LOGE("AudioSfDecoder::onPrepare: Failed to start source/decoder.");
        notifyPrepared(MEDIA_ERROR_BASE);
        return;
    }

    //---------------------------------
    // The data source, and audio source (a decoder if required) are ready to be used
    mDataSource = dataSource;
    mAudioSource = source;
    mAudioSourceStarted = true;

    if (!hasChannelCount) {
        CHECK(meta->findInt32(kKeyChannelCount, &channelCount));
    }

    if (!hasSampleRate) {
        CHECK(meta->findInt32(kKeySampleRate, &sr));
    }
    // FIXME add code below once channel mask support is in, currently initialized to default
    //       value computed from the channel count
    //    if (!hasChannelMask) {
    //        CHECK(meta->findInt32(kKeyChannelMask, &channelMask));
    //    }

    if (!wantPrefetch()) {
        SL_LOGV("AudioSfDecoder::onPrepare: no need to prefetch");
        // doesn't need prefetching, notify good to go
        mCacheStatus = kStatusHigh;
        mCacheFill = 1000;
        notifyStatus();
        notifyCacheFill();
    }

    {
        android::Mutex::Autolock autoLock(mPcmFormatLock);
        mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr;
        mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount;
        mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] =
                channelCountToMask(channelCount);
    }

    // at this point we have enough information about the source to create the sink that
    // will consume the data
    createAudioSink();

    // signal successful completion of prepare
    mStateFlags |= kFlagPrepared;

    GenericPlayer::onPrepare();
    SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags);
}

void AudioSfDecoder::onPause() {
    SL_LOGV("AudioSfDecoder::onPause()");
    GenericPlayer::onPause();
    pauseAudioSink();
}

void AudioSfDecoder::onPlay() {
    SL_LOGV("AudioSfDecoder::onPlay()");
    GenericPlayer::onPlay();
    startAudioSink();
}

void AudioSfDecoder::onSeek(const sp<AMessage> &msg) {
    SL_LOGV("AudioSfDecoder::onSeek");
    int64_t timeMsec;
    CHECK(msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec));

    Mutex::Autolock _l(mTimeLock);
    mStateFlags |= kFlagSeeking;
    mSeekTimeMsec = timeMsec;
    // don't set mLastDecodedPositionUs to ANDROID_UNKNOWN_TIME; getPositionUsec
    // ignores mLastDecodedPositionUs while seeking, and substitutes the seek goal instead

    // nop for now
    GenericPlayer::onSeek(msg);
}

void AudioSfDecoder::onLoop(const sp<AMessage> &msg) {
    SL_LOGV("AudioSfDecoder::onLoop");
    int32_t loop;
    CHECK(msg->findInt32(WHATPARAM_LOOP_LOOPING, &loop));

    if (loop) {
        //SL_LOGV("AudioSfDecoder::onLoop start looping");
        mStateFlags |= kFlagLooping;
    } else {
        //SL_LOGV("AudioSfDecoder::onLoop stop looping");
        mStateFlags &= ~kFlagLooping;
    }

    // nop for now
    GenericPlayer::onLoop(msg);
}

void AudioSfDecoder::onCheckCache(const sp<AMessage> &msg) {
    //SL_LOGV("AudioSfDecoder::onCheckCache");
    bool eos;
    CacheStatus_t status = getCacheRemaining(&eos);

    if (eos || status == kStatusHigh
            || ((mStateFlags & kFlagPreparing) && (status >= kStatusEnough))) {
        if (mStateFlags & kFlagPlaying) {
            startAudioSink();
        }
        mStateFlags &= ~kFlagBuffering;

        SL_LOGV("AudioSfDecoder::onCheckCache: buffering done.");

        if (mStateFlags & kFlagPreparing) {
            //SL_LOGV("AudioSfDecoder::onCheckCache: preparation done.");
            mStateFlags &= ~kFlagPreparing;
        }

        if (mStateFlags & kFlagPlaying) {
            (new AMessage(kWhatDecode, id()))->post();
        }
        return;
    }

    msg->post(100000);
}

void AudioSfDecoder::onDecode() {
    SL_LOGV("AudioSfDecoder::onDecode");

    //-------------------------------- Need to buffer some more before decoding?
    bool eos;
    if (mDataSource == 0) {
        // application set play state to paused which failed, then set play state to playing
        return;
    }

    if (wantPrefetch()
            && (getCacheRemaining(&eos) == kStatusLow)
            && !eos) {
        SL_LOGV("buffering more.");

        if (mStateFlags & kFlagPlaying) {
            pauseAudioSink();
        }
        mStateFlags |= kFlagBuffering;
        (new AMessage(kWhatCheckCache, id()))->post(100000);
        return;
    }

    if (!(mStateFlags & (kFlagPlaying | kFlagBuffering | kFlagPreparing))) {
        // don't decode if we're not buffering, prefetching or playing
        //SL_LOGV("don't decode: not buffering, prefetching or playing");
        return;
    }

    //-------------------------------- Decode
    status_t err;
    MediaSource::ReadOptions readOptions;
    if (mStateFlags & kFlagSeeking) {
        assert(mSeekTimeMsec != ANDROID_UNKNOWN_TIME);
        readOptions.setSeekTo(mSeekTimeMsec * 1000);
    }

    int64_t timeUsec = ANDROID_UNKNOWN_TIME;
    {
        Mutex::Autolock _l(mBufferSourceLock);

        if (NULL != mDecodeBuffer) {
            // the current decoded buffer hasn't been rendered, drop it
            mDecodeBuffer->release();
            mDecodeBuffer = NULL;
        }
        if (!mAudioSourceStarted) {
            return;
        }
        err = mAudioSource->read(&mDecodeBuffer, &readOptions);
        if (err == OK) {
            // FIXME workaround apparent bug in AAC decoder: kKeyTime is 3 frames old if length is 0
            if (mDecodeBuffer->range_length() == 0) {
                timeUsec = ANDROID_UNKNOWN_TIME;
            } else {
                CHECK(mDecodeBuffer->meta_data()->findInt64(kKeyTime, &timeUsec));
            }
        } else {
            // errors are handled below
        }
    }

    {
        Mutex::Autolock _l(mTimeLock);
        if (mStateFlags & kFlagSeeking) {
            mStateFlags &= ~kFlagSeeking;
            mSeekTimeMsec = ANDROID_UNKNOWN_TIME;
        }
        if (timeUsec != ANDROID_UNKNOWN_TIME) {
            // Note that though we've decoded this position, we haven't rendered it yet.
            // So a GetPosition called after this point will observe the advanced position,
            // even though the PCM may not have been supplied to the sink.  That's OK as
            // we don't claim to provide AAC frame-accurate (let alone sample-accurate) GetPosition.
            mLastDecodedPositionUs = timeUsec;
        }
    }

    //-------------------------------- Handle return of decode
    if (err != OK) {
        bool continueDecoding = false;
        switch(err) {
            case ERROR_END_OF_STREAM:
                if (0 < mDurationUsec) {
                    Mutex::Autolock _l(mTimeLock);
                    mLastDecodedPositionUs = mDurationUsec;
                }
                // handle notification and looping at end of stream
                if (mStateFlags & kFlagPlaying) {
                    notify(PLAYEREVENT_ENDOFSTREAM, 1, true /*async*/);
                }
                if (mStateFlags & kFlagLooping) {
                    seek(0);
                    // kick-off decoding again
                    continueDecoding = true;
                }
                break;
            case INFO_FORMAT_CHANGED:
                SL_LOGD("MediaSource::read encountered INFO_FORMAT_CHANGED");
                // reconfigure output
                {
                    Mutex::Autolock _l(mBufferSourceLock);
                    hasNewDecodeParams();
                }
                continueDecoding = true;
                break;
            case INFO_DISCONTINUITY:
                SL_LOGD("MediaSource::read encountered INFO_DISCONTINUITY");
                continueDecoding = true;
                break;
            default:
                SL_LOGE("MediaSource::read returned error %d", err);
                break;
        }
        if (continueDecoding) {
            if (NULL == mDecodeBuffer) {
                (new AMessage(kWhatDecode, id()))->post();
                return;
            }
        } else {
            return;
        }
    }

    //-------------------------------- Render
    sp<AMessage> msg = new AMessage(kWhatRender, id());
    msg->post();

}

void AudioSfDecoder::onMessageReceived(const sp<AMessage> &msg) {
    switch (msg->what()) {
        case kWhatDecode:
            onDecode();
            break;

        case kWhatRender:
            onRender();
            break;

        case kWhatCheckCache:
            onCheckCache(msg);
            break;

        default:
            GenericPlayer::onMessageReceived(msg);
            break;
    }
}

//--------------------------------------------------
// Prepared state, prefetch status notifications
void AudioSfDecoder::notifyPrepared(status_t prepareRes) {
    assert(!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully)));
    if (NO_ERROR == prepareRes) {
        // The "then" fork is not currently used, but is kept here to make it easier
        // to replace by a new signalPrepareCompletion(status) if we re-visit this later.
        mStateFlags |= kFlagPrepared;
    } else {
        mStateFlags |= kFlagPreparedUnsuccessfully;
    }
    // Do not call the superclass onPrepare to notify, because it uses a default error
    // status code but we can provide a more specific one.
    // GenericPlayer::onPrepare();
    notify(PLAYEREVENT_PREPARED, (int32_t)prepareRes, true /*async*/);
    SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags);
}

void AudioSfDecoder::onNotify(const sp<AMessage> &msg) {
    notif_cbf_t notifyClient;
    void*       notifyUser;
    {
        android::Mutex::Autolock autoLock(mNotifyClientLock);
        if (NULL == mNotifyClient) {
            return;
        } else {
            notifyClient = mNotifyClient;
            notifyUser   = mNotifyUser;
        }
    }
    int32_t val;
    if (msg->findInt32(PLAYEREVENT_PREFETCHSTATUSCHANGE, &val)) {
        SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHSTATUSCHANGE, val);
        notifyClient(kEventPrefetchStatusChange, val, 0, notifyUser);
    }
    else if (msg->findInt32(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, &val)) {
        SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHFILLLEVELUPDATE, val);
        notifyClient(kEventPrefetchFillLevelUpdate, val, 0, notifyUser);
    }
    else if (msg->findInt32(PLAYEREVENT_ENDOFSTREAM, &val)) {
        SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_ENDOFSTREAM, val);
        notifyClient(kEventEndOfStream, val, 0, notifyUser);
    }
    else {
        GenericPlayer::onNotify(msg);
    }
}

//--------------------------------------------------
// Private utility functions

bool AudioSfDecoder::wantPrefetch() {
    if (mDataSource != 0) {
        return (mDataSource->flags() & DataSource::kWantsPrefetching);
    } else {
        // happens if an improper data locator was passed, if the media extractor couldn't be
        //  initialized, if there is no audio track in the media, if the OMX decoder couldn't be
        //  instantiated, if the source couldn't be opened, or if the MediaSource
        //  couldn't be started
        SL_LOGV("AudioSfDecoder::wantPrefetch() tries to access NULL mDataSource");
        return false;
    }
}

int64_t AudioSfDecoder::getPositionUsec() {
    Mutex::Autolock _l(mTimeLock);
    if (mStateFlags & kFlagSeeking) {
        return mSeekTimeMsec * 1000;
    } else {
        return mLastDecodedPositionUs;
    }
}

CacheStatus_t AudioSfDecoder::getCacheRemaining(bool *eos) {
    sp<NuCachedSource2> cachedSource =
        static_cast<NuCachedSource2 *>(mDataSource.get());

    CacheStatus_t oldStatus = mCacheStatus;

    status_t finalStatus;
    size_t dataRemaining = cachedSource->approxDataRemaining(&finalStatus);
    *eos = (finalStatus != OK);

    CHECK_GE(mBitrate, 0);

    int64_t dataRemainingUs = dataRemaining * 8000000ll / mBitrate;
    //SL_LOGV("AudioSfDecoder::getCacheRemaining: approx %.2f secs remaining (eos=%d)",
    //       dataRemainingUs / 1E6, *eos);

    if (*eos) {
        // data is buffered up to the end of the stream, it can't get any better than this
        mCacheStatus = kStatusHigh;
        mCacheFill = 1000;

    } else {
        if (mDurationUsec > 0) {
            // known duration:

            //   fill level is ratio of how much has been played + how much is
            //   cached, divided by total duration
            int64_t currentPositionUsec = getPositionUsec();
            if (currentPositionUsec == ANDROID_UNKNOWN_TIME) {
                // if we don't know where we are, assume the worst for the fill ratio
                currentPositionUsec = 0;
            }
            if (mDurationUsec > 0) {
                mCacheFill = (int16_t) ((1000.0
                        * (double)(currentPositionUsec + dataRemainingUs) / mDurationUsec));
            } else {
                mCacheFill = 0;
            }
            //SL_LOGV("cacheFill = %d", mCacheFill);

            //   cache status is evaluated against duration thresholds
            if (dataRemainingUs > DURATION_CACHED_HIGH_MS*1000) {
                mCacheStatus = kStatusHigh;
                //ALOGV("high");
            } else if (dataRemainingUs > DURATION_CACHED_MED_MS*1000) {
                //ALOGV("enough");
                mCacheStatus = kStatusEnough;
            } else if (dataRemainingUs < DURATION_CACHED_LOW_MS*1000) {
                //ALOGV("low");
                mCacheStatus = kStatusLow;
            } else {
                mCacheStatus = kStatusIntermediate;
            }

        } else {
            // unknown duration:

            //   cache status is evaluated against cache amount thresholds
            //   (no duration so we don't have the bitrate either, could be derived from format?)
            if (dataRemaining > SIZE_CACHED_HIGH_BYTES) {
                mCacheStatus = kStatusHigh;
            } else if (dataRemaining > SIZE_CACHED_MED_BYTES) {
                mCacheStatus = kStatusEnough;
            } else if (dataRemaining < SIZE_CACHED_LOW_BYTES) {
                mCacheStatus = kStatusLow;
            } else {
                mCacheStatus = kStatusIntermediate;
            }
        }

    }

    if (oldStatus != mCacheStatus) {
        notifyStatus();
    }

    if (abs(mCacheFill - mLastNotifiedCacheFill) > mCacheFillNotifThreshold) {
        notifyCacheFill();
    }

    return mCacheStatus;
}

void AudioSfDecoder::hasNewDecodeParams() {

    if ((mAudioSource != 0) && mAudioSourceStarted) {
        sp<MetaData> meta = mAudioSource->getFormat();

        int32_t channelCount;
        CHECK(meta->findInt32(kKeyChannelCount, &channelCount));
        int32_t sr;
        CHECK(meta->findInt32(kKeySampleRate, &sr));

        // FIXME similar to onPrepare()
        {
            android::Mutex::Autolock autoLock(mPcmFormatLock);
            SL_LOGV("format changed: old sr=%d, channels=%d; new sr=%d, channels=%d",
                    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE],
                    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS],
                    sr, channelCount);
            mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount;
            mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr;
            mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] =
                    channelCountToMask(channelCount);
        }
        // there's no need to do a notify of PLAYEREVENT_CHANNEL_COUNT,
        // because the only listener is for volume updates, and decoders don't support that
    }

    // alert users of those params
    updateAudioSink();
}

static const char* const kPlaybackOnlyCodecs[] = { MEDIA_MIMETYPE_AUDIO_AMR_NB,
        MEDIA_MIMETYPE_AUDIO_AMR_WB };
#define NB_PLAYBACK_ONLY_CODECS (sizeof(kPlaybackOnlyCodecs)/sizeof(kPlaybackOnlyCodecs[0]))

bool AudioSfDecoder::isSupportedCodec(const char* mime) {
    bool codecRequiresPermission = false;
    for (unsigned int i = 0 ; i < NB_PLAYBACK_ONLY_CODECS ; i++) {
        if (!strcasecmp(mime, kPlaybackOnlyCodecs[i])) {
            codecRequiresPermission = true;
            break;
        }
    }
    if (codecRequiresPermission) {
        // verify only the system can decode, for playback only
        return checkCallingPermission(
                String16("android.permission.ALLOW_ANY_CODEC_FOR_PLAYBACK"));
    } else {
        return true;
    }
}

} // namespace android


text:
<template name="admin_servicedetail">
    {{#if currentUser}}
        {{#if isInRole 'admin'}}
            {{>adminnavbar}}

{{service.name}}

Requests over Time

                    <select class="interval">
                        <option>minute</option>
                        <option selected>hour</option>
                        <option>day</option>
                        <option>week</option>
                        <option>month</option>
                        <option>year</option>
                    </select>
                    <input type="number" class="count" value="24"/>
                    <button class=" btn btn-primary calc">Draw</button>

                <svg class="ROTchart"></svg>

Distribution of Requests by Response Time

                <svg class="TDchart"></svg>

                    <select class="query">
                        <option>uri</option>
                        <option>method</option>
                        <option>code</option>
                        <option selected>excStatus</option>
                        <option>excApiKey</option>
                    </select>
                    <button class=" btn btn-primary calc2">Draw</button>

                    <svg class="QUchart"></svg>

        {{else}}
            {{>usernavbar}}
            {{>userrestricted}}
        {{/if}}
    {{else}}
        {{>usernotloggedin}}
    {{/if}}
</template>

redpajama_set_name: RedPajamaGithub


text:
package org.openqa.selenium.html5;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_APPLICATION_CACHE;
import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_LOCATION_CONTEXT;
import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_SQL_DATABASE;
import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_WEB_STORAGE;
import static org.openqa.selenium.testing.drivers.Browser.HTMLUNIT;
import static org.openqa.selenium.testing.drivers.Browser.IE;
import static org.openqa.selenium.testing.drivers.Browser.MARIONETTE;
import static org.openqa.selenium.testing.drivers.Browser.SAFARI;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.TestUtilities;
import org.openqa.selenium.testing.drivers.WebDriverBuilder;

@Ignore(HTMLUNIT)
@Ignore(IE)
@Ignore(SAFARI)
@Ignore(MARIONETTE)
public class Html5CapabilitiesTest extends JUnit4TestBase {

  private WebDriver localDriver;

  @Before
  public void avoidRemote() {
    // TODO: Resolve why these tests don't work on the remote server
    assumeTrue(TestUtilities.isLocal());
    assumeTrue(TestUtilities.getFirefoxVersion(driver) >= 12);
  }

  @Test
  public void enableWebStorageCapability() {
    configureCapability(SUPPORTS_WEB_STORAGE, true);
    assertThat(hasWebStorage(localDriver)).isTrue();
  }

  @Test
  public void disableWebStorageCapability() {
    configureCapability(SUPPORTS_WEB_STORAGE, false);
    assertThat(hasWebStorage(localDriver)).isFalse();
  }

  private boolean hasWebStorage(WebDriver driver) {
    driver.get(pages.html5Page);
    return (Boolean) ((JavascriptExecutor) driver).executeScript("return !!window.localStorage");
  }

  @Test
  public void enableApplicationCacheCapability() {
    configureCapability(SUPPORTS_APPLICATION_CACHE, true);
    // TODO: Checks that application cache is enabled
  }

  @Test
  public void disableApplicationCacheCapability() {
    configureCapability(SUPPORTS_APPLICATION_CACHE, false);
    // TODO: Checks that application cache is disabled
  }

  @Test
  public void enableLocationContextCapability() {
    configureCapability(SUPPORTS_LOCATION_CONTEXT, true);
    // TODO: Checks that location context is enabled
  }

  @Test
  public void disableLocationContextCapability() {
    configureCapability(SUPPORTS_LOCATION_CONTEXT, false);
    // TODO: Checks that location context is disabled
  }

  @Test
  public void enableDatabaseCapability() {
    configureCapability(SUPPORTS_SQL_DATABASE, true);
    // TODO: Checks that SQL database is enabled
  }

  @Test
  public void disableDatabaseCapability() {
    configureCapability(SUPPORTS_SQL_DATABASE, false);
    // TODO: Checks that SQL database is disabled
  }

  private void configureCapability(String capability, boolean isEnabled) {
    Capabilities desiredCaps = new ImmutableCapabilities(capability, isEnabled);
    localDriver = new WebDriverBuilder().get(desiredCaps);
    Capabilities caps = ((HasCapabilities) localDriver).getCapabilities();
    assertThat(caps.getCapability(capability)).isNotNull();
    assertThat(caps.is(capability)).isEqualTo(isEnabled);
  }

  @After
  public void quitDriver() {
    if (this.localDriver != null) {
      this.localDriver.quit();
      this.localDriver = null;
    }
  }
}


text:
const fs = require('fs');
const path = require('path');
const parse = require('csv-parse');
const transform = require('stream-transform');

/**
 * generate JSON documents in 'public/' directory for demo
**/
const files = [
    'births',
    'deaths',
];

const seen = {};

const transformer = (holder) => transform(function(record, callback) {
    const pre = holder.first ? '' : ',';
    holder.first = false;
    callback(null, pre + JSON.stringify(record));
}, {parallel: 1});

function saveDataset() {
  const name = files.shift();

  return new Promise((resolve, reject) => {
    const parsing = parse({columns:true, auto_parse:true});
    const outFile = fs.createWriteStream(path.join(__dirname, `../public/data/${name}.json`));
    outFile.write('{"records":[\n');

    fs.createReadStream(path.join(__dirname, `./${name}.csv`))
        .pipe(parsing)
        .pipe(transformer({first:true}))
        .pipe(outFile);

    parsing.on('finish', () => {
        outFile.close();
        fs.appendFileSync(path.join(__dirname, `../public/data/${name}.json`),'\n]}');

        if (files.length) resolve(saveDataset());
        else resolve(true);
    });
  });
}

saveDataset().then(() => 0);


text:
import React from 'react';

import { cx } from './lib/cx';

export type ToggleRefinementClassNames = {
  /**
   * Class names to apply to the root element
   */
  root: string;
  /**
   * Class names to apply to the label element
   */
  label: string;
  /**
   * Class names to apply to the checkbox element
   */
  checkbox: string;
  /**
   * Class names to apply to the label text
   */
  labelText: string;
};

export type ToggleRefinementProps = Omit<
  React.ComponentProps<'div'>,
  'onChange'
> &
  Pick<React.ComponentProps<'input'>, 'checked'> & {
    classNames?: Partial<ToggleRefinementClassNames>;
    onChange(isChecked: boolean): void;
    label: string;
  };

export function ToggleRefinement({
  classNames = {},
  checked,
  onChange,
  label,
  ...props
}: ToggleRefinementProps) {
  return (
    <div
      {...props}
      className={cx('ais-ToggleRefinement', classNames.root, props.className)}
    >
      <label className={cx('ais-ToggleRefinement-label', classNames.label)}>
        <input
          className={cx('ais-ToggleRefinement-checkbox', classNames.checkbox)}
          type="checkbox"
          checked={checked}
          onChange={(event) => {
            onChange(event.target.checked);
          }}
        />

        <span
          className={cx('ais-ToggleRefinement-labelText', classNames.labelText)}
        >
          {label}
        </span>
      </label>
    </div>
  );
}


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * ReplaceTransitGatewayRouteRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ReplaceTransitGatewayRouteRequestMarshaller implements Marshaller<Request<ReplaceTransitGatewayRouteRequest>, ReplaceTransitGatewayRouteRequest> {

    public Request<ReplaceTransitGatewayRouteRequest> marshall(ReplaceTransitGatewayRouteRequest replaceTransitGatewayRouteRequest) {

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

        Request<ReplaceTransitGatewayRouteRequest> request = new DefaultRequest<ReplaceTransitGatewayRouteRequest>(replaceTransitGatewayRouteRequest,
                "AmazonEC2");
        request.addParameter("Action", "ReplaceTransitGatewayRoute");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (replaceTransitGatewayRouteRequest.getDestinationCidrBlock() != null) {
            request.addParameter("DestinationCidrBlock", StringUtils.fromString(replaceTransitGatewayRouteRequest.getDestinationCidrBlock()));
        }

        if (replaceTransitGatewayRouteRequest.getTransitGatewayRouteTableId() != null) {
            request.addParameter("TransitGatewayRouteTableId", StringUtils.fromString(replaceTransitGatewayRouteRequest.getTransitGatewayRouteTableId()));
        }

        if (replaceTransitGatewayRouteRequest.getTransitGatewayAttachmentId() != null) {
            request.addParameter("TransitGatewayAttachmentId", StringUtils.fromString(replaceTransitGatewayRouteRequest.getTransitGatewayAttachmentId()));
        }

        if (replaceTransitGatewayRouteRequest.getBlackhole() != null) {
            request.addParameter("Blackhole", StringUtils.fromBoolean(replaceTransitGatewayRouteRequest.getBlackhole()));
        }

        return request;
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="AnimationNodeStateMachine" inherits="AnimationRootNode" version="4.0">
	<brief_description>
		State machine for control of animations.
	</brief_description>
	<description>
		Contains multiple nodes representing animation states, connected in a graph. Node transitions can be configured to happen automatically or via code, using a shortest-path algorithm. Retrieve the [AnimationNodeStateMachinePlayback] object from the [AnimationTree] node to control it programmatically.
		[b]Example:[/b]
		[codeblocks]
		[gdscript]
		var state_machine = $AnimationTree.get("parameters/playback")
		state_machine.travel("some_state")
		[/gdscript]
		[csharp]
		var stateMachine = GetNode<AnimationTree>("AnimationTree").Get("parameters/playback") as AnimationNodeStateMachinePlayback;
		stateMachine.Travel("some_state");
		[/csharp]
		[/codeblocks]
	</description>
	<tutorials>
		<link title="AnimationTree">https://docs.godotengine.org/en/latest/tutorials/animation/animation_tree.html</link>
	</tutorials>
	<methods>
		<method name="add_node">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<argument index="1" name="node" type="AnimationNode">
			</argument>
			<argument index="2" name="position" type="Vector2" default="Vector2( 0, 0 )">
			</argument>
			<description>
				Adds a new node to the graph. The [code]position[/code] is used for display in the editor.
			</description>
		</method>
		<method name="add_transition">
			<return type="void">
			</return>
			<argument index="0" name="from" type="StringName">
			</argument>
			<argument index="1" name="to" type="StringName">
			</argument>
			<argument index="2" name="transition" type="AnimationNodeStateMachineTransition">
			</argument>
			<description>
				Adds a transition between the given nodes.
			</description>
		</method>
		<method name="get_end_node" qualifiers="const">
			<return type="String">
			</return>
			<description>
				Returns the graph's end node.
			</description>
		</method>
		<method name="get_graph_offset" qualifiers="const">
			<return type="Vector2">
			</return>
			<description>
				Returns the draw offset of the graph. Used for display in the editor.
			</description>
		</method>
		<method name="get_node" qualifiers="const">
			<return type="AnimationNode">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<description>
				Returns the animation node with the given name.
			</description>
		</method>
		<method name="get_node_name" qualifiers="const">
			<return type="StringName">
			</return>
			<argument index="0" name="node" type="AnimationNode">
			</argument>
			<description>
				Returns the given animation node's name.
			</description>
		</method>
		<method name="get_node_position" qualifiers="const">
			<return type="Vector2">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<description>
				Returns the given node's coordinates. Used for display in the editor.
			</description>
		</method>
		<method name="get_start_node" qualifiers="const">
			<return type="String">
			</return>
			<description>
				Returns the graph's end node.
			</description>
		</method>
		<method name="get_transition" qualifiers="const">
			<return type="AnimationNodeStateMachineTransition">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
				Returns the given transition.
			</description>
		</method>
		<method name="get_transition_count" qualifiers="const">
			<return type="int">
			</return>
			<description>
				Returns the number of connections in the graph.
			</description>
		</method>
		<method name="get_transition_from" qualifiers="const">
			<return type="StringName">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
				Returns the given transition's start node.
			</description>
		</method>
		<method name="get_transition_to" qualifiers="const">
			<return type="StringName">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
				Returns the given transition's end node.
			</description>
		</method>
		<method name="has_node" qualifiers="const">
			<return type="bool">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<description>
				Returns [code]true[/code] if the graph contains the given node.
			</description>
		</method>
		<method name="has_transition" qualifiers="const">
			<return type="bool">
			</return>
			<argument index="0" name="from" type="StringName">
			</argument>
			<argument index="1" name="to" type="StringName">
			</argument>
			<description>
				Returns [code]true[/code] if there is a transition between the given nodes.
			</description>
		</method>
		<method name="remove_node">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<description>
				Deletes the given node from the graph.
			</description>
		</method>
		<method name="remove_transition">
			<return type="void">
			</return>
			<argument index="0" name="from" type="StringName">
			</argument>
			<argument index="1" name="to" type="StringName">
			</argument>
			<description>
				Deletes the transition between the two specified nodes.
			</description>
		</method>
		<method name="remove_transition_by_index">
			<return type="void">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
				Deletes the given transition by index.
			</description>
		</method>
		<method name="rename_node">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<argument index="1" name="new_name" type="StringName">
			</argument>
			<description>
				Renames the given node.
			</description>
		</method>
		<method name="replace_node">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<argument index="1" name="node" type="AnimationNode">
			</argument>
			<description>
			</description>
		</method>
		<method name="set_end_node">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<description>
				Sets the given node as the graph end point.
			</description>
		</method>
		<method name="set_graph_offset">
			<return type="void">
			</return>
			<argument index="0" name="offset" type="Vector2">
			</argument>
			<description>
				Sets the draw offset of the graph. Used for display in the editor.
			</description>
		</method>
		<method name="set_node_position">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<argument index="1" name="position" type="Vector2">
			</argument>
			<description>
				Sets the node's coordinates. Used for display in the editor.
			</description>
		</method>
		<method name="set_start_node">
			<return type="void">
			</return>
			<argument index="0" name="name" type="StringName">
			</argument>
			<description>
				Sets the given node as the graph start point.
			</description>
		</method>
	</methods>
	<constants>
	</constants>
</class>


text:
namespace mesos {
namespace internal {
namespace slave {
namespace docker {
namespace volume {
namespace paths {

// We checkpoint the information about docker volumes that each
// container uses. The layout is as follows:
//   <docker_volume_checkpoint_dir> ('--docker_volume_checkpoint_dir' flag)
//      |-- <ID of Container1>/
//      |      |-- volumes
//      |-- <ID of Container2>/
//      |      |-- volumes
//      |-- <ID of Container3>/
//      |-- ...

std::string getContainerDir(
    const std::string& rootDir,
    const std::string& containerId);

std::string getVolumesPath(
    const std::string& rootDir,
    const std::string& containerId);

} // namespace paths {
} // namespace volume {
} // namespace docker {
} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __ISOLATOR_VOLUME_PATHS_HPP__


text:
@interface YLOffScreenRender : UIViewController

@end


text:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <tenantName>contoso.onmicrosoft.com</tenantName>
  <pictureSourceCsv>c:\temp\userlist.csv</pictureSourceCsv>
  <targetLibraryPath>/User Photos/Profile Pictures</targetLibraryPath>
  <thumbs upload3Thumbs="true" createSMLThumbs="true"/>
  <additionalProfileProperties />
  <logFile path="c:\temp\log.txt" enableLogging="true" loggingLevel="verbose" />
  <uploadDelay>500</uploadDelay>
 </configuration>


text:
package org.nem.monitor;

import org.apache.commons.io.FileUtils;
import org.hamcrest.core.IsEqual;
import org.junit.*;
import org.mockito.Mockito;
import org.nem.core.connect.client.DefaultAsyncNemConnector;
import org.nem.core.model.NemStatus;
import org.nem.core.model.ncc.NemRequestResult;
import org.nem.core.node.NodeEndpoint;
import org.nem.core.serialization.*;
import org.nem.core.utils.LockFile;
import org.nem.monitor.node.NemNodePolicy;

import java.io.*;
import java.util.concurrent.CompletableFuture;

public class NemConnectorTest {
	private static final String WORKING_DIRECTORY = System.getProperty("user.dir");
	private static final File TEST_FILE_DIRECTORY = new File(WORKING_DIRECTORY, "test_files");
	private static final File TEST_LOCK_FILE = new File(TEST_FILE_DIRECTORY, "test.lock");

	//region BeforeClass / AfterClass

	@BeforeClass
	public static void createTestFiles() throws IOException {
		final boolean result = TEST_FILE_DIRECTORY.mkdir() && TEST_LOCK_FILE.createNewFile();

		if (!result) {
			throw new RuntimeException("unable to initialize test suite");
		}
	}

	@AfterClass
	public static void removeTestFiles() throws IOException {
		FileUtils.deleteDirectory(TEST_FILE_DIRECTORY);
	}

	//endregion

	@Test
	public void getStatusReturnsRunningWhenNoExceptionIsThrownAndDeserializerIsNull() {
		// Arrange:
		final TestContext context = new TestContext();
		Mockito.when(context.asyncConnector.getAsync(Mockito.any(), Mockito.any(), Mockito.any()))
				.thenReturn(CompletableFuture.completedFuture(null));

		// Act:
		final NemStatus status = context.connector.getStatus().join();

		// Assert:
		Assert.assertThat(status, IsEqual.equalTo(NemStatus.RUNNING));
		context.assertStatusCalledOnce();
	}

	@Test
	public void getStatusReturnsDeserializedStatusWhenNoExceptionIsThrown() {
		// Arrange:
		final TestContext context = new TestContext();
		final Deserializer deserializer = new BinaryDeserializer(BinarySerializer.serializeToBytes(new NemRequestResult(-1, 4, "?")), null);
		Mockito.when(context.asyncConnector.getAsync(Mockito.any(), Mockito.any(), Mockito.any()))
				.thenReturn(CompletableFuture.completedFuture(deserializer));

		// Act:
		final NemStatus status = context.connector.getStatus().join();

		// Assert:
		Assert.assertThat(status, IsEqual.equalTo(NemStatus.BOOTED));
		context.assertStatusCalledOnce();
	}

	@Test
	public void getStatusReturnsRunningWhenNemNodeExpectedExceptionIsThrown() {
		// Arrange:
		final TestContext context = new TestContext();
		Mockito.when(context.asyncConnector.getAsync(Mockito.any(), Mockito.any(), Mockito.any()))
				.thenReturn(CompletableFuture.supplyAsync(() -> { throw new NemNodeExpectedException(); }));

		// Act:
		final NemStatus status = context.connector.getStatus().join();

		// Assert:
		Assert.assertThat(status, IsEqual.equalTo(NemStatus.RUNNING));
		context.assertStatusCalledOnce();
	}

	@Test
	public void getStatusReturnsStoppedWhenOtherExceptionIsThrownAndLockFileIsNotLocked() {
		// Arrange:
		final TestContext context = new TestContext();
		Mockito.when(context.asyncConnector.getAsync(Mockito.any(), Mockito.any(), Mockito.any()))
				.thenReturn(CompletableFuture.supplyAsync(() -> { throw new RuntimeException(); }));

		// Act:
		final NemStatus status = context.connector.getStatus().join();

		// Assert:
		Assert.assertThat(status, IsEqual.equalTo(NemStatus.STOPPED));
		context.assertStatusCalledOnce();
	}

	@Test
	public void getStatusReturnsStartingWhenOtherExceptionIsThrownAndLockFileIsLocked() throws IOException {
		// Arrange:
		try (final Closeable ignored = LockFile.tryAcquireLock(TEST_LOCK_FILE)) {
			final TestContext context = new TestContext();
			Mockito.when(context.asyncConnector.getAsync(Mockito.any(), Mockito.any(), Mockito.any()))
					.thenReturn(CompletableFuture.supplyAsync(() -> { throw new RuntimeException(); }));

			// Act:
			final NemStatus status = context.connector.getStatus().join();

			// Assert:
			Assert.assertThat(status, IsEqual.equalTo(NemStatus.STARTING));
			context.assertStatusCalledOnce();
		}
	}

	@Test
	public void shutdownDelegatesToAsyncConnector() {
		// Arrange:
		final TestContext context = new TestContext();
		Mockito.when(context.asyncConnector.getAsync(Mockito.any(), Mockito.any(), Mockito.any()))
				.thenReturn(CompletableFuture.completedFuture(null));

		// Act:
		context.connector.shutdown().join();

		// Assert:
		context.assertShutdownCalledOnce();
	}

	private static class TestContext {
		private final NemNodePolicy policy;
		private final DefaultAsyncNemConnector<String> asyncConnector;
		private final NemConnector connector;

		@SuppressWarnings("unchecked")
		private TestContext() {
			this.policy = Mockito.mock(NemNodePolicy.class);
			Mockito.when(this.policy.getEndpoint()).thenReturn(NodeEndpoint.fromHost("10.0.0.18"));
			Mockito.when(this.policy.getLockFile()).thenReturn(TEST_LOCK_FILE);
			Mockito.when(this.policy.mapToUrlPath(Mockito.any()))
					.then(invocationOnMock -> String.format("{%s}", invocationOnMock.getArguments()[0]));

			this.asyncConnector = Mockito.mock(DefaultAsyncNemConnector.class);
			this.connector = new NemConnector(this.policy, this.asyncConnector);
		}

		private void assertStatusCalledOnce() {
			Mockito.verify(this.asyncConnector, Mockito.times(1)).getAsync(NodeEndpoint.fromHost("10.0.0.18"), "{/status}", null);
		}

		private void assertShutdownCalledOnce() {
			Mockito.verify(this.asyncConnector, Mockito.times(1)).getAsync(NodeEndpoint.fromHost("10.0.0.18"), "{/shutdown}", null);
		}
	}
}


text:
<?php $form = $this->beginWidget('UActiveForm', array(
    'id'                              => 'registration-form',
    'enableAjaxValidation'            => true,
    'disableAjaxValidationAttributes' => array('RegistrationForm_verifyCode'),
    'clientOptions'                   => array(
        'validateOnSubmit' => true,
    ),
    'htmlOptions'                     => array(
        'class'   => 'form-horizontal form-groups-bordered validate',
        'role'    => 'form',
        'enctype' => 'multipart/form-data',
    ),
)); ?>
<?php
    $profileFields = $profile->getFields();
    if ($profileFields) {
        foreach ($profileFields as $field) { ?>

                <?php echo $form->labelEx($profile, $field->varname, array('class' => 'col-sm-3 control-label')); ?>

                    <?php
                        if ($widgetEdit = $field->widgetEdit($profile)) {
                            echo $widgetEdit;
                        } elseif ($field->range) {
                            echo $form->dropDownList($profile, $field->varname, Profile::range($field->range), array(
                                'class' => 'form-control',
                            ));
                        } elseif ($field->field_type == "TEXT") {
                            echo $form->textArea($profile, $field->varname, array(
                                'rows'  => 6,
                                'cols'  => 50,
                                'class' => 'form-control',
                                //'data-validate'         => 'required',
                                //'data-message-required' => 'Wajib diisi',
                            ));
                        } else {
                            echo $form->textField($profile, $field->varname, array(
                                'size'      => 60,
                                'maxlength' => (($field->field_size) ? $field->field_size : 255),
                                'class'     => 'form-control',
                                //'data-validate'         => 'required',
                                //'data-message-required' => 'Wajib diisi',
                            ));
                        }
                    ?>

                <?php echo $form->error($profile, $field->varname); ?>

            <?php
        }
    }
?>

    <?php echo CHtml::activeLabel($model, 'email', array('for' => 'field-1', 'class' => 'col-sm-3 control-label')); ?>

        <?php echo CHtml::activeEmailField($model, 'email', array(
            'class' => 'form-control',
            //'name'                  => 'User[email]',
            //'data-validate'         => 'required',
            //'data-message-required' => 'Wajib diisi',
        )); ?>

    <?php echo CHtml::activeLabel($model, 'username',
        array('for' => 'field-1', 'class' => 'col-sm-3 control-label')); ?>

        <?php echo CHtml::activeTextField($model, 'username', array(
            'class' => 'form-control',
            //'name'                  => 'User[username]',
            //'data-validate'         => 'required',
            //'data-message-required' => 'Wajib diisi',
        )); ?>

    <?php echo CHtml::activeLabel($model, 'password',
        array('for' => 'field-1', 'class' => 'col-sm-3 control-label')); ?>

        <?php echo CHtml::activePasswordField($model, 'password', array(
            'class' => 'form-control',
            //'name'                  => 'User[password]',
            //'data-validate'         => 'required',
            //'data-message-required' => 'Wajib diisi',
        )); ?>

    <?php echo CHtml::activeLabel($model, 'verifyPassword',
        array('for' => 'field-1', 'class' => 'col-sm-3 control-label')); ?>

        <?php echo CHtml::activePasswordField($model, 'verifyPassword', array(
            'class' => 'form-control',
            //'name'                  => 'User[verifyPassword]',
            //'data-validate'         => 'required',
            //'data-message-required' => 'Wajib diisi',
        )); ?>

<?php if (AdminModule::doCaptcha('registration')): ?>

        <?php echo $form->labelEx($model, 'verifyCode', array('class' => 'col-sm-3 control-label')); ?>

            <?php $this->widget('CCaptcha'); ?>
            <?php echo $form->textField($model, 'verifyCode', array(
                'class' => 'form-control',
                //'data-validate'         => 'required',
                //'data-message-required' => 'Wajib diisi',
            ));
            ?>
            <?php echo $form->error($model, 'verifyCode'); ?>

<?php echo AdminModule::t("Please enter the letters as they are shown in the image above."); ?>

<?php echo AdminModule::t("Letters are not case-sensitive."); ?>

<?php endif; ?>

        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',
            array('class' => 'btn btn-primary add-post')); ?>
        <?php echo CHtml::resetButton('Cancel',
            array('class' => 'btn btn-primary cancel')); ?>

<?php $this->endWidget(); ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<workspaceFilter version="1.0">
    <filter root="/apps/wcm/core/content/editor/jcr:content/content/items/content/header/items/headerbar"/>
    <filter root="/apps/adobe/samples/backtosites/clientlibs"/>
</workspaceFilter>


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Create Viewshed

The Create Viewshed tool creates areas where
an observer can see objects on the ground. The analysis
points can represent either observers (such as people on the ground
or lookouts in a fire tower) or observed objects (such as wind
turbines, water towers, vehicles, or other people). The result areas are those areas where the observers
can see the observed objects and vice versa: the observed objects
can see the observers.

Both the
observers and the observed objects  can have a height above ground, and these heights are used in determining visibility.
For example, a viewshed computed for 400-foot wind turbines and six-foot people standing on the ground will typically be larger  than a viewshed computed for 200-foot turbines and six-foot people.

Note that the computation of the viewshed does
not account for obstructions such as trees or buildings. You can
think of the computation as occurring on bare ground devoid of
anything but the observer and observed objects.

The  result layer contains   area features representing visible areas. The  Frequency field  records the number of analysis points that can see each area. For example, if you have five input points, each  representing a fire lookout tower, the Frequency field will have values between one and five; areas with a value of one can only be seen by one tower, and areas with a value of five can be seen by all towers. The result layer also contains the DEMResolution field, which records the resolution  of the digital elevation model (DEM) used to create the viewsheds.

If  Use current map extent is checked, only the features that are visible within the current map extent will be analyzed.  If unchecked, all features in the analysis layer will be analyzed, even if they are outside the current map extent.

Height of analysis points

This is the height above ground of your analysis points.    The default is approximately the average height of a person.

Height of other objects on the ground

This is the height of  structures or people on the ground used to establish visibility. The result viewshed are those areas where an analysis point can see these other objects.  The converse is also true; the other objects can see an analysis point.

If your analysis points represent wind turbines and you want to determine where people standing on the ground can see the turbines, enter the average height of a person (approximately 6 feet).  The result is those areas where a person standing on the ground can see the wind turbines.

If your analysis points represent fire lookout towers and you want to determine which lookout towers can see a smoke plume 20 feet high or higher, enter 20 feet for the height.  The result is those areas where a fire lookout tower can see a smoke plume at least 20 feet high.

If your analysis points represent scenic overlooks along roads and trails and you want to determine where wind turbines 400 feet high or higher can be seen, enter 400 feet for the height.  The result is those areas where a person standing at a scenic overlook can see a wind turbine at least 400 feet high.

If your analysis points represent scenic overlooks and you want to determine how much area on the ground people standing at the overlook can see, enter zero.  The result is those areas that can be seen from the scenic overlook.

Maximum distance

This is a cutoff distance where the computation of visible areas stops. Beyond this distance, it is unknown whether the analysis points and the other objects  can see each other. Large values increase computation time. The maximum allowed value is 18.6 miles (30 kilometers).

Result layer
name

This is the name of the layer that will be created in  your  My Content  and added to the map.  The default  name is based on the analysis type and the analysis layer name. If the layer already exists, you will be asked to confirm if you want to overwrite it.

Using the  Save result in drop-down box, you can  specify the name of a folder in My Content where the result will be saved.


text:
<?php

namespace Myapp\CroisiereBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * BateauTypeCabineRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class BateauTypeCabineRepository extends EntityRepository
{

    public function findByBateau()
{

    $qb = $this->createQueryBuilder('p');
     $qb->where('p.id =:id')
      ->setParameter('id', 1);

// Puis on filtre sur le nom des catégories à l'aide d'un IN

  return $qb->getQuery()
            ->getResult();

}

}


text:
@implementation A_JSONHelper

+ (NSDictionary*)_tidyDict: (NSDictionary*) _dict {
    NSMutableDictionary *_tidyDict = [[NSMutableDictionary alloc] init];
    for (NSString *_key in [_dict allKeys]) {
        if ([[_dict valueForKey:_key] isKindOfClass:[NSDate class]]) {
            [_tidyDict setValue:[NSString stringWithFormat:@"%@", [_dict valueForKey:_key]] forKey:_key];
        }else {
            [_tidyDict setValue:[_dict valueForKey:_key] forKey:_key];
        }
    }
    return _tidyDict;
}

+ (NSDictionary*)A_ConvertJSONToDictionary: (NSString*)JSONStr{
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData: [JSONStr dataUsingEncoding:NSUTF8StringEncoding]
                                                        options: NSJSONReadingMutableContainers
                                                          error: &error];
    if (!dic) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <JSON to Dictionary error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        return dic;
    }
}
+ (NSArray*)A_ConvertJSONToArray: (NSString*)JSONStr{
    NSError *error = nil;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData: [JSONStr dataUsingEncoding:NSUTF8StringEncoding]
                                                   options: NSJSONReadingMutableContainers
                                                     error: &error];
    if (!arr) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <JSON to Array error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        return arr;
    }
}

+ (NSString*)A_ConvertDictionaryToJSON: (NSDictionary*)Dict{
    NSError *error = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: [self _tidyDict: Dict]
                                                       options: 0
                                                         error: &error];
    if (!jsonData) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <Dictionary to JSON error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
        return JSONString;
    }
}
+ (NSString*)A_ConvertArrayToJSON: (NSArray*)Arr{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: Arr
                                                       options: 0
                                                         error: &error];
    if (!jsonData) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <Array to JSON error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
        return JSONString;
    }
}

+ (NSData*)A_ConvertDictionaryToData: (NSDictionary*)Dict{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: [self _tidyDict: Dict]
                                                       options: 0
                                                         error: &error];
    if (!jsonData) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <Dictionary to Data error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        return jsonData;
    }
}
+ (NSData*)A_ConvertArrayToData: (NSArray*)Arr{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: Arr
                                                       options: 0
                                                         error: &error];
    if (!jsonData) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <Array to Data error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        return jsonData;
    }
}

+ (NSDictionary*)A_ConvertJSONDataToDictionary: (NSData*)JSONData {
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData: JSONData
                                                        options: NSJSONReadingMutableContainers
                                                          error: &error];
    if (!dic) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <JSON Data to Dictionary error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        return dic;
    }
}
+ (NSArray*)A_ConvertJSONDataToArray: (NSData*)JSONData {
    NSError *error = nil;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData: JSONData
                                                   options: NSJSONReadingMutableContainers
                                                     error: &error];
    if (!arr) {
#ifndef NDEBUG
        NSLog(@"\r\n -------- \r\n [MESSAGE FROM A IOS HELPER] \r\n <JSON Data to Array error>  \r\n %@ \r\n -------- \r\n\r\n", error);
#endif
        return nil;
    } else {
        return arr;
    }
}

@end


text:
class CreateTphData < ActiveRecord::Migration[5.1]
  def change
    create_table :tph_data, id: false do |t|
      t.timestamp :timestamp
      t.float :t
      t.float :p
      t.float :h
    end

    add_index :tph_data, :timestamp
  end
end


text:
 package oracle.ateam.sample.mobile.v2.persistence.metadata;
import oracle.adfmf.util.Utility;
import oracle.adfmf.util.XmlAnyDefinition;

/**
 * Implementation of SOAP method parameter or REST resource parameter that reads values from persistenceMapping.xml
 */
public class XMLMethodParameter extends XmlAnyDefinition implements MethodParameter
{

  public XMLMethodParameter(XmlAnyDefinition xmlAnyDefinition)
  {
    super(xmlAnyDefinition);
  }

  public String getName()
  {
    return getAttributeStringValue("name");
  }

  public String getValueProvider()
  {
    return getAttributeStringValue("valueProvider");
  }

  public String getDataObjectAttribute()
  {
    return getAttributeStringValue("dataObjectAttribute");
  }

  public String getValue()
  {
    return getAttributeStringValue("value");
  }

  public String getJavaType()
  {
    return getAttributeStringValue("javaType");
  }

  public Class getJavaTypeClass()
  {
    String type = getJavaType();
    if (type==null)
    {
      type = "java.lang.String";
    }
    try
    {
      return Utility.loadClass(type);
    }
    catch (ClassNotFoundException e)
    {
    }
    return String.class;
  }

  public boolean isLiteralValue()
  {
    return MethodParameter.LITERAL_VALUE.equalsIgnoreCase(getValueProvider());
  }

  public boolean isELExpression()
  {
    return MethodParameter.EL_EXPRESSION.equalsIgnoreCase(getValueProvider());
  }

  public boolean isDataObjectAttribute()
  {
    return MethodParameter.DATA_OBJECT_ATTRIBUTE.equalsIgnoreCase(getValueProvider());
  }

  public boolean isSerializedDataObject()
  {
    return MethodParameter.SERIALIZED_DATA_OBJECT.equalsIgnoreCase(getValueProvider());
  }

  public boolean isSearchValue()
  {
    return MethodParameter.SEARCH_VALUE.equalsIgnoreCase(getValueProvider());
  }

  public boolean isPathParam()
  {
    return getAttributeBooleanValue("pathParam",false);
  }
}


text:
<!DOCTYPE html>

    <title>Subscript Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

Sourcery 1.8.2 Docs (100% documented)

View on GitHub

          <form role="search" action="../search.json">
            <input type="text" placeholder="Search documentation" data-typeahead>
          </form>

        Sourcery Reference

        Subscript Class Reference

            Guides

                Installing

                Usage

                Writing templates

            Examples

                Equatable

                Hashable

                Enum cases

                Lenses

                Mocks

                Codable

                Diffable

                Diffable

                LinuxMain

                Decorator

            Types

                Types

                Type

                Protocol

                Class

                Struct

                Enum

                EnumCase

                AssociatedValue

                AssociatedType

                Variable

                Method

                MethodParameter

                Subscript

                TypeName

                TupleType

                TupleElement

                ArrayType

                DictionaryType

                ClosureType

                GenericType

                GenericTypeParameter

                Attribute

                ProtocolComposition

            Other Classes

                ClosureParameter

                DiffableResult

                GenericRequirement

                – Relationship

                Import

                Modifier

            Other Enumerations

                Composer

            Other Extensions

                Array

                String

                StringProtocol

            Other Protocols

                Annotated

                Definition

                Documented

                Typed

            Other Type Aliases

                Annotations

                Documentation

                SourceryModifier

Subscript

@objcMembers
public final class Subscript : NSObject, SourceryModel, Annotated, Documented, Definition

Describes subscript

                    parameters

Method parameters

Declaration

Swift

public var parameters: [MethodParameter]

                    returnTypeName

Return value type name used in declaration, including generic constraints, i.e. where T: Equatable

Declaration

Swift

public var returnTypeName: TypeName

                    actualReturnTypeName

Actual return value type name if declaration uses typealias, otherwise just a returnTypeName

Declaration

Swift

public var actualReturnTypeName: TypeName { get }

                    returnType

Actual return value type, if known

Declaration

Swift

public var returnType: Type?

                    isOptionalReturnType

Whether return value type is optional

Declaration

Swift

public var isOptionalReturnType: Bool { get }

                    isImplicitlyUnwrappedOptionalReturnType

Whether return value type is implicitly unwrapped optional

Declaration

Swift

public var isImplicitlyUnwrappedOptionalReturnType: Bool { get }

                    unwrappedReturnTypeName

Return value type name without attributes and optional type information

Declaration

Swift

public var unwrappedReturnTypeName: String { get }

                    isFinal

Whether method is final

Declaration

Swift

public var isFinal: Bool { get }

                    readAccess

Variable read access level, i.e. internal, private, fileprivate, public, open

Declaration

Swift

public let readAccess: String

                    writeAccess

Variable write access, i.e. internal, private, fileprivate, public, open.
For immutable variables this value is empty string

Declaration

Swift

public var writeAccess: String

                    isMutable

Whether variable is mutable or not

Declaration

Swift

public var isMutable: Bool { get }

                    annotations

Annotations, that were created with // sourcery: annotation1, other = “annotation value”, alterantive = 2

Declaration

Swift

public let annotations: Annotations

                    documentation

Declaration

Swift

public let documentation: Documentation

                    definedInTypeName

Reference to type name where the method is defined,
nil if defined outside of any enum, struct, class etc

Declaration

Swift

public let definedInTypeName: TypeName?

                    actualDefinedInTypeName

Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a definedInTypeName

Declaration

Swift

public var actualDefinedInTypeName: TypeName? { get }

                    definedInType

Reference to actual type where the object is defined,
nil if defined outside of any enum, struct, class etc or type is unknown

Declaration

Swift

public var definedInType: Type?

                    attributes

Method attributes, i.e. @discardableResult

Declaration

Swift

public let attributes: AttributeList

                    modifiers

Method modifiers, i.e. private

Declaration

Swift

public let modifiers: [SourceryModifier]

Copyright © 2016-2021 Pixle. All rights reserved.

Generated by jazzy ♪♫ v0.14.0, a Realm project.


text:
module Stevedore
  class Aws
    def initialize
      ::Aws.config.update(
        region: ENV['AWS_REGION'],
        credentials: ::Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
      )
      @cf = ::Aws::CloudFormation::Client.new
      @ecr = ::Aws::ECR::Client.new
    end

    # Cloud Formation

    def create_cloud_formation_stack
      validate_cloud_formation_template

      resp = @cf.create_stack(
        stack_name: Project.name,
        template_body: cloud_formation_template,
        tags: [
          {
            key: 'Name',
            value: Project.name
          }
        ]
      )

      wait_cloud_formation(:stack_create_complete, stack_name: resp.stack_id)
    end

    def delete_cloud_formation_stack
      @cf.delete_stack(stack_name: Project.name)
      wait_cloud_formation(:stack_delete_complete, stack_name: Project.name)
    end

    def update_cloud_formation_stack
      validate_cloud_formation_template

      resp = @cf.update_stack(
        stack_name: Project.name,
        template_body: cloud_formation_template
      )

      wait_cloud_formation(:stack_update_complete, stack_name: resp.stack_id)
    end

    def validate_cloud_formation_template
      @cf.validate_template(template_body: cloud_formation_template)
    end

    # ECR

    def get_ecr_token
      raw_token = @ecr.get_authorization_token.authorization_data.first.authorization_token
      Base64.decode64(raw_token).split(':').last
    end

    private

    def cloud_formation_template
      ERB.new(File.read("#{Project.root_dir}/#{ENV['AWS_CLOUD_FORMATION_TEMPLATE_PATH'] || 'cloud_formation_template.json'}"), nil, '%<>-').result(binding)
    end

    def wait_cloud_formation(waiter_name, params={})
      print "Waiting for #{waiter_name} "
      @cf.wait_until(waiter_name, params) do |w|
        w.before_wait { print '.' }
      end
      puts ' Done'
    end
  end
end


text:
#ifndef GRAPHICS_H_
#define GRAPHICS_H_

#include <iostream>
#include <stdio.h>
#include <math.h>
/**
 * Graficos
 */
class Graphics {

    public:
        Graphics(int base, int lenght, float score);
        void boundaries(int b);
        void description();
        void graph(float c, float w, float e);
        void scorePrint();

    private:
        int base;
        int lenght;
        float score;
};
#endif


text: - Added the indicator attributes to the outputs of the ***tc-get-indicator*** command.


text:
import java.util.ArrayList;
import java.util.Hashtable;

/**
 *
 */

/**
 * @author wgf2104
 *
 */
public class BaconGraph {

	//hashmap from movie title to array of actors
	private Hashtable<BaconNode, ArrayList<BaconEdge>> graph;

	/**
	 * Initalize a Bacon Degrees Graph with a given depth
	 * @param degrees depth of representation
	 */
	public BaconGraph ( ) {
		graph = new Hashtable<BaconNode, ArrayList<BaconEdge>>();
	}

	/**
	 * Add an actor node to the graph
	 * @param v vertex to be added
	 */
	public void addVertex ( BaconNode v ) {
		graph.put(v, new ArrayList<BaconEdge>());
	}

	/**
	 * Add edge between two vertices on the graph
	 * @param v1 first vertex of edge
	 * @param v2 second vertex of edge
	 * @param movie edge label
	 */
	public void addEdge ( BaconNode v1, BaconNode v2, String movie) {
		if(!graph.containsKey(v1))
			addVertex(v1);
		if(!graph.containsKey(v2))
			addVertex(v2);
		graph.get(v1).add(new BaconEdge(v1, v2, movie));
		graph.get(v2).add(new BaconEdge(v1, v2, movie));
	}

	/**
	 * Get Edges for a given vertex
	 * @param v vertex to analyze
	 * @return arraylist of associated edges
	 */
	public ArrayList<BaconEdge> getEdges ( BaconNode v ) {
		return graph.get(v);
	}

	/**
	 * Get size of map
	 * @return number of vertices
	 */
	public int getSize ( ) {
		return graph.size();
	}

	/**
	 * Get local edge density - since graph is symmetric, incount == outcount.
	 * @param v vertex to analyze
	 * @return size of edgelist
	 */
	public int getOutCount ( BaconNode v ) {
		return graph.get(v).size();
	}

	/**
	 * Get graph node by actor name array
	 * @param actor String array [last, first]
	 * @return bacon node representing actor
	 */
	public BaconNode getNode ( String[] actor ) {
		for(BaconNode v:graph.keySet())
			if(v.getName()[0] == actor[0] && v.getName()[1] == actor[1])
				return v;
		return null;
	}

}


text:
(function() {
  var App, Background, CanvasView, Data, DeviceRotation, View,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  this.rainOrNot = {};

  Data = (function() {
    function Data() {
      this.api = 'http://api.openweathermap.org/data/2.5/weather?q=Macao,MO';
      this.api = 'http://demo0670260.mockable.io/data/2.5/weather?sunny';
    }

    Data.prototype.fetch = function(callback) {
      return $.getJSON(this.api, function(data) {
        var code;
        console.log(data);
        code = data.weather[0].id + "";
        if (code[0] === '5') {
          return callback(true);
        } else {
          return callback(false);
        }
      });
    };

    return Data;

  })();

  DeviceRotation = (function() {
    function DeviceRotation() {
      DeviceRotation.a = DeviceRotation.b = DeviceRotation.g = 0;
      $(window).on('deviceorientation', function(e) {
        DeviceRotation.a = this.a = e.originalEvent.alpha;
        DeviceRotation.b = this.b = e.originalEvent.beta;
        DeviceRotation.g = this.g = e.originalEvent.gamma;
        return $('#debug').text("" + (parseInt(this.a * 1000) / 1000) + " " + (parseInt(this.b * 1000) / 1000) + " " + (parseInt(this.g * 1000) / 1000));
      });
    }

    return DeviceRotation;

  })();

  View = (function() {
    function View() {
      $('.status').hide();
      $('.description').hide();
      this.canvasView = new CanvasView();
      this.canvasView.reset();
      this.background = new Background();
    }

    View.prototype.update = function(is_rainy) {
      if (is_rainy == null) {
        is_rainy = true;
      }
      $('.loading').removeClass('loading');
      this.canvasView.moveIn();
      if (is_rainy) {
        $('.rainy-only').show();
        $('.sunny-only').hide();
        this.canvasView.showRainy();
        return this.background.setRainyBackground();
      } else {
        $('.rainy-only').hide();
        $('.sunny-only').show();
        this.canvasView.showSunny();
        return this.background.setSunnyBackground();
      }
    };

    return View;

  })();

  Background = (function() {
    function Background() {
      this.element = $('body');
    }

    Background.prototype.setSunnyBackground = function() {
      return this.element.addClass('sunny');
    };

    Background.prototype.setRainyBackground = function() {
      return this.element.addClass('rainy');
    };

    return Background;

  })();

  CanvasView = (function() {
    function CanvasView() {
      this.tick = __bind(this.tick, this);
      var cjs;
      cjs = createjs;
      this.canvas = document.getElementById("app-canvas");
      this.stage = new cjs.Stage(this.canvas);
      cjs.Ticker.setFPS(60);
      cjs.Ticker.addEventListener("tick", this.stage);
      cjs.Ticker.addEventListener("tick", this.tick);
      this.retinalize();
    }

    CanvasView.prototype.tick = function() {
      return this.applyDeviceRotation();
    };

    CanvasView.prototype.retinalize = function() {
      if (CanvasView.width == null) {
        CanvasView.width = this.canvas.width;
      }
      if (CanvasView.height == null) {
        CanvasView.height = this.canvas.height;
      }
      this.canvas.style.width = CanvasView.width + 'px';
      this.canvas.style.height = CanvasView.height + 'px';
      this.canvas.width = CanvasView.width * 2;
      this.canvas.height = CanvasView.height * 2;
      return this.stage.scaleX = this.stage.scaleY = 2;
    };

    CanvasView.prototype.applyDeviceRotation = function() {
      var a, b, g;
      a = DeviceRotation.a;
      b = DeviceRotation.b;
      g = DeviceRotation.g;
      this.icon.front.x = CanvasView.width / 2 + g / 10;
      this.icon.front.y = CanvasView.height / 2 + b / 10;
      this.icon.back.x = CanvasView.width / 2 + g / 5;
      return this.icon.back.y = CanvasView.height / 2 + b / 5;
    };

    CanvasView.prototype.moveIn = function() {
      return $(this.canvas).removeClass('out').addClass('in');
    };

    CanvasView.prototype.reset = function() {
      return $(this.canvas).removeClass().addClass('out');
    };

    CanvasView.prototype.showRainy = function() {
      this.icon = new lib.Rainy();
      return this.stage.addChild(this.icon);
    };

    CanvasView.prototype.showSunny = function() {
      this.icon = new lib.Sunny();
      return this.stage.addChild(this.icon);
    };

    return CanvasView;

  })();

  App = (function() {
    function App() {
      console.log("Do you need your umbrella today?");
      setTimeout((function(_this) {
        return function() {
          return _this.refresh();
        };
      })(this), 500);
      $('body').click((function(_this) {
        return function() {
          return _this.refresh();
        };
      })(this));
      new DeviceRotation();
    }

    App.prototype.refresh = function() {
      var data, view;
      data = new Data();
      view = new View();
      return data.fetch(function(is_rainy) {
        return view.update(is_rainy);
      });
    };

    return App;

  })();

  new App();

}).call(this);


text:
/**
 * @file os_int.h
 *
 * Ensure a consistent bit size
 */

#ifndef HEADER_OS_INT_H
#define HEADER_OS_INT_H

#ifdef __cplusplus
extern "C" {
#endif

#if defined(WIN32)
typedef UINT8 uint8_t;
typedef INT8 int8_t;
typedef UINT16 uint16_t;
typedef INT16 int16_t;
typedef UINT32 uint32_t;
typedef INT32 int32_t;
typedef UINT64 uint64_t;
typedef INT64 int64_t;
#else   /* Not Win32 */

#ifdef CONFIG_PLATFORM_SOLARIS
#include <inttypes.h>
#else
//#include <stdint.h>
#endif /* Not Solaris */

#endif /* Not Win32 */

#ifdef __cplusplus
}
#endif

#endif


text:
<bill session="111" type="h" number="509" updated="2009-03-07T10:47:30-05:00">
	<status><introduced date="1231909200" datetime="2009-01-14"/></status>

	<introduced date="1231909200" datetime="2009-01-14"/>
	<titles>
		<title type="short" as="introduced">Marine Turtle Conservation Reauthorization Act of 2009</title>
		<title type="official" as="introduced">To reauthorize the Marine Turtle Conservation Act of 2004.</title>
	</titles>
	<sponsor id="400049"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1231909200" datetime="2009-01-14"><text>Sponsor introductory remarks on measure. (CR E83)</text></action>
		<action date="1231909200" datetime="2009-01-14"><text>Referred to the House Committee on Natural Resources.</text></action>
		<action date="1233723600" datetime="2009-02-04"><text>Referred to the Subcommittee on Insular Affairs, Oceans and Wildlife.</text></action>
	</actions>
	<committees>
		<committee name="House Natural Resources" subcommittee="" activity="Referral, In Committee" />
		<committee name="House Natural Resources" subcommittee="Insular Affairs, Oceans and Wildlife" activity="Referral" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>
		<term name="Public lands and natural resources"/>
		<term name="Department of the Interior"/>
		<term name="Executive agency funding and structure"/>
		<term name="Foreign aid and international relief"/>
		<term name="International organizations and cooperation"/>
		<term name="Marine and coastal resources, fisheries"/>
		<term name="Reptiles"/>
		<term name="Wildlife conservation and habitat protection"/>
	</subjects>
	<amendments>

	</amendments>

	1/14/2009--Introduced.
Marine Turtle Conservation Reauthorization Act of 2009 - Reauthorizes the Marine Turtle Conservation Act of 2004 through FY2014.

</bill>


text:
using Core.Interfaces.Base;
using Core.Interfaces.Components.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Interfaces.Components
{
    public interface IWebHost : IRunnable, IComponent
    {
    }
}


text:
<?php

namespace Syndic\CommentBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SyndicCommentBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSCommentBundle';
    }
}


text:
using System;
using Couchbase.Linq.Filters;
using NUnit.Framework;

namespace Couchbase.Linq.UnitTests.Filters
{
    public class CollectionMetadataCacheTests
    {
        [Test]
        public void GetCollection_Annotated_AnnotationValues()
        {
            // Arrange

            var cache = new CollectionMetadataCache();

            // Act

            var (scope, collection) = cache.GetCollection<Annotated>();

            // Assert

            Assert.AreEqual("my_scope", scope);
            Assert.AreEqual("my_collection", collection);
        }

        [Test]
        public void GetCollection_Unannotated_DefaultValues()
        {
            // Arrange

            var cache = new CollectionMetadataCache();

            // Act

            var (scope, collection) = cache.GetCollection<Unannotated>();

            // Assert

            Assert.AreEqual("_default", scope);
            Assert.AreEqual("_default", collection);
        }

        #region Helpers

        [CouchbaseCollection("my_scope", "my_collection")]
        public class Annotated
        {
        }

        public class Unannotated
        {
        }

        #endregion
    }
}


text:
/*
//
// Select run-time part for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/

//
// Main part of SELECT procedure
//

yy.Select = function (params) { return yy.extend(this, params); }
yy.Select.prototype.toString = function() {
	var s;
	s = '';
	if (this.explain) {
		s += 'EXPLAIN ';
	}
	s += 'SELECT ';
	if (this.modifier) {
		s += this.modifier + ' ';
	}
	if (this.distinct) {
		s += 'DISTINCT ';
	}
	if (this.top) {
		s += 'TOP ' + this.top.value + ' ';
		if (this.percent) {
			s += 'PERCENT ';
		}
	}
	s += this.columns.map(function(col) {
		var s;
		s = col.toString();
		if (typeof col.as !== 'undefined') {
			s += ' AS ' + col.as;
		}
		return s;
	}).join(', ');
	if (this.from) {
		s += ' FROM ' + this.from.map(function(f) {
			var ss;
			ss = f.toString();
			if (f.as) {
				ss += ' AS ' + f.as;
			}
			return ss;
		}).join(',');
	}
	if (this.joins) {
		s += this.joins.map(function(jn) {
			var ss;
			ss = ' ';
			if (jn.joinmode) {
				ss += jn.joinmode + ' ';
			}
			if (jn.table) {
				ss += 'JOIN ' + jn.table.toString();
			} else if (jn.select) {
				ss += 'JOIN (' + jn.select.toString() + ')';
			} else if (jn instanceof alasql.yy.Apply) {
				ss += jn.toString();
			} else {
				throw new Error('Wrong type in JOIN mode');
			}
			if (jn.as) {
				ss += ' AS ' + jn.as;
			}
			if (jn.using) {
				ss += ' USING ' + jn.using.toString();
			}
			if (jn.on) {
				ss += ' ON ' + jn.on.toString();
			}
			return ss;
		});
	}
	if (this.where) {
		s += ' WHERE ' + this.where.toString();
	}
	if (this.group && this.group.length > 0) {
		s += ' GROUP BY ' + this.group.map(function(grp) {
			return grp.toString();
		}).join(', ');
	}
	if (this.having) {
		s += ' HAVING ' + this.having.toString();
	}
	if (this.order && this.order.length > 0) {
		s += ' ORDER BY ' + this.order.map(function(ord) {
			return ord.toString();
		}).join(', ');
	}
	if (this.limit) {
		s += ' LIMIT ' + this.limit.value;
	}
	if (this.offset) {
		s += ' OFFSET ' + this.offset.value;
	}
	if (this.union) {
		s += ' UNION ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.union.toString();
	}
	if (this.unionall) {
		s += ' UNION ALL ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.unionall.toString();
	}
	if (this.except) {
		s += ' EXCEPT ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.except.toString();
	}
	if (this.intersect) {
		s += ' INTERSECT ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.intersect.toString();
	}
	return s;
};

/**
 Select statement in expression
 */
yy.Select.prototype.toJS = function(context) {
//	console.log('Expression',this);
//	if(this.expression.reduced) return 'true';
//	return this.expression.toJS(context, tableid, defcols);
// console.log('Select.toJS', 81, this.queriesidx);
//	var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]';

	var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+'))[0]';

//	var s = '(ee=alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+')),console.log(999,ee),ee[0])';

	return s;
};

// Compile SELECT statement
yy.Select.prototype.compile = function(databaseid, params) {
	var db = alasql.databases[databaseid];
	// Create variable for query
	var query = new Query();

	// Array with columns to be removed
    query.removeKeys = [];
    query.aggrKeys = [];

	query.explain = this.explain; // Explain
	query.explaination = [];
	query.explid = 1;
//console.log(this.modifier);
	query.modifier = this.modifier;

	query.database = db;
	// 0. Precompile whereexists
	this.compileWhereExists(query);

	// 0. Precompile queries for IN, NOT IN, ANY and ALL operators
	this.compileQueries(query);

	query.defcols = this.compileDefCols(query, databaseid);

	// 1. Compile FROM clause
	query.fromfn = this.compileFrom(query);

	// 2. Compile JOIN clauses
	if(this.joins){
		this.compileJoins(query);
	}

	// todo?: 3. Compile SELECT clause

	// For ROWNUM()
	query.rownums = [];

	this.compileSelectGroup0(query);

	if(this.group || query.selectGroup.length>0) {
		query.selectgfns = this.compileSelectGroup1(query);
	} else {
		query.selectfns = this.compileSelect1(query, params);
	}

	// Remove columns clause
	this.compileRemoveColumns(query);

	// 5. Optimize WHERE and JOINS
	if(this.where){
		this.compileWhereJoins(query);
	}

	// 4. Compile WHERE clause
	query.wherefn = this.compileWhere(query);

	// 6. Compile GROUP BY
	if(this.group || query.selectGroup.length>0){
		query.groupfn = this.compileGroup(query);
	}

	// 6. Compile HAVING
	if(this.having){
		query.havingfn = this.compileHaving(query);
	}

	// 8. Compile ORDER BY clause
	if(this.order){
		query.orderfn = this.compileOrder(query);
	}

	if(this.group || query.selectGroup.length>0) {
		query.selectgfn = this.compileSelectGroup2(query);
	} else {
		query.selectfn = this.compileSelect2(query);
	}

	// 7. Compile DISTINCT, LIMIT and OFFSET
	query.distinct = this.distinct;

	// 9. Compile PIVOT clause
	if(this.pivot) query.pivotfn = this.compilePivot(query);
	if(this.unpivot) query.pivotfn = this.compileUnpivot(query);

	// 10. Compile TOP/LIMIT/OFFSET/FETCH cleuse
	if(this.top) {
		query.limit = this.top.value;
	} else if(this.limit) {
		query.limit = this.limit.value;
		if(this.offset) {
			query.offset = this.offset.value;
		}
	}

	query.percent = this.percent;

	// 9. Compile ordering function for UNION and UNIONALL
	query.corresponding = this.corresponding; // If CORRESPONDING flag exists
	if(this.union) {
		query.unionfn = this.union.compile(databaseid);
		if(this.union.order) {
			query.orderfn = this.union.compileOrder(query);
		} else {
			query.orderfn = null;
		}
	} else if(this.unionall) {
		query.unionallfn = this.unionall.compile(databaseid);
		if(this.unionall.order) {
			query.orderfn = this.unionall.compileOrder(query);
		} else {
			query.orderfn = null;
		}
	} else if(this.except) {
		query.exceptfn = this.except.compile(databaseid);
		if(this.except.order) {
			query.orderfn = this.except.compileOrder(query);
		} else {
			query.orderfn = null;
		}
	} else if(this.intersect) {
		query.intersectfn = this.intersect.compile(databaseid);
		if(this.intersect.order) {
			query.intersectfn = this.intersect.compileOrder(query);
		} else {
			query.orderfn = null;
		}
	}

	// SELECT INTO
	if(this.into) {
		if(this.into instanceof yy.Table) {
			//
			// Save into the table in database
			//
			if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) {
				// For external database when AUTOCOMMIT is ONs
				query.intoallfns = 'return alasql.engines["'+alasql.databases[this.into.databaseid||databaseid].engineid+'"]'+
					'.intoTable("'+(this.into.databaseid||databaseid)+'","'+this.into.tableid+'",this.data, columns, cb);';
			} else {
				// Into AlaSQL tables
				query.intofns =
				'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+
				'[\''+this.into.tableid+'\'].data.push(r);';
			}
		} else if(this.into instanceof yy.VarValue) {
			//
			// Save into local variable
			// SELECT * INTO @VAR1 FROM ?
			//
			query.intoallfns = 'alasql.vars["'+this.into.variable+'"]=this.data;res=this.data.length;if(cb)res=cb(res);return res;';
		} else if (this.into instanceof yy.FuncValue) {
			//
			// If this is INTO() function, then call it
			// with one or two parameters
			//
			var qs = 'return alasql.into[\''+this.into.funcid.toUpperCase()+'\'](';
			if(this.into.args && this.into.args.length>0 ) {
				qs += this.into.args[0].toJS()+',';
				if(this.into.args.length > 1) {
					qs += this.into.args[1].toJS()+',';
				} else {
					qs += 'undefined,';
				}
			} else {
				qs += 'undefined, undefined,'
			}
			query.intoallfns = qs+'this.data,columns,cb)';
//console.log('999');

		} else if (this.into instanceof yy.ParamValue) {
			//
			// Save data into parameters array
			// like alasql('SELECT * INTO ? FROM ?',[outdata,srcdata]);
			//
			query.intofns = "params['"+this.into.param+"'].push(r)";
		}

		if(query.intofns) {
			// Create intofn function
			query.intofn = new Function("r,i,params,alasql",'var y;'+query.intofns);
		} else if(query.intoallfns) {
			// Create intoallfn function
			query.intoallfn = new Function("columns,cb,params,alasql",'var y;'+query.intoallfns);
		}

	}
//console.log(query);

	// Now, compile all togeather into one function with query object in scope
	var statement = function(params, cb, oldscope) {
		query.params = params;
		var res1 = queryfn(query,oldscope,function(res){

//console.log(res[0].schoolid);
//console.log(184,res);
			if(query.rownums.length>0) {
				for(var i=0,ilen=res.length;i<ilen;i++) {
					for(var j=0,jlen=query.rownums.length;j<jlen;j++) {
						res[i][query.rownums[j]] = i+1;
					}
				}
			}

			var res2 = modify(query, res);

			if(cb){
				cb(res2);
			}
//console.log(8888,res2);
			return res2;

		});
//console.log(9999,res1);

//		if(typeof res1 != 'undefined') res1 =  modify(query,res1);

		return res1;

	};

//	statement.dbversion = ;
//	console.log(statement.query);
//console.log(202,statement);
	statement.query = query;
	return statement;
};

/**
	Modify res according modifier
	@function
	@param {object} query Query object
	@param res {object|number|string|boolean} res Data to be converted
*/
function modify(query, res) { // jshint ignore:line
//	console.log(arguments);

	/* If source is a primitive value then return it */
	if(		typeof res === 'undefined'
		|| 	typeof res === 'number'
		|| 	typeof res === 'string'
		|| 	typeof res == 'boolean'
	){
		return res;
	}

	var modifier = query.modifier || alasql.options.modifier;
	var columns = query.columns;
	if(typeof columns === 'undefined' || columns.length == 0) {
		// Try to create columns
		if(res.length > 0) {
			var allcol = {};
			for(var i=Math.min(res.length,alasql.options.columnlookup||10)-1;0<=i;i--) {
				for(var key in res[i]) {
					allcol[key] = true;
				}
			}

			columns = Object.keys(allcol).map(function(columnid){
				return {columnid:columnid};
			});
		} else {
			// Cannot recognize columns
			columns = [];
		}
	}

//	console.log(columns);

	if(modifier === 'VALUE') {
//		console.log(222,res);
		if(res.length > 0) {
			var key;
			if(columns && columns.length > 0){
				key = columns[0].columnid;
			} else {
				key = Object.keys(res[0])[0];
			}
			res = res[0][key];
		} else {
			res = undefined;
		}
	} else if(modifier === 'ROW') {
		if(res.length > 0) {
			var key;
			var a = [];
			for(var key in res[0]) {
				a.push(res[0][key]);
			}
			res = a;
		} else {
			res = undefined;
		}
	} else if(modifier === 'COLUMN') {
		var ar = [];
		if(res.length > 0) {
			var key;
			if(columns && columns.length > 0){
				key = columns[0].columnid;
			} else {
				key = Object.keys(res[0])[0];
			}

			for(var i=0, ilen=res.length; i<ilen; i++){
				ar.push(res[i][key]);
			}
		}
		res = ar;
	} else if(modifier === 'MATRIX') {
		// Returns square matrix of rows
		var ar = [];
		for(var i=0;i<res.length;i++) {
			var a = [];
			var r = res[i];
			for(var j=0;j<columns.length;j++) {
				a.push(r[columns[j].columnid]);
			}
			ar.push(a);
		}
		res = ar;

	}else if(modifier === 'INDEX') {
		var ar = {};
		var key,val;
		if(columns && columns.length > 0) {
			key = columns[0].columnid;
			val = columns[1].columnid;
		} else {
			var okeys = Object.keys(res[0]);
			key = okeys[0];
			val = okeys[1];
		}
		for(var i=0, ilen=res.length; i<ilen; i++){
			ar[res[i][key]] = res[i][val];
		}
		res = ar;
//		res = arrayOfArrays(res);
	}else if(modifier === 'RECORDSET') {
		res = new alasql.Recordset({columns:columns, data:res});
//		res = arrayOfArrays(res);
	}else if(modifier === 'TEXTSTRING') {
		var key;
		if(columns && columns.length > 0){
			key = columns[0].columnid;
		} else{
			key = Object.keys(res[0])[0];
		}

		for(var i=0, ilen=res.length; i<ilen; i++){
			res[i] = res[i][key];
		}
		res = res.join('\n');
//		res = arrayOfArrays(res);
	}
	return res;
}

//  yy.Select.prototype.exec = function(databaseid) {
// 	throw new Error('Select statement should be precompiled');

//  };
yy.Select.prototype.execute = function (databaseid, params, cb) {
	return this.compile(databaseid)(params,cb);
//	throw new Error('Insert statement is should be compiled')
}