text:
package com.tokbox.sample.advancedaudiodriver;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder.AudioSource;
import android.media.audiofx.AcousticEchoCanceler;
import android.media.audiofx.NoiseSuppressor;
import android.os.Build;
import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.opentok.android.BaseAudioDevice;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class AdvancedAudioDevice extends BaseAudioDevice {
    private final static String TAG =  AdvancedAudioDevice.class.getSimpleName();

    private static final int NUM_CHANNELS_CAPTURING = 1;
    private static final int NUM_CHANNELS_RENDERING = 1;
    private static final int STEREO_CHANNELS = 2;
    private static final int DEFAULT_SAMPLE_RATE = 44100;
    private static final int SAMPLE_SIZE_IN_BYTES = 2;
    private static final int DEFAULT_SAMPLES_PER_BUFFER = (DEFAULT_SAMPLE_RATE / 1000) * 10; // 10ms
    private static final int DEFAULT_BUFFER_SIZE =
        SAMPLE_SIZE_IN_BYTES * DEFAULT_SAMPLES_PER_BUFFER * STEREO_CHANNELS;
    // Max 10 ms @ 48 kHz - Stereo
    private static final int DEFAULT_START_RENDERER_AND_CAPTURER_DELAY = 5 * 1000;
    private static final int DEFAULT_BLUETOOTH_SCO_START_DELAY = 2000;

    private Context context;

    private AudioTrack audioTrack;
    private AudioRecord audioRecord;

    // Capture & render buffers
    private ByteBuffer playBuffer;
    private ByteBuffer recBuffer;
    private byte[] tempBufPlay;
    private byte[] tempBufRec;

    private final ReentrantLock rendererLock = new ReentrantLock(true);
    private final Condition renderEvent = rendererLock.newCondition();
    private volatile boolean isRendering = false;
    private volatile boolean shutdownRenderThread = false;

    private final ReentrantLock captureLock = new ReentrantLock(true);
    private final Condition captureEvent = captureLock.newCondition();
    private volatile boolean isCapturing = false;
    private volatile boolean shutdownCaptureThread = false;

    private AudioSettings captureSettings;
    private AudioSettings rendererSettings;
    private NoiseSuppressor noiseSuppressor;
    private AcousticEchoCanceler echoCanceler;

    // Capturing delay estimation
    private int estimatedCaptureDelay = 0;

    // Rendering delay estimation
    private int bufferedPlaySamples = 0;
    private int playPosition = 0;
    private int estimatedRenderDelay = 0;

    private AudioManager audioManager;
    private AudioManagerMode audioManagerMode = new AudioManagerMode();

    private int outputSamplingRate = DEFAULT_SAMPLE_RATE;
    private int captureSamplingRate = DEFAULT_SAMPLE_RATE;
    private int samplesPerBuffer = DEFAULT_SAMPLES_PER_BUFFER;

    // For headset receiver.
    private static final String HEADSET_PLUG_STATE_KEY = "state";

    private BluetoothState bluetoothState;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothProfile bluetoothProfile;
    private final Object bluetoothLock = new Object();
    private TelephonyManager telephonyManager;

    private boolean isPaused;

    private enum OutputType {
        SPEAKER_PHONE,
        EAR_PIECE,
        HEAD_PHONES,
        BLUETOOTH
    }

    private OutputType audioOutputType = OutputType.SPEAKER_PHONE;

    private OutputType getOutputType() {
        return audioOutputType;
    }

    private void setOutputType(OutputType type) {
        audioOutputType = type;
    }

    private static class AudioManagerMode {
        private int oldMode;
        private int naquire;

        AudioManagerMode() {
            oldMode = 0;
            naquire = 0;
        }

        void acquireMode(AudioManager audioManager) {
            if (0 == naquire++) {
                oldMode = audioManager.getMode();
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            }
        }

        void releaseMode(AudioManager audioManager) {
            if (0 == --naquire) {
                audioManager.setMode(oldMode);
            }
        }
    }

    private static class AudioState {
        private int lastStreamVolume = 0;
        private int lastKnownFocusState = 0;
        private OutputType lastOutputType = OutputType.SPEAKER_PHONE;

        int getLastStreamVolume() {
            return lastStreamVolume;
        }

        void setLastStreamVolume(int lastStreamVolume) {
            this.lastStreamVolume = lastStreamVolume;
        }

        int getLastKnownFocusState() {
            return lastKnownFocusState;
        }

        void setLastKnownFocusState(int lastKnownFocusState) {
            this.lastKnownFocusState = lastKnownFocusState;
        }

        OutputType getLastOutputType() {
            return this.lastOutputType;
        }

        void setLastOutputType(OutputType lastOutputType) {
            this.lastOutputType = lastOutputType;
        }

    }

    private AudioState audioState = new AudioState();

    private BroadcastReceiver headsetBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "headsetBroadcastReceiver.onReceive()");
            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.getIntExtra(HEADSET_PLUG_STATE_KEY, 0) == 1) {
                    Log.d(TAG, "headsetBroadcastReceiver.onReceive():  Headphones connected");
                    audioState.setLastOutputType(getOutputType());
                    setOutputType(OutputType.HEAD_PHONES);
                    audioManager.setSpeakerphoneOn(false);
                    audioManager.setBluetoothScoOn(false);
                } else {
                    Log.d(TAG, "headsetBroadcastReceiver.onReceive():  Headphones disconnected");
                    if (getOutputType() == OutputType.HEAD_PHONES) {
                        if (audioState.getLastOutputType() == OutputType.BLUETOOTH &&
                                BluetoothState.Connected == bluetoothState) {
                            audioManager.setBluetoothScoOn(true);
                            startBluetoothSco();
                            setOutputType(OutputType.BLUETOOTH);
                        } else {
                            if (audioState.getLastOutputType() == OutputType.SPEAKER_PHONE) {
                                setOutputType(OutputType.SPEAKER_PHONE);
                                audioManager.setSpeakerphoneOn(true);
                            }
                            if (audioState.getLastOutputType() == OutputType.EAR_PIECE) {
                                setOutputType(OutputType.EAR_PIECE);
                                audioManager.setSpeakerphoneOn(false);
                            }
                        }
                    }
                }
            }
        }
    };

    // Intent broadcast receiver which handles changes in Bluetooth device availability.
    // Detects headset changes and Bluetooth SCO state changes.
    private final BroadcastReceiver bluetoothHeadsetReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
                final int state = intent.getIntExtra(
                        BluetoothHeadset.EXTRA_STATE, -1);
                switch (state) {
                    case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
                        Log.d(TAG, "bluetoothHeadsetReceiver.onReceive(): STATE_AUDIO_DISCONNECTED");
                        break;

                    case BluetoothHeadset.STATE_AUDIO_CONNECTING:
                        Log.d(TAG, "bluetoothHeadsetReceiver.onReceive(): STATE_AUDIO_CONNECTING");
                        break;

                    case BluetoothHeadset.STATE_AUDIO_CONNECTED:
                        Log.d(TAG, "bluetoothHeadsetReceiver.onReceive(): STATE_AUDIO_CONNECTED");
                        break;

                    default:
                        break;
                }
            }
        }
    };

    private void restoreAudioAfterBluetoothDisconnect() {
        if (audioManager.isWiredHeadsetOn()) {
            setOutputType(OutputType.HEAD_PHONES);
            audioManager.setSpeakerphoneOn(false);
        } else {
            if (audioState.getLastOutputType() == OutputType.SPEAKER_PHONE) {
                setOutputType(OutputType.SPEAKER_PHONE);
                super.setOutputMode(OutputMode.SpeakerPhone);
                audioManager.setSpeakerphoneOn(true);
            } else if (audioState.getLastOutputType() == OutputType.EAR_PIECE) {
                setOutputType(OutputType.EAR_PIECE);
                super.setOutputMode(OutputMode.Handset);
                audioManager.setSpeakerphoneOn(false);
            }
        }
    }

    private final BroadcastReceiver bluetoothBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (null != action && action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
                int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, -1);
                switch (state) {
                    case BluetoothHeadset.STATE_CONNECTED:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): BluetoothHeadset.STATE_CONNECTED");
                        new Handler().postDelayed(() -> connectBluetooth(), DEFAULT_BLUETOOTH_SCO_START_DELAY);
                        break;
                    case BluetoothHeadset.STATE_DISCONNECTING:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): BluetoothHeadset.STATE_DISCONNECTING");
                        break;
                    case BluetoothHeadset.STATE_DISCONNECTED:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): BluetoothHeadset.STATE_DISCONNECTED");
                        stopBluetoothSco();
                        audioManager.setBluetoothScoOn(false);
                        break;
                    default:
                        break;
                }
            } else if (null != action && action.equals(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED)) {
                int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
                switch (state) {
                    case AudioManager.SCO_AUDIO_STATE_CONNECTED:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_CONNECTED");
                        bluetoothState = BluetoothState.Connected;
                        setOutputType(OutputType.BLUETOOTH);
                        AdvancedAudioDevice.super.setOutputMode(OutputMode.Handset); // When BT is connected it replaces the handset
                        break;
                    case AudioManager.SCO_AUDIO_STATE_ERROR:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_ERROR");
                        break;
                    case AudioManager.SCO_AUDIO_STATE_DISCONNECTED:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_DISCONNECTED");
                        restoreAudioAfterBluetoothDisconnect();
                        bluetoothState = BluetoothState.Disconnected;
                        break;
                    case AudioManager.SCO_AUDIO_STATE_CONNECTING:
                        Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_CONNECTING");
                        break;
                    default:
                        break;
                }
            }
        }
    };
    private PhoneStateListener phoneStateListener = new PhoneStateListener(){
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            Log.d(TAG, "PhoneStateListener.onCallStateChanged()");

            super.onCallStateChanged(state, incomingNumber);
            switch (state) {

                case TelephonyManager.CALL_STATE_IDLE:
                    //Initial state
                    Log.d(TAG, "PhoneStateListener.onCallStateChanged(): TelephonyManager.CALL_STATE_IDLE");
                    // We delay a bit here the action of start capturing and rendering again because Android has to
                    // finish routing audio to the earpiece. It is an Android behaviour we have to deal with.
                    new Handler().postDelayed(() -> startRendererAndCapturer(), DEFAULT_START_RENDERER_AND_CAPTURER_DELAY);
                    break;

                case TelephonyManager.CALL_STATE_RINGING:
                    // Incoming call Ringing
                    Log.d(TAG, "PhoneStateListener.onCallStateChanged(): TelephonyManager.CALL_STATE_RINGING");
                    stopRendererAndCapturer();
                    break;

                case TelephonyManager.CALL_STATE_OFFHOOK:
                    // Outgoing Call | Accepted incoming call
                    Log.d(TAG, "PhoneStateListener.onCallStateChanged(): TelephonyManager.CALL_STATE_OFFHOOK");
                    stopRendererAndCapturer();
                    break;

                default:
                    Log.d(TAG, "PhoneStateListener.onCallStateChanged() default");
                    break;
            }
        }
    };

    private boolean wasRendering;
    private boolean wasCapturing;

    private void startRendererAndCapturer() {
        if (wasRendering) {
            startRenderer();
        }

        if (wasCapturing) {
            startCapturer();
        }
    }

    private void stopRendererAndCapturer() {
        if (isRendering) {
            stopRenderer();
            wasRendering = true;
        }

        if (isCapturing) {
            stopCapturer();
            wasCapturing = true;
        }
    }

    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + ")");
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): ");
                    //Check if coming back from a complete loss or a transient loss
                    switch (audioState.getLastKnownFocusState()) {
                        case AudioManager.AUDIOFOCUS_LOSS:
                            break;
                        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                            break;
                        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                                audioState.getLastStreamVolume(), 0);
                            break;
                        default:
                            Log.d(TAG, "focusChange = " + focusChange);
                            break;
                    }
                    setOutputType(audioState.getLastOutputType());
                    connectBluetooth();
                    forceInvokeConnectBluetooth();
                    break;

                case AudioManager.AUDIOFOCUS_LOSS:
                    // -1 Loss for indefinite time
                    Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_LOSS");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    // -2 Loss for short duration
                    Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_LOSS_TRANSIENT");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    // -3 stay quite in background
                    Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                    audioState.setLastStreamVolume(audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL));
                    audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 0, 0);
                    break;
                case AudioManager.AUDIOFOCUS_NONE:
                    Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_NONE");
                    break;
                default:
                    Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): default");
                    break;
            }
            audioState.setLastOutputType(getOutputType());
            audioState.setLastKnownFocusState(focusChange);
        }
    };

    private void connectBluetooth() {
        Log.d(TAG, "connectBluetooth() called");
        audioManager.setBluetoothScoOn(true);
        startBluetoothSco();
    }

    public AdvancedAudioDevice(Context context) {
        this.context = context;

        try {
            recBuffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        tempBufRec = new byte[DEFAULT_BUFFER_SIZE];

        audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothProfile = null;

        int outputBufferSize = DEFAULT_BUFFER_SIZE;

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            try {
                outputSamplingRate = Integer.parseInt(
                        audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
            } finally {
                if (outputSamplingRate == 0) {
                    outputSamplingRate = DEFAULT_SAMPLE_RATE;
                }
            }
            try {
                samplesPerBuffer = Integer.parseInt(
                        audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
                outputBufferSize = SAMPLE_SIZE_IN_BYTES
                    * samplesPerBuffer
                    * NUM_CHANNELS_RENDERING;
            } catch(NumberFormatException numberFormatException) {
                Log.e(TAG, "DefaultAudioDevice(): " + numberFormatException.getMessage());
            } finally {
                if (outputBufferSize == 0) {
                    outputBufferSize = DEFAULT_BUFFER_SIZE;
                    samplesPerBuffer = DEFAULT_SAMPLES_PER_BUFFER;
                }
            }
        }

        try {
            playBuffer = ByteBuffer.allocateDirect(outputBufferSize);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        tempBufPlay = new byte[outputBufferSize];

        captureSettings = new AudioSettings(captureSamplingRate, NUM_CHANNELS_CAPTURING);
        rendererSettings = new AudioSettings(outputSamplingRate, NUM_CHANNELS_RENDERING);

        try {
            telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        isPhoneStateListenerRegistered = false;
        wasCapturing = false;
        wasRendering = false;
        isPaused = false;
        Log.d(TAG, "DefaultAudioDevice() exit  " + this);

    }

    @Override
    public boolean initCapturer() {
        // get the minimum buffer size that can be used
        int minRecBufSize = AudioRecord.getMinBufferSize(
            captureSettings.getSampleRate(),
            NUM_CHANNELS_CAPTURING == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO,
            AudioFormat.ENCODING_PCM_16BIT
        );

        // double size to be more safe
        int recBufSize = minRecBufSize * 2;

        // release the object
        if (noiseSuppressor != null) {
            noiseSuppressor.release();
            noiseSuppressor = null;
        }

        if (echoCanceler != null) {
            echoCanceler.release();
            echoCanceler = null;
        }

        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }

        try {
            int channelConfig = NUM_CHANNELS_CAPTURING == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;

            audioRecord = new AudioRecord(
                    AudioSource.VOICE_COMMUNICATION,
                    captureSettings.getSampleRate(),
                    channelConfig,
                    AudioFormat.ENCODING_PCM_16BIT, recBufSize);

            if (NoiseSuppressor.isAvailable()) {
                noiseSuppressor = NoiseSuppressor.create(audioRecord.getAudioSessionId());
            }

            if (AcousticEchoCanceler.isAvailable()) {
                echoCanceler = AcousticEchoCanceler.create(audioRecord.getAudioSessionId());
            }

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        // Check that the audioRecord is ready to be used.
        if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
            String errorDescription = String.format(Locale.getDefault(), "Audio capture could not be initialized.\n" +
                            "Requested parameters\n" +
                            "  Sampling Rate: %d\n" +
                            "  Number of channels: %d\n" +
                            "  Buffer size: %d\n",
                    captureSettings.getSampleRate(),
                    captureSettings.getNumChannels(),
                    minRecBufSize);
            Log.e(TAG, errorDescription);
            throw new RuntimeException(errorDescription);
        }

        registerPhoneStateListener();

        shutdownCaptureThread = false;
        new Thread(captureThread).start();
        return true;
    }

    @Override
    public boolean destroyCapturer() {
        captureLock.lock();

        // release the object
        if (null != echoCanceler) {
            echoCanceler.release();
            echoCanceler = null;
        }

        if (null != noiseSuppressor) {
            noiseSuppressor.release();
            noiseSuppressor = null;
        }

        audioRecord.release();
        audioRecord = null;
        shutdownCaptureThread = true;
        captureEvent.signal();

        captureLock.unlock();

        unRegisterPhoneStateListener();
        wasCapturing = false;
        return true;
    }

    public int getEstimatedCaptureDelay() {
        return estimatedCaptureDelay;
    }

    @Override
    public boolean startCapturer() {
        if (audioRecord == null) {
            throw new IllegalStateException("startCapturer(): startRecording() called on an "
                    + "uninitialized AudioRecord");
        }
        try {
            audioRecord.startRecording();

        } catch (IllegalStateException e) {
            throw new RuntimeException(e.getMessage());
        }

        captureLock.lock();
        isCapturing = true;
        captureEvent.signal();
        captureLock.unlock();
        return true;
    }

    @Override
    public boolean stopCapturer() {

        if (audioRecord == null) {
            throw new IllegalStateException("stopCapturer(): stop() called on an uninitialized AudioRecord");
        }
        captureLock.lock();
        try {
            // Only stop if we are recording.
            if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
                audioRecord.stop();
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            // Ensure we always unlock
            isCapturing = false;
            captureLock.unlock();
        }
        return true;
    }

    private Runnable captureThread = () -> {
        int samplesToRec = captureSamplingRate / 100;
        int samplesRead;

        try {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
        } catch (Exception e) {
            Log.e(TAG, "android.os.Process.setThreadPriority(): " + e.getMessage());
        }

        while (!shutdownCaptureThread) {
            captureLock.lock();
            try {
                if (!this.isCapturing) {
                    captureEvent.await();
                    continue;
                } else {
                    if (audioRecord == null) {
                        continue;
                    }
                    int lengthInBytes = (samplesToRec << 1) * NUM_CHANNELS_CAPTURING;
                    int readBytes = audioRecord.read(tempBufRec, 0, lengthInBytes);
                    if (readBytes >= 0) {
                        recBuffer.rewind();
                        recBuffer.put(tempBufRec);
                        samplesRead = (readBytes >> 1) / NUM_CHANNELS_CAPTURING;
                    } else {
                        switch (readBytes) {
                            case AudioRecord.ERROR_BAD_VALUE:
                                throw new RuntimeException("captureThread(): AudioRecord.ERROR_BAD_VALUE");
                            case AudioRecord.ERROR_INVALID_OPERATION:
                                throw new RuntimeException("captureThread(): AudioRecord.ERROR_INVALID_OPERATION");
                            case AudioRecord.ERROR:
                            default:
                                throw new RuntimeException("captureThread(): AudioRecord.ERROR or default");
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                // Ensure we always unlock
                captureLock.unlock();
            }
            getAudioBus().writeCaptureData(recBuffer, samplesRead);
            estimatedCaptureDelay = samplesRead * 1000 / captureSamplingRate;
        }
    };

    @Override
    public boolean initRenderer() {

        // Request audio focus for playback
        int result = audioManager.requestAudioFocus(audioFocusChangeListener,
            // Use the music stream.
            AudioManager.STREAM_VOICE_CALL,
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            Log.d("AUDIO_FOCUS", "Audio Focus request GRANTED !");
        } else {
            Log.e("AUDIO_FOCUS", "Audio Focus request DENIED !");
            return false;
        }

        // initalize default values
        bluetoothState = BluetoothState.Disconnected;
        /* register for bluetooth sco callbacks and attempt to enable it */
        enableBluetoothEvents();
        // get the minimum buffer size that can be used
        int minPlayBufSize = AudioTrack.getMinBufferSize(
            rendererSettings.getSampleRate(),
            NUM_CHANNELS_RENDERING == 1 ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO,
            AudioFormat.ENCODING_PCM_16BIT
        );

        // release the object
        if (audioTrack != null) {
            audioTrack.release();
            audioTrack = null;
        }

        try {
            int channelConfig = (NUM_CHANNELS_RENDERING == 1) ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO;

            audioTrack = new AudioTrack(
                    AudioManager.STREAM_VOICE_CALL,
                    rendererSettings.getSampleRate(),
                    channelConfig,
                    AudioFormat.ENCODING_PCM_16BIT,
                    minPlayBufSize >= 6000 ? minPlayBufSize : minPlayBufSize * 2,
                    AudioTrack.MODE_STREAM
            );
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        // Check that the audioRecord is ready to be used.
        if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
            throw new RuntimeException("Audio renderer not initialized " + rendererSettings.getSampleRate());
        }

        bufferedPlaySamples = 0;

        registerPhoneStateListener();

        shutdownRenderThread = false;
        new Thread(renderThread).start();
        return true;
    }

    private void destroyAudioTrack() {
        rendererLock.lock();
        audioTrack.release();
        audioTrack = null;
        shutdownRenderThread = true;
        renderEvent.signal();
        rendererLock.unlock();
    }

    @Override
    public boolean destroyRenderer() {
        destroyAudioTrack();
        disableBluetoothEvents();
        unregisterHeadsetReceiver();
        audioManager.setSpeakerphoneOn(false);
        audioManager.abandonAudioFocus(audioFocusChangeListener);

        unRegisterPhoneStateListener();
        wasRendering = false;
        return true;
    }

    public int getEstimatedRenderDelay() {
        return estimatedRenderDelay;
    }

    @Override
    public boolean startRenderer() {
        Log.d("AUDIO_FOCUS", "Start Renderer");

        // Enable speakerphone unless headset is connected.
        synchronized (bluetoothLock) {
            if (BluetoothState.Connected != bluetoothState) {
                if (audioManager.isWiredHeadsetOn()) {
                    Log.d(TAG, "Turn off Speaker phone");
                    audioManager.setSpeakerphoneOn(false);
                } else {
                    Log.d(TAG, "Turn on Speaker phone");
                    if (getOutputType() == OutputType.SPEAKER_PHONE) {
                        audioManager.setSpeakerphoneOn(true);
                    }
                }
            }
        }

        // Start playout.
        if (audioTrack == null) {
            throw new IllegalStateException("startRenderer(): play() called on uninitialized AudioTrack");
        }
        try {
            audioTrack.play();
        } catch (IllegalStateException e) {
            throw new RuntimeException(e.getMessage());
        }

        rendererLock.lock();
        isRendering = true;
        renderEvent.signal();
        rendererLock.unlock();
        registerBtReceiver();
        registerHeadsetReceiver();
        return true;
    }

    @Override
    public boolean stopRenderer() {
        Log.d("AUDIO_FOCUS", "Stop Renderer");

        if (audioTrack == null) {
            throw new IllegalStateException("stopRenderer(): stop() called on uninitialized AudioTrack");
        }

        rendererLock.lock();

        try {
            // Only stop if we are playing.
            if (audioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
                audioTrack.stop();

            }
            audioTrack.flush();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            isRendering = false;
            rendererLock.unlock();
        }
        audioManagerMode.releaseMode(audioManager);

        unregisterHeadsetReceiver();
        unregisterBtReceiver();
        return true;
    }

    private Runnable renderThread = () -> {
        int samplesToPlay = samplesPerBuffer;
        try {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
        } catch (Exception e) {
            Log.e(TAG, "android.os.Process.setThreadPriority(): " + e.getMessage());
        }

        while (!shutdownRenderThread) {
            rendererLock.lock();
            try {
                if (!this.isRendering) {
                    renderEvent.await();
                    continue;

                } else {
                    rendererLock.unlock();

                    // Don't lock on audioBus calls
                    playBuffer.clear();
                    int samplesRead = getAudioBus().readRenderData(playBuffer, samplesToPlay);

                    rendererLock.lock();

                    // After acquiring the lock again we must check if we are still playing
                    if (audioTrack == null || !this.isRendering) {
                        continue;
                    }

                    int bytesRead = (samplesRead << 1) * NUM_CHANNELS_RENDERING;
                    playBuffer.get(tempBufPlay, 0, bytesRead);

                    int bytesWritten = audioTrack.write(tempBufPlay, 0, bytesRead);

                    if (bytesWritten > 0) {
                        // increase by number of written samples
                        bufferedPlaySamples += (bytesWritten >> 1) / NUM_CHANNELS_RENDERING;

                        // decrease by number of played samples
                        int pos = audioTrack.getPlaybackHeadPosition();

                        if (pos < playPosition) {
                            // wrap or reset by driver
                            playPosition = 0;
                        }

                        bufferedPlaySamples -= (pos - playPosition);
                        playPosition = pos;

                        // we calculate the estimated delay based on the buffered samples
                        estimatedRenderDelay = bufferedPlaySamples * 1000 / outputSamplingRate;
                    } else {
                        switch (bytesWritten) {
                            case AudioTrack.ERROR_BAD_VALUE:
                                throw new RuntimeException("renderThread(): AudioTrack.ERROR_BAD_VALUE");
                            case AudioTrack.ERROR_INVALID_OPERATION:
                                throw new RuntimeException("renderThread(): AudioTrack.ERROR_INVALID_OPERATION");
                            case AudioTrack.ERROR:
                            default:
                                throw new RuntimeException(
                                        "renderThread(): AudioTrack.ERROR or default");
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                rendererLock.unlock();
            }
        }
    };

    @Override
    public AudioSettings getCaptureSettings() {
        return this.captureSettings;
    }

    @Override
    public AudioSettings getRenderSettings() {
        return this.rendererSettings;
    }

    /*
     * Communication modes handling.
     */
    public boolean setOutputMode(OutputMode mode) {
        //This is public API and also called during initialization
        Log.d("AUDIO_FOCUS", "outputmode set to : " + mode);
        super.setOutputMode(mode);

        if(OutputMode.SpeakerPhone == mode) {
            audioState.setLastOutputType(getOutputType());
            setOutputType(OutputType.SPEAKER_PHONE);
            audioManager.setSpeakerphoneOn(true);
            stopBluetoothSco();
            audioManager.setBluetoothScoOn(false);
        } else {
            if (audioState.getLastOutputType() == OutputType.BLUETOOTH || bluetoothState == BluetoothState.Connected) {
                connectBluetooth();
            } else {
                audioState.setLastOutputType(getOutputType());
                audioManager.setSpeakerphoneOn(false);
                setOutputType(OutputType.EAR_PIECE);
                stopBluetoothSco();
                audioManager.setBluetoothScoOn(false);
            }
        }

        return true;
    }

    private boolean isHeadsetReceiverRegistered;

    private void registerHeadsetReceiver() {
        Log.d(TAG, "registerHeadsetReceiver() called ... isHeadsetReceiverRegistered = " + isHeadsetReceiverRegistered);

        if (isHeadsetReceiverRegistered) {
            return;
        }

        context.registerReceiver(headsetBroadcastReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
        isHeadsetReceiverRegistered = true;
    }

    private void unregisterHeadsetReceiver() {
        Log.d(TAG, "unregisterHeadsetReceiver() called .. isHeadsetReceiverRegistered = " + isHeadsetReceiverRegistered);

        if (!isHeadsetReceiverRegistered) {
            return;
        }

        context.unregisterReceiver(headsetBroadcastReceiver);
        isHeadsetReceiverRegistered = false;
    }

    private boolean isBluetoothHeadSetReceiverRegistered;

    private void registerBtReceiver() {
        Log.d(TAG, "registerBtReceiver() called .. isBluetoothHeadSetReceiverRegistered = " + isBluetoothHeadSetReceiverRegistered);

        if (isBluetoothHeadSetReceiverRegistered) {
            return;
        }

        IntentFilter btFilter =  new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        btFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        context.registerReceiver(bluetoothBroadcastReceiver, btFilter);

        // Register receiver for change in audio connection state of the Headset profile.
        context.registerReceiver(bluetoothHeadsetReceiver, new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED));

        isBluetoothHeadSetReceiverRegistered = true;
    }

    private void unregisterBtReceiver() {
        Log.d(TAG, "unregisterBtReceiver() called .. bluetoothHeadSetReceiverRegistered = " + isBluetoothHeadSetReceiverRegistered);

        if (!isBluetoothHeadSetReceiverRegistered) {
            return;
        }

        context.unregisterReceiver(bluetoothBroadcastReceiver);
        context.unregisterReceiver(bluetoothHeadsetReceiver);
        isBluetoothHeadSetReceiverRegistered = false;
    }

    private boolean isPhoneStateListenerRegistered;

    //Phone state permissions are required to from Api 31. Adding this check to avoid crash.
    private boolean hasPhoneStatePermission() {
        if (Build.VERSION.SDK_INT >= 31) {
            if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "Some features may not be available unless the phone permissions has been granted explicitly " +
                        "in the App settings.");
                return false;
            }
        }
        return true;
    }

    private void registerPhoneStateListener() {
        Log.d(TAG, "registerPhoneStateListener() called");

        if (isPhoneStateListenerRegistered) {
            return;
        }

        if (!hasPhoneStatePermission()) {
            Log.e(TAG, "No Phone State permissions. Register phoneStateListener cannot " +
                    "be completed.");
            return;
        }

        if (telephonyManager != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
            isPhoneStateListenerRegistered = true;
        }
    }

    private void unRegisterPhoneStateListener() {
        Log.d(TAG, "unRegisterPhoneStateListener() called");

        if (!isPhoneStateListenerRegistered) {
            return;
        }

        if (!hasPhoneStatePermission()) {
            Log.e(TAG, "No Phone State permissions. Register phoneStateListener cannot " +
                    "be completed.");
            return;
        }

        if (telephonyManager != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            isPhoneStateListenerRegistered = false;
        }
    }

    @Override
    public synchronized void onPause() {
        audioState.setLastOutputType(getOutputType());
        unregisterBtReceiver();
        unregisterHeadsetReceiver();
        isPaused = true;
    }

    @Override
    public synchronized void onResume() {
        Log.d(TAG, "onResume() called");
        if (!isPaused) {
            return;
        }

        if (bluetoothState == BluetoothState.Disconnected) {
            if (isRendering && (audioState.getLastOutputType() == OutputType.SPEAKER_PHONE)) {
                if (!audioManager.isWiredHeadsetOn()) {
                    Log.d(TAG, "onResume() - Set Speaker Phone ON True");
                    audioManager.setSpeakerphoneOn(true);
                }
            }
        }

        /* register handler for phonejack notifications */
        registerBtReceiver();
        registerHeadsetReceiver();
        connectBluetooth();
        forceInvokeConnectBluetooth();

        isPaused = false;
    }

    @Override
    public BluetoothState getBluetoothState() {
        return bluetoothState;
    }

    private void enableBluetoothEvents() {
        if (audioManager.isBluetoothScoAvailableOffCall()) {
            registerBtReceiver();
            connectBluetooth();
        }

    }

    private void disableBluetoothEvents() {
        if (null != bluetoothProfile && bluetoothAdapter != null) {
            bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothProfile);
        }

        unregisterBtReceiver();

        // Force a shutdown of bluetooth: when a call comes in, the handler is not invoked by system.
        Intent intent = new Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        intent.putExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED);
        bluetoothBroadcastReceiver.onReceive(context, intent);
    }

    private void startBluetoothSco() {
        try {
            audioManager.startBluetoothSco();
        } catch (NullPointerException e) {
            Log.d(TAG, e.getMessage());
        }
    }

    private void stopBluetoothSco() {
        try {
            audioManager.stopBluetoothSco();
        } catch (NullPointerException e) {
            Log.d(TAG, e.getMessage());
        }
    }

    private final BluetoothProfile.ServiceListener bluetoothProfileServiceListener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int type, BluetoothProfile profile) {
            Log.d(TAG, "BluetoothProfile.ServiceListener.onServiceConnected()");
            if (BluetoothProfile.HEADSET == type) {
                bluetoothProfile = profile;
                List<BluetoothDevice> devices = profile.getConnectedDevices();

                Log.d(TAG, "Service Proxy Connected");

                if (!devices.isEmpty() &&
                        BluetoothHeadset.STATE_CONNECTED == profile.getConnectionState(devices.get(0))) {
                    // Force a init of bluetooth: the handler will not send a connected event if a
                    // device is already connected at the time of proxy connection request.
                    Intent intent = new Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
                    intent.putExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_CONNECTED);
                    bluetoothBroadcastReceiver.onReceive(context, intent);
                }
            }
        }

        @Override
        public void onServiceDisconnected(int type) {
            Log.d(TAG, "BluetoothProfile.ServiceListener.onServiceDisconnected()");
        }
    };

    private void forceInvokeConnectBluetooth() {
        Log.d(TAG, "forceConnectBluetooth() called");

        // Force reconnection of bluetooth in the event of a phone call.
        synchronized (bluetoothLock) {
            bluetoothState = BluetoothState.Disconnected;
            if (bluetoothAdapter != null) {
                bluetoothAdapter.getProfileProxy(
                        context,
                        bluetoothProfileServiceListener,
                        BluetoothProfile.HEADSET
                );
            }
        }
    }
}


text:
package org.apache.spark.sql.catalyst

import java.io._
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.atomic.AtomicBoolean

import com.google.common.io.ByteStreams

import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{MetadataBuilder, NumericType, StringType}
import org.apache.spark.unsafe.types.UTF8String
import org.apache.spark.util.Utils

package object util extends Logging {

  /** Silences output to stderr or stdout for the duration of f */
  def quietly[A](f: => A): A = {
    val origErr = System.err
    val origOut = System.out
    try {
      System.setErr(new PrintStream((_: Int) => {}))
      System.setOut(new PrintStream((_: Int) => {}))

      f
    } finally {
      System.setErr(origErr)
      System.setOut(origOut)
    }
  }

  def fileToString(file: File, encoding: Charset = UTF_8): String = {
    val inStream = new FileInputStream(file)
    try {
      new String(ByteStreams.toByteArray(inStream), encoding)
    } finally {
      inStream.close()
    }
  }

  def resourceToBytes(
      resource: String,
      classLoader: ClassLoader = Utils.getSparkClassLoader): Array[Byte] = {
    val inStream = classLoader.getResourceAsStream(resource)
    try {
      ByteStreams.toByteArray(inStream)
    } finally {
      inStream.close()
    }
  }

  def resourceToString(
      resource: String,
      encoding: String = UTF_8.name(),
      classLoader: ClassLoader = Utils.getSparkClassLoader): String = {
    new String(resourceToBytes(resource, classLoader), encoding)
  }

  def stringToFile(file: File, str: String): File = {
    Utils.tryWithResource(new PrintWriter(file)) { out =>
      out.write(str)
    }
    file
  }

  def sideBySide(left: String, right: String): Seq[String] = {
    sideBySide(left.split("\n"), right.split("\n"))
  }

  def sideBySide(left: Seq[String], right: Seq[String]): Seq[String] = {
    val maxLeftSize = left.map(_.length).max
    val leftPadded = left ++ Seq.fill(math.max(right.size - left.size, 0))("")
    val rightPadded = right ++ Seq.fill(math.max(left.size - right.size, 0))("")

    leftPadded.zip(rightPadded).map {
      case (l, r) => (if (l == r) " " else "!") + l + (" " * ((maxLeftSize - l.length) + 3)) + r
    }
  }

  def stackTraceToString(t: Throwable): String = {
    val out = new java.io.ByteArrayOutputStream
    Utils.tryWithResource(new PrintWriter(out)) { writer =>
      t.printStackTrace(writer)
      writer.flush()
    }
    new String(out.toByteArray, UTF_8)
  }

  // Replaces attributes, string literals, complex type extractors with their pretty form so that
  // generated column names don't contain back-ticks or double-quotes.
  def usePrettyExpression(e: Expression): Expression = e transform {
    case a: Attribute => new PrettyAttribute(a)
    case Literal(s: UTF8String, StringType) => PrettyAttribute(s.toString, StringType)
    case Literal(v, t: NumericType) if v != null => PrettyAttribute(v.toString, t)
    case Literal(null, dataType) => PrettyAttribute("NULL", dataType)
    case e: GetStructField =>
      val name = e.name.getOrElse(e.childSchema(e.ordinal).name)
      PrettyAttribute(usePrettyExpression(e.child).sql + "." + name, e.dataType)
    case e: GetArrayStructFields =>
      PrettyAttribute(usePrettyExpression(e.child) + "." + e.field.name, e.dataType)
    case r: InheritAnalysisRules =>
      PrettyAttribute(r.makeSQLString(r.parameters.map(toPrettySQL)), r.dataType)
    case c: Cast if !c.getTagValue(Cast.USER_SPECIFIED_CAST).getOrElse(false) =>
      PrettyAttribute(usePrettyExpression(c.child).sql, c.dataType)
    case p: PythonUDF => PrettyPythonUDF(p.name, p.dataType, p.children)
  }

  def quoteIdentifier(name: String): String = {
    // Escapes back-ticks within the identifier name with double-back-ticks, and then quote the
    // identifier with back-ticks.
    "`" + name.replace("`", "``") + "`"
  }

  def quoteNameParts(name: Seq[String]): String = {
    name.map(part => quoteIdentifier(part)).mkString(".")
  }

  def quoteIfNeeded(part: String): String = {
    if (part.matches("[a-zA-Z0-9_]+") && !part.matches("\\d+")) {
      part
    } else {
      s"`${part.replace("`", "``")}`"
    }
  }

  def toPrettySQL(e: Expression): String = usePrettyExpression(e).sql

  def escapeSingleQuotedString(str: String): String = {
    val builder = new StringBuilder

    str.foreach {
      case '\'' => builder ++= s"\\\'"
      case ch => builder += ch
    }

    builder.toString()
  }

  /** Whether we have warned about plan string truncation yet. */
  private val truncationWarningPrinted = new AtomicBoolean(false)

  /**
   * Format a sequence with semantics similar to calling .mkString(). Any elements beyond
   * maxNumToStringFields will be dropped and replaced by a "... N more fields" placeholder.
   *
   * @return the trimmed and formatted string.
   */
  def truncatedString[T](
      seq: Seq[T],
      start: String,
      sep: String,
      end: String,
      maxFields: Int): String = {
    if (seq.length > maxFields) {
      if (truncationWarningPrinted.compareAndSet(false, true)) {
        logWarning(
          "Truncated the string representation of a plan since it was too large. This " +
            s"behavior can be adjusted by setting '${SQLConf.MAX_TO_STRING_FIELDS.key}'.")
      }
      val numFields = math.max(0, maxFields - 1)
      seq.take(numFields).mkString(
        start, sep, sep + "... " + (seq.length - numFields) + " more fields" + end)
    } else {
      seq.mkString(start, sep, end)
    }
  }

  /** Shorthand for calling truncatedString() without start or end strings. */
  def truncatedString[T](seq: Seq[T], sep: String, maxFields: Int): String = {
    truncatedString(seq, "", sep, "", maxFields)
  }

  val METADATA_COL_ATTR_KEY = "__metadata_col"

  implicit class MetadataColumnHelper(attr: Attribute) {
    /**
     * If set, this metadata column can only be accessed with qualifiers, e.g. `qualifiers.col` or
     * `qualifiers.*`. If not set, metadata columns cannot be accessed via star.
     */
    val QUALIFIED_ACCESS_ONLY = "__qualified_access_only"

    def isMetadataCol: Boolean = attr.metadata.contains(METADATA_COL_ATTR_KEY) &&
      attr.metadata.getBoolean(METADATA_COL_ATTR_KEY)

    def qualifiedAccessOnly: Boolean = attr.isMetadataCol &&
      attr.metadata.contains(QUALIFIED_ACCESS_ONLY) &&
      attr.metadata.getBoolean(QUALIFIED_ACCESS_ONLY)

    def markAsQualifiedAccessOnly(): Attribute = attr.withMetadata(
      new MetadataBuilder()
        .withMetadata(attr.metadata)
        .putBoolean(METADATA_COL_ATTR_KEY, true)
        .putBoolean(QUALIFIED_ACCESS_ONLY, true)
        .build()
    )
  }
}

redpajama_set_name: RedPajamaGithub


text:
package de.oliver_heger.linedj.archive.media

import java.nio.file.Paths
import java.util.concurrent.atomic.AtomicReference

import akka.actor.{ActorRef, ActorSystem, Props, Terminated}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import de.oliver_heger.linedj.StateTestHelper
import de.oliver_heger.linedj.io.FileData
import de.oliver_heger.linedj.shared.archive.media.{MediumID, MediumInfo}
import org.scalatest.BeforeAndAfterAll
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar

import scala.concurrent.duration._
import scala.concurrent.{Await, Promise}
import scala.util.Failure

object ScanSinkActorSpec {
  /** Maximum buffer size used by tests. */
  private val BufferSize = 42

  /** A test sequence number. */
  private val SeqNo = 111

  /**
    * Creates a test medium ID with the given index.
    *
    * @param idx the index
    * @return the test medium ID
    */
  private def createMediumID(idx: Int): MediumID = {
    val uri = "/music/test/medium" + idx
    MediumID(uri, Some(uri + "/playlist.settings"))
  }

  /**
    * Generates an enhanced scan result for the test medium with the given
    * index.
    *
    * @param idx the index
    * @return the scan result for this medium
    */
  private def createScanResult(idx: Int): EnhancedMediaScanResult = {
    val mid = createMediumID(idx)
    val files = (1 to idx).map(i => FileData(Paths get s"${mid.mediumURI}/music/song$i.mp3", i * 10))
    val scanResult = MediaScanResult(Paths get mid.mediumURI, Map(mid -> files.toList))
    EnhancedMediaScanResult(scanResult, Map(mid -> MediumChecksum(s"foo_$idx")))
  }

  /**
    * Creates a medium info object for the test medium with the given index.
    *
    * @param idx the index
    * @return the medium information for this medium
    */
  private def createMediumInfo(idx: Int): MediumInfo =
    MediumInfo(mediumID = createMediumID(idx), name = "info" + idx, description = "",
      orderMode = "", orderParams = "", checksum = "")

  /**
    * Creates a map with medium information for the specified test medium.
    *
    * @param idx the index of the test medium
    * @return the map with medium information for this test medium
    */
  private def createMediaInfoMap(idx: Int): Map[MediumID, MediumInfo] = {
    val info = createMediumInfo(idx)
    Map(info.mediumID -> info)
  }

  /**
    * Creates a combined result object for the specified test medium.
    *
    * @param idx the index of the test medium
    * @return the combined result object for this medium
    */
  private def createCombinedResult(idx: Int): CombinedMediaScanResult =
    CombinedMediaScanResult(createScanResult(idx), createMediaInfoMap(idx))

  /**
    * Checks that no message was sent to the given test probe.
    *
    * @param probe the test probe
    */
  private def expectNoMessageToProbe(probe: TestProbe): Unit = {
    val Ping = new Object
    probe.ref ! Ping
    probe.expectMsg(Ping)
  }
}

/**
  * Test class for ''ScanSinkActor''.
  */
class ScanSinkActorSpec(testSystem: ActorSystem) extends TestKit(testSystem) with ImplicitSender
  with AnyFlatSpecLike with BeforeAndAfterAll with Matchers with MockitoSugar {
  def this() = this(ActorSystem("ScanSinkActorSpec"))

  override protected def afterAll(): Unit = {
    TestKit shutdownActorSystem system
  }

  import ScanSinkActorSpec._

  "A ScanSinkActor" should "use the default sink update service" in {
    val manager = TestProbe()
    val actor = TestActorRef[ScanSinkActor](Props(classOf[ScanSinkActor], manager.ref,
      Promise[Unit](), BufferSize, SeqNo))

    actor.underlyingActor.sinkUpdateService should be(ScanSinkUpdateServiceImpl)
  }

  it should "ACK an init message" in {
    val helper = new SinkActorTestHelper

    helper post ScanSinkActor.Init
    expectMsg(ScanSinkActor.Ack)
  }

  it should "pass combined results for a new scan result to the manager" in {
    val res = createScanResult(1)
    val results = List(createCombinedResult(1), createCombinedResult(2))
    val messages = SinkTransitionMessages(results, Nil, processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleNewScanResult(res, testActor, BufferSize)
    }
      .post(res)
      .expectCombinedResults(results)
  }

  it should "send ACK messages to actors when receiving a new scan result" in {
    val probeAck1 = TestProbe()
    val probeAck2 = TestProbe()
    val res = createScanResult(1)
    val messages = SinkTransitionMessages(Nil, List(probeAck1.ref, probeAck2.ref),
      processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleNewScanResult(res, testActor, BufferSize)
    }
      .post(res)
    probeAck1.expectMsg(ScanSinkActor.Ack)
    probeAck2.expectMsg(ScanSinkActor.Ack)
    helper.expectNoResults()
  }

  it should "handle the arrival of a medium information" in {
    val probeAck = TestProbe()
    val info = createMediumInfo(1)
    val results = List(createCombinedResult(1))
    val messages = SinkTransitionMessages(results, List(probeAck.ref), processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleNewMediumInfo(info, testActor, BufferSize)
    }
      .post(info)
      .expectCombinedResults(results)
    probeAck.expectMsg(ScanSinkActor.Ack)
  }

  it should "correctly manage its internal state" in {
    val res = createScanResult(1)
    val info = createMediumInfo(1)
    val results = List(createCombinedResult(1))
    val state = ScanSinkUpdateServiceImpl.InitialState.copy(scanResults = List(res))
    val messages1 = SinkTransitionMessages(Nil, Nil, processingDone = false)
    val messages2 = SinkTransitionMessages(results, Nil, processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages1, state) {
      _.handleNewScanResult(res, testActor, BufferSize)
    }
      .stub(messages2, ScanSinkUpdateServiceImpl.InitialState) {
        _.handleNewMediumInfo(info, testActor, BufferSize)
      }
      .post(res)
      .expectStateUpdate(ScanSinkUpdateServiceImpl.InitialState)
      .expectNoResults()
      .post(info)
      .expectStateUpdate(state)
      .expectCombinedResults(results)
  }

  it should "handle an ACK message from the management actor" in {
    val actor = TestProbe()
    val messages = SinkTransitionMessages(Nil, List(actor.ref), processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleResultAck(BufferSize)
    }
      .postAckFromManager()
    actor.expectMsg(ScanSinkActor.Ack)
  }

  it should "ignore an ACK message from another sender" in {
    val results1 = List(createCombinedResult(1))
    val results2 = List(createCombinedResult(2))
    val res = createScanResult(3)
    val messages1 = SinkTransitionMessages(results1, Nil, processingDone = false)
    val messages2 = SinkTransitionMessages(results2, Nil, processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages1, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleResultAck(BufferSize)
    }
      .stub(messages2, ScanSinkUpdateServiceImpl.InitialState) {
        _.handleNewScanResult(res, testActor, BufferSize)
      }
      .post(ScanSinkActor.Ack)
      .post(res)
      .expectCombinedResults(results2)
  }

  it should "handle a message about completed scan results" in {
    val results = List(createCombinedResult(1))
    val messages = SinkTransitionMessages(results, Nil, processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleScanResultsDone(BufferSize)
    }
      .post(ScanSinkActor.ScanResultsComplete)
      .expectCombinedResults(results)
  }

  it should "handle a message about completed media info" in {
    val results = List(createCombinedResult(1))
    val messages = SinkTransitionMessages(results, Nil, processingDone = false)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleMediaInfoDone(BufferSize)
    }
      .post(ScanSinkActor.MediaInfoComplete)
      .expectCombinedResults(results)
  }

  it should "handle processing done flag" in {
    val messages = SinkTransitionMessages(Nil, Nil, processingDone = true)
    val helper = new SinkActorTestHelper

    helper.stub(messages, ScanSinkUpdateServiceImpl.InitialState) {
      _.handleResultAck(BufferSize)
    }
      .postAckFromManager()
      .expectPromiseCompleted()
      .expectSinkActorStopped()
  }

  it should "handle a stream failure message" in {
    val ex = new RuntimeException("Stream failure!")
    val helper = new SinkActorTestHelper

    helper.post(ScanSinkActor.StreamFailure(ex))
      .expectPromiseFailed(ex)
      .expectSinkActorStopped()
  }

  /**
    * A test helper class managing a test instance and its dependencies.
    */
  private class SinkActorTestHelper
    extends StateTestHelper[ScanSinkState, ScanSinkUpdateService] {
    /** Mock for the scan sink update service. */
    override val updateService: ScanSinkUpdateService = mock[ScanSinkUpdateService]

    /** Test probe for the media manager actor. */
    private val probeManager = TestProbe()

    /** The promise passed to the test actor. */
    private val promise = Promise[Unit]()

    /** The actor to be tested. */
    private val sinkActor = createSinkActor()

    /**
      * Sends the specified message to the test actor.
      *
      * @param msg the message to be sent
      * @return this test helper
      */
    def post(msg: Any): SinkActorTestHelper = {
      sinkActor ! msg
      this
    }

    /**
      * Tests that a message with the specified results has been sent to the
      * manager actor.
      *
      * @param results a list with the expected results
      * @return this test helper
      */
    def expectCombinedResults(results: Iterable[CombinedMediaScanResult]):
    SinkActorTestHelper = {
      probeManager.expectMsg(ScanSinkActor.CombinedResults(results, SeqNo))
      this
    }

    /**
      * Checks that no message was sent to the manager actor.
      *
      * @return this test helper
      */
    def expectNoResults(): SinkActorTestHelper = {
      expectNoMessageToProbe(probeManager)
      this
    }

    /**
      * Simulates an ACK message from the management actor.
      *
      * @return this test helper
      */
    def postAckFromManager(): SinkActorTestHelper = {
      sinkActor.tell(ScanSinkActor.Ack, probeManager.ref)
      this
    }

    /**
      * Tests that the test actor has been stopped.
      *
      * @return this test helper
      */
    def expectSinkActorStopped(): SinkActorTestHelper = {
      val probeWatcher = TestProbe()
      probeWatcher watch sinkActor
      probeWatcher.expectMsgType[Terminated]
      this
    }

    /**
      * Checks whether the promise passed to the test actor has been completed
      * with a success value.
      *
      * @return this test helper
      */
    def expectPromiseCompleted(): SinkActorTestHelper = {
      Await.result(promise.future, 5.seconds)
      this
    }

    /**
      * Checks whether the promise passed to the test actor has been completed
      * with the exception specified.
      *
      * @param ex the exception
      * @return this test helper
      */
    def expectPromiseFailed(ex: Throwable): SinkActorTestHelper = {
      import system.dispatcher
      val refEx = new AtomicReference[Throwable]
      promise.future.onComplete {
        case Failure(e) =>
          refEx set e
        case _ =>
      }
      awaitCond(refEx.get() == ex)
      this
    }

    /**
      * Creates a test actor instance.
      *
      * @return the test actor instance
      */
    private def createSinkActor(): ActorRef =
      system.actorOf(Props(new ScanSinkActor(probeManager.ref, promise, BufferSize, SeqNo,
        updateService)))
  }

}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import os

from pants.backend.jvm.tasks.jvmdoc_gen import Jvmdoc, JvmdocGen
from pants.base.exceptions import TaskError
from pants_test.jvm.jvm_task_test_base import JvmTaskTestBase

dummydoc = Jvmdoc(tool_name='dummydoc', product_type='dummydoc')

class DummyJvmdocGen(JvmdocGen):
  @classmethod
  def jvmdoc(cls):
    return dummydoc

  def execute(self):
    self.generate_doc(lambda t: True, create_dummydoc_command)

def create_dummydoc_command(classpath, gendir, *targets):
  # here we need to test that we get the expected classpath
  pass

class JvmdocGenTest(JvmTaskTestBase):
  """Test some base functionality in JvmdocGen."""

  @classmethod
  def task_type(cls):
    return DummyJvmdocGen

  def setUp(self):
    super(JvmdocGenTest, self).setUp()

    self.t1 = self.make_target('t1')
    context = self.context(target_roots=[self.t1])

    self.targets = context.targets()

    self.populate_runtime_classpath(context)

    self.task = self.create_task(context)

  def test_classpath(self):
    self.task.execute()

  def test_generate(self):
    def create_jvmdoc_command_fail(classpath, gendir, *targets):
      return os.path.join(os.path.dirname(__file__), "false.py")
    def create_jvmdoc_command_succeed(classpath, gendir, *targets):
      return os.path.join(os.path.dirname(__file__), "true.py")

    for generate in [self.task._generate_individual,
                     self.task._generate_combined]:
      with self.assertRaises(TaskError):
        generate([], self.targets, create_jvmdoc_command_fail)

      generate([], self.targets, create_jvmdoc_command_succeed)


text:
angular.module('TemplateFillerApp.services', [])

.constant('OpenFile', function() {
  var input = $('<input type="file">');

  input.on('change', function(e) {
    console.log(e.target.value);
  });

  input.trigger('click');
})

.constant('SaveFile', function(callback) {
  var input = $('<input nwsaveas="result.pdf" type="file">');

  input.on('change', function(e) {
    callback(e.target.value);
  });

  input.trigger('click');
})

.service('CurrentData', [function() {
  var header = [ 'FieldColumn' ];
  var data = [ { 'FieldColumn': 'value' } ];

  this.getRows = function() {
    return data;
  }

  this.getColumns = function() {
    return header;
  }
}])

.service('CurrentTemplate', [function() {
  var text = '#example page\n{{ FieldColumn }}';

  this.getMarkdown = function() {
    return text;
  }

  this.setMarkdown = function(str) {
    text = str;
  }

}])


text:
<readable><title>210686241_b8e069fff3</title><content>
A boy being drenched in a downpour of water .
A boy playing in water .
A child in a white sox shirt is covered in water spray and looks distressed .
A young boy wearing a black shirt is getting soaked in the rain .
Children playing in water .
</content></readable>


text:
function Pubsubcutioner() {
    var messages = {};

    function gatherSubscribers(topic){
        var subscribers = [];
        for(var message in messages) {
            if( new RegExp('^' + message + '$').test( topic ) ){
                subscribers = subscribers.concat( messages[message] );
            }
        }
        return subscribers;
    }

    // Publicly exposed methods
    var methods = {};
    /**
     *    Pubsubcutioner.publish( message[, data] ) -> Boolean
     *    - message (String): The message to publish
     *    - data: The data to pass to subscribers
     *    Publishes the the message, passing the data to it's subscribers
    **/
    methods.publish = function( message, data ){
        var subscribers = gatherSubscribers(message), s;
        for (s in subscribers){
            if ( subscribers.hasOwnProperty(s)){
                try{
                    subscribers[s](message, data);
                }catch(e){
                    if(typeof console !== 'undefined'){
                        console.log(e.stack);
                    }
                }
            }
        }
        return true;
    };

    /**
     *    Pubsubcutioner.subscribe( message, func ) -> String
     *    - message (String): The message to subscribe to
     *    - func (Function): The function to call when a new message is published
     *    Subscribes the passed function to the passed message.
    **/
    methods.subscribe = function( message, func ){
        if ( typeof func !== 'function'){
            return false;
        }

        // message is not registered yet
        if ( !messages.hasOwnProperty( message ) ){
            messages[message] = [];
        }

        messages[message] = messages[message].concat(func);
        return true;
    };

    /* Public: Clears all subscriptions
     */
    methods.clearAllSubscriptions = function clearAllSubscriptions(){
        messages = {};
    };

    /*Public: Clear subscriptions by the topic
    */
    methods.clearSubscriptions = function clearSubscriptions(topic){
        var m;
        for (m in messages){
            if (messages.hasOwnProperty(m) && m.indexOf(topic) === 0){
                delete messages[m];
            }
        }
    };

    /* Public: removes subscriptions.
     * When passed a token, removes a specific subscription.
     * When passed a function, removes all subscriptions for that function
     * When passed a topic, removes all subscriptions for that topic (hierarchy)
     *
     * value - A token, function or topic to unsubscribe.
     *
     * Examples
     *
     *        // Example 1 - unsubscribing with a token
     *        var token = Pubsubcutioner.subscribe('mytopic', myFunc);
     *        Pubsubcutioner.unsubscribe(token);
     *
     *        // Example 2 - unsubscribing with a function
     *        Pubsubcutioner.unsubscribe(myFunc);
     *
     *        // Example 3 - unsubscribing a topic
     *        Pubsubcutioner.unsubscribe('mytopic');
     */
    methods.unsubscribe = function(value){
        var isTopic    = typeof value === 'string' && messages.hasOwnProperty(value),
            isFunction = typeof value === 'function',
            result = false,
            m, message, t;

        if (isTopic){
            delete messages[value];
            return;
        }

        for ( m in messages ){
            if ( messages.hasOwnProperty( m ) ){
                message = messages[m];

                if (isFunction) {
                    for ( t in message ){
                        if (message.hasOwnProperty(t) && message[t] === value){
                            delete message[t];
                            result = true;
                        }
                    }
                }
            }
        }

        return result;
    };

    if(typeof window !== 'undefined'){
        if(window.pubsubcutioner){
            console.error('pubsubcutioner already initialized, aborting!');
        }else{
            window.pubsubcutioner = methods;
        }
    }
    return methods;
}


text:
'use strict';
const common = require('../common');
const assert = require('assert');
const child_process = require('child_process');
const fixtures = require('../common/fixtures');

const wrong_script = fixtures.path('cert.pem');

const p = child_process.spawn(process.execPath, [
  '-e',
  'require(process.argv[1]);',
  wrong_script
]);

p.stdout.on('data', common.mustNotCall());

let output = '';

p.stderr.on('data', (data) => output += data);

p.stderr.on('end', common.mustCall(() => {
  assert(/BEGIN CERT/.test(output));
  assert(/^\s+\^/m.test(output));
  assert(/Invalid left-hand side expression in prefix operation/.test(output));
}));


text:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" type="text/css" href="http://fast.fonts.com/cssapi/72bd3277-b253-4903-97d8-6a9d18744569.css" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Inconsolata" />
<link rel="stylesheet" type="text/css" href="/release/quickui.css" />
<link rel="stylesheet" type="text/css" href="/release/quickui.catalog.css" />
<link rel="stylesheet" type="text/css" href="/site.css" />
<link rel="stylesheet" type="text/css" href="/controls/controls.css" />
<link rel="stylesheet" type="text/css" href="/catalog/demos.css" />

<script type="text/javascript" src="/lib/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="/thirdParty/ace/ace.js"></script>
<script type="text/javascript" src="/thirdParty/ace/mode-javascript.js"></script>
<script type="text/javascript" src="/release/quickui.js"></script>
<script type="text/javascript" src="/release/quickui.catalog.js"></script>
<script type="text/javascript" src="/catalog/catalog-db.js"></script>
<script type="text/javascript" src="/controls/controls.js"></script>
<script type="text/javascript" src="/catalog/demos.js"></script>
<script type="text/javascript" src="/catalog/controlDocumentation.js"></script>

<title>Log</title>

</head>

<body data-create-controls="true" data-control="CatalogPage">

<div data-property="summary">
Displays a growing text log showing, for example, the output of an ongoing
process.
</div>

</body>

</html>


text:
#include <osquery/logger.h>

#include "osquery/sql/virtual_table.h"

namespace osquery {
namespace tables {

int xOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) {
  int rc = SQLITE_NOMEM;
  BaseCursor *pCur = new BaseCursor;

  if (pCur) {
    memset(pCur, 0, sizeof(BaseCursor));
    *ppCursor = (sqlite3_vtab_cursor *)pCur;
    rc = SQLITE_OK;
  }

  return rc;
}

int xClose(sqlite3_vtab_cursor *cur) {
  BaseCursor *pCur = (BaseCursor *)cur;

  delete pCur;
  return SQLITE_OK;
}

int xEof(sqlite3_vtab_cursor *cur) {
  BaseCursor *pCur = (BaseCursor *)cur;
  auto *pVtab = (VirtualTable *)cur->pVtab;

  if (pCur->row >= pVtab->content->n) {
    // If the requested row exceeds the size of the row set then all rows
    // have been visited, clear the data container.
    QueryData().swap(pVtab->content->data);
    return true;
  }
  return false;
}

int xDestroy(sqlite3_vtab *p) {
  auto *pVtab = (VirtualTable *)p;
  delete pVtab->content;
  delete pVtab;
  return SQLITE_OK;
}

int xNext(sqlite3_vtab_cursor *cur) {
  BaseCursor *pCur = (BaseCursor *)cur;
  pCur->row++;
  return SQLITE_OK;
}

int xRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid) {
  const BaseCursor *pCur = (BaseCursor *)cur;
  *pRowid = pCur->row;
  return SQLITE_OK;
}

int xCreate(sqlite3 *db,
            void *pAux,
            int argc,
            const char *const *argv,
            sqlite3_vtab **ppVtab,
            char **pzErr) {
  auto *pVtab = new VirtualTable;

  if (!pVtab || argc == 0 || argv[0] == nullptr) {
    return SQLITE_NOMEM;
  }

  memset(pVtab, 0, sizeof(VirtualTable));
  pVtab->content = new VirtualTableContent;

  PluginResponse response;
  pVtab->content->name = std::string(argv[0]);

  // Get the table column information.
  auto status = Registry::call(
      "table", pVtab->content->name, {{"action", "columns"}}, response);
  if (!status.ok() || response.size() == 0) {
    return SQLITE_ERROR;
  }

  auto statement =
      "CREATE TABLE " + pVtab->content->name + columnDefinition(response);
  int rc = sqlite3_declare_vtab(db, statement.c_str());
  if (rc != SQLITE_OK) {
    return rc;
  }

  if (!status.ok() || response.size() == 0) {
    return SQLITE_ERROR;
  }

  for (const auto &column : response) {
    pVtab->content->columns.push_back(
        std::make_pair(column.at("name"), column.at("type")));
  }

  *ppVtab = (sqlite3_vtab *)pVtab;
  return rc;
}

int xColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int col) {
  const BaseCursor *pCur = (BaseCursor *)cur;
  const auto *pVtab = (VirtualTable *)cur->pVtab;

  if (col >= pVtab->content->columns.size()) {
    // Requested column index greater than column set size.
    return SQLITE_ERROR;
  }

  const auto &column_name = pVtab->content->columns[col].first;
  const auto &type = pVtab->content->columns[col].second;
  if (pCur->row >= pVtab->content->data.size()) {
    // Request row index greater than row set size.
    return SQLITE_ERROR;
  }

  // Attempt to cast each xFilter-populated row/column to the SQLite type.
  const auto &value = pVtab->content->data[pCur->row][column_name];
  if (type == "TEXT") {
    sqlite3_result_text(ctx, value.c_str(), value.size(), SQLITE_STATIC);
  } else if (type == "INTEGER") {
    char *end = nullptr;
    long int afinite = strtol(value.c_str(), &end, 10);
    if (end == nullptr || end == value.c_str() || *end != '\0' ||
        ((afinite == LONG_MIN || afinite == LONG_MAX) && errno == ERANGE) ||
        afinite < INT_MIN || afinite > INT_MAX) {
      afinite = -1;
      VLOG(1) << "Error casting " << column_name << " (" << value
              << ") to INTEGER";
    }
    sqlite3_result_int(ctx, (int)afinite);
  } else if (type == "BIGINT") {
    char *end = nullptr;
    long long int afinite = strtoll(value.c_str(), &end, 10);
    if (end == nullptr || end == value.c_str() || *end != '\0' ||
        ((afinite == LLONG_MIN || afinite == LLONG_MAX) && errno == ERANGE)) {
      afinite = -1;
      VLOG(1) << "Error casting " << column_name << " (" << value
              << ") to BIGINT";
    }
    sqlite3_result_int64(ctx, afinite);
  } else if (type == "DOUBLE") {
    char *end = nullptr;
    double afinite = strtod(value.c_str(), &end);
    if (end == nullptr || end == value.c_str() || *end != '\0') {
      afinite = 0;
      VLOG(1) << "Error casting " << column_name << " (" << value
              << ") to DOUBLE";
    }
    sqlite3_result_double(ctx, afinite);
  }

  return SQLITE_OK;
}

static int xBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo) {
  auto *pVtab = (VirtualTable *)tab;
  ConstraintSet().swap(pVtab->content->constraints);

  int expr_index = 0;
  int cost = 0;
  for (size_t i = 0; i < pIdxInfo->nConstraint; ++i) {
    if (!pIdxInfo->aConstraint[i].usable) {
      // A higher cost less priority, prefer more usable query constraints.
      cost += 10;
      // TODO: OR is not usable.
      continue;
    }

    const auto &name =
        pVtab->content->columns[pIdxInfo->aConstraint[i].iColumn].first;
    pVtab->content->constraints.push_back(
        std::make_pair(name, Constraint(pIdxInfo->aConstraint[i].op)));
    pIdxInfo->aConstraintUsage[i].argvIndex = ++expr_index;
  }

  pIdxInfo->estimatedCost = cost;
  return SQLITE_OK;
}

static int xFilter(sqlite3_vtab_cursor *pVtabCursor,
                   int idxNum,
                   const char *idxStr,
                   int argc,
                   sqlite3_value **argv) {
  BaseCursor *pCur = (BaseCursor *)pVtabCursor;
  auto *pVtab = (VirtualTable *)pVtabCursor->pVtab;

  pCur->row = 0;
  pVtab->content->n = 0;
  QueryContext context;

  for (size_t i = 0; i < pVtab->content->columns.size(); ++i) {
    // Set the column affinity for each optional constraint list.
    // There is a separate list for each column name.
    context.constraints[pVtab->content->columns[i].first].affinity =
        pVtab->content->columns[i].second;
  }

  // Iterate over every argument to xFilter, filling in constraint values.
  for (size_t i = 0; i < argc; ++i) {
    auto expr = (const char *)sqlite3_value_text(argv[i]);
    if (expr == nullptr) {
      // SQLite did not expose the expression value.
      continue;
    }
    // Set the expression from SQLite's now-populated argv.
    pVtab->content->constraints[i].second.expr = std::string(expr);
    // Add the constraint to the column-sorted query request map.
    context.constraints[pVtab->content->constraints[i].first].add(
        pVtab->content->constraints[i].second);
  }

  // Reset the virtual table contents.
  pVtab->content->data.clear();

  // Generate the row data set.
  PluginRequest request = {{"action", "generate"}};
  TablePlugin::setRequestFromContext(context, request);
  Registry::call("table", pVtab->content->name, request, pVtab->content->data);

  // Set the number of rows.
  pVtab->content->n = pVtab->content->data.size();

  return SQLITE_OK;
}
}

Status attachTableInternal(const std::string &name,
                           const std::string &statement,
                           sqlite3 *db) {
  if (SQLiteDBManager::isDisabled(name)) {
    VLOG(0) << "Table " << name << " is disabled, not attaching";
    return Status(0, getStringForSQLiteReturnCode(0));
  }

  // A static module structure does not need specific logic per-table.
  // clang-format off
  static sqlite3_module module = {
      0,
      tables::xCreate,
      tables::xCreate,
      tables::xBestIndex,
      tables::xDestroy,
      tables::xDestroy,
      tables::xOpen,
      tables::xClose,
      tables::xFilter,
      tables::xNext,
      tables::xEof,
      tables::xColumn,
      tables::xRowid,
  };
  // clang-format on

  // Note, if the clientData API is used then this will save a registry call
  // within xCreate.
  int rc = sqlite3_create_module(db, name.c_str(), &module, 0);
  if (rc == SQLITE_OK || rc == SQLITE_MISUSE) {
    auto format =
        "CREATE VIRTUAL TABLE temp." + name + " USING " + name + statement;
    rc = sqlite3_exec(db, format.c_str(), nullptr, nullptr, 0);
  } else {
    LOG(ERROR) << "Error attaching table: " << name << " (" << rc << ")";
  }
  return Status(rc, getStringForSQLiteReturnCode(rc));
}

Status detachTableInternal(const std::string &name, sqlite3 *db) {
  auto format = "DROP TABLE IF EXISTS temp." + name;
  int rc = sqlite3_exec(db, format.c_str(), nullptr, nullptr, 0);
  if (rc != SQLITE_OK) {
    LOG(ERROR) << "Error detaching table: " << name << " (" << rc << ")";
  }

  return Status(rc, getStringForSQLiteReturnCode(rc));
}

void attachVirtualTables(sqlite3 *db) {
  PluginResponse response;
  for (const auto &name : Registry::names("table")) {
    // Column information is nice for virtual table create call.
    auto status =
        Registry::call("table", name, {{"action", "columns"}}, response);
    if (status.ok()) {
      auto statement = columnDefinition(response);
      attachTableInternal(name, statement, db);
    }
  }
}
}


text:
<?php declare(strict_types=1);

namespace Altair\Cache\Contracts;

interface CacheItemTagValidatorInterface extends FailureReasonAwareInterface
{
    /**
     * Checks whether a cache tag is valid and if not. If valid will return true, false otherwise.
     *
     * @param string $tag
     *
     * @return bool
     */
    public function validate(string $tag): bool;
}


text:
'use strict';

var AppConstants = require('../constants/AppConstants');
var Dispatcher = require('flux').Dispatcher;

var PayloadSources = AppConstants.PayloadSources;

var AppDispatcher = new Dispatcher();

AppDispatcher.handleViewAction = function(action) {
  this.dispatch({
    source: PayloadSources.VIEW_ACTION,
    action: action
  });
};

AppDispatcher.handleServerAction = function(action) {
  this.dispatch({
    source: PayloadSources.SERVER_ACTION,
    action: action
  });
};

module.exports = AppDispatcher;


text:
package net.tridentsdk.meta.entity.living.animal;

import lombok.Getter;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;

/**
 * Represents the different types of Horses.
 *
 * @author TridentSDK
 * @since 0.5-alpha
 */
@Immutable
public enum HorseType {
    /**
     * A horse.
     */
    HORSE(0),

    /**
     * A donkey.
     */
    DONKEY(1),

    /**
     * A mule.
     */
    MULE(2),

    /**
     * A zombie.
     */
    ZOMBIE(3),

    /**
     * A skeleton.
     */
    SKELETON(4);

    @Getter
    private final int data;

    HorseType(int data) {
        this.data = data;
    }

    /**
     * Gets the horse type corresponding to the given internal identification number.
     * <br>
     * If none are found, an {@link IllegalArgumentException} will be thrown.
     *
     * @param id The identification number.
     *
     * @return The horse type.
     */
    @Nonnull
    public static HorseType of(int id) {
        for (HorseType type : values()) {
            if (type.data == id) {
                return type;
            }
        }

        throw new IllegalArgumentException("no horse type with id = " + id);
    }
}


text:
'use strict';

angular.module('demoApp', [
  'officeuifabric.core',
  'officeuifabric.components.orgchart'
])
  .controller('demoController', function () {
    var vm = this;

    vm.selectedItems1 = [];
    vm.selectedItems2 = [];

    vm.items = [
      {
        country: 'Denmark',
        imageUrl: 'Persona.Person2.png',
        name: 'Kevin Magnussen',
        presence: 'available',
        selected1: true,
        selected2: true,
        team: 'Renault'
      },
      {
        country: '	Germany',
        imageUrl: 'Persona.Person2.png',
        name: 'Sebastian Vettel',
        presence: 'busy',
        selected1: true,
        selected2: true,
        team: 'Ferrari'
      },
      {
        country: '	United Kingdom',
        imageUrl: 'Persona.Person2.png',
        name: 'Jolyon Palmer',
        presence: 'away',
        selected1: false,
        selected2: false,
        team: 'Renault'
      },
      {
        country: 'United Kingdom',
        imageUrl: 'Persona.Person2.png',
        name: 'Lewis Hamilton',
        presence: 'blocked',
        selected1: false,
        selected2: false,
        team: '	Mercedes'
      }
    ];

  });


text:
import React, {Component} from 'react';

import ButtonRadioSelect from 'src/ButtonRadioSelect';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';
import Dialog from 'src/Dialog';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/ButtonRadioSelect.json';

import 'scss/containers/app/modules/field/ButtonRadioSelectExamples.scss';

class ButtonRadioSelectExamples extends Component {

    constructor(props) {

        super(props);

        this.data = [{
            label: 1,
            value: 1
        }, {
            label: 2,
            value: 2
        }, {
            label: 3,
            value: 3
        }, {
            label: 4,
            value: 4
        }, {
            label: 5,
            value: 5
        }];

        this.state = {
            ButtonRadioSelectVisible: {}
        };

    }

    show = id => {

        const {ButtonRadioSelectVisible} = this.state;

        ButtonRadioSelectVisible[id] = true;

        this.setState({
            ButtonRadioSelectVisible
        });

    };

    hide = id => {

        const {ButtonRadioSelectVisible} = this.state;

        ButtonRadioSelectVisible[id] = false;

        this.setState({
            ButtonRadioSelectVisible
        });

    };

    changeHandler = value => {
        console.log(value);
    };

    render() {

        const {ButtonRadioSelectVisible} = this.state;

        return (

ButtonRadioSelect

                    ButtonRadioSelect
                     is a radio select use button style.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

Button Radio Select simple example.

                                <ButtonRadioSelect popupClassName="button-radio-select-example-pop"
                                                   data={this.data}
                                                   value={this.data[0]}
                                                   onChange={this.changeHandler}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="In Dialog"/>

Button Radio Select simple example.

                                <RaisedButton className="trigger-button dialog-button"
                                              value="Show Dialog"
                                              onClick={() => this.show(1)}/>

                                <Dialog visible={ButtonRadioSelectVisible[1]}
                                        onRequestClose={() => this.hide(1)}>
                                    {
                                        dialogContentEl =>

                                                <ButtonRadioSelect popupClassName="button-radio-select-example-pop"
                                                                   data={this.data}
                                                                   value={this.data[0]}
                                                                   parentEl={dialogContentEl}
                                                                   onChange={this.changeHandler}/>

                                    }

                                </Dialog>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};

export default ButtonRadioSelectExamples;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>biz.wolschon</groupId>
    <artifactId>gnucash</artifactId>
    <version>2.0.26</version>
  </parent>
  <groupId>biz.wolschon.finance.jgnucash</groupId>
  <artifactId>accountProperties</artifactId>
  <version>2.0.26</version>
  <packaging>jar</packaging>

  <name>accountProperties</name>
 <dependencies>
    <dependency>
      <groupId>biz.wolschon.finance.jgnucash.editor</groupId>
      <artifactId>main</artifactId>
      <version>2.0.26</version>
    </dependency>
    <dependency>
      <groupId>net.sf.jpf</groupId>
      <artifactId>jpf-boot</artifactId>
      <version>1.5</version>
      <scope>provided</scope>
    </dependency>
 </dependencies>
</project>