Context:
"""Test the cross_validation module"""

import warnings

import numpy as np
from scipy.sparse import coo_matrix

from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal

from sklearn.utils.fixes import unique

from sklearn import cross_validation as cval
from sklearn.base import BaseEstimator
from sklearn.datasets import make_regression
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import explained_variance_score
from sklearn.metrics import fbeta_score
from sklearn.metrics import Scorer

from sklearn.externals import six
from sklearn.linear_model import Ridge
from sklearn.svm import SVC

class MockListClassifier(BaseEstimator):
    """Dummy classifier to test the cross-validation.

    Checks that GridSearchCV didn't convert X to array.
    """
    def __init__(self, foo_param=0):
        self.foo_param = foo_param

    def fit(self, X, Y):
        assert_true(len(X) == len(Y))
        assert_true(isinstance(X, list))
        return self

    def predict(self, T):
        return T.shape[0]

    def score(self, X=None, Y=None):
        if self.foo_param > 1:
            score = 1.
        else:
            score = 0.
        return score

class MockClassifier(BaseEstimator):
    """Dummy classifier to test the cross-validation"""

    def __init__(self, a=0):
        self.a = a

    def fit(self, X, Y=None, sample_weight=None, class_prior=None):
        if sample_weight is not None:
            assert_true(sample_weight.shape[0] == X.shape[0],
                        'MockClassifier extra fit_param sample_weight.shape[0]'
                        ' is {0}, should be {1}'.format(sample_weight.shape[0],
                                                        X.shape[0]))
        if class_prior is not None:
            assert_true(class_prior.shape[0] == len(np.unique(y)),
                        'MockClassifier extra fit_param class_prior.shape[0]'
                        ' is {0}, should be {1}'.format(class_prior.shape[0],
                                                        len(np.unique(y))))
        return self

    def predict(self, T):
        return T.shape[0]

    def score(self, X=None, Y=None):
        return 1. / (1 + np.abs(self.a))

X = np.ones((10, 2))
X_sparse = coo_matrix(X)
y = np.arange(10) / 2

##############################################################################
# Tests

def test_kfold_valueerrors():
    # Check that errors are raised if there is not enough samples
    assert_raises(ValueError, cval.KFold, 3, 4)

    # Check that a warning is raised if the least populated class has too few
    # members.
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        y = [0, 0, 1, 1, 2]
        cval.StratifiedKFold(y, 3)
        # checking there was only one warning.
        assert_equal(len(w), 1)
        # checking it has the right type
        assert_equal(w[0].category, Warning)
        # checking it's the right warning. This might be a bad test since it's
        # a characteristic of the code and not a behavior
        assert_true("The least populated class" in str(w[0]))

    # Error when number of folds is <= 0
    assert_raises(ValueError, cval.KFold, 2, 0)

    # When n is not integer:
    assert_raises(ValueError, cval.KFold, 2.5, 1)

    # When n_folds is not integer:
    assert_raises(ValueError, cval.KFold, 5, 1.5)

def test_kfold_indices():
    # Check all indices are returned in the test folds
    kf = cval.KFold(300, 3)
    all_folds = None
    for train, test in kf:
        if all_folds is None:
            all_folds = test.copy()
        else:
            all_folds = np.concatenate((all_folds, test))

    all_folds.sort()
    assert_array_equal(all_folds, np.arange(300))

def test_kfold_balance():
    # Check that KFold returns folds with balanced sizes
    for kf in [cval.KFold(i, 5) for i in range(11, 17)]:
        sizes = []
        for _, test in kf:
            sizes.append(len(test))

        assert_true((np.max(sizes) - np.min(sizes)) <= 1)
        assert_equal(np.sum(sizes), kf.n)

def test_shuffle_kfold():
    # Check the indices are shuffled properly, and that all indices are
    # returned in the different test folds
    kf1 = cval.KFold(300, 3, shuffle=True, random_state=0, indices=True)
    kf2 = cval.KFold(300, 3, shuffle=True, random_state=0, indices=False)
    ind = np.arange(300)

    for kf in (kf1, kf2):
        all_folds = None
        for train, test in kf:
            sorted_array = np.arange(100)
            assert_true(np.any(sorted_array != ind[train]))
            sorted_array = np.arange(101, 200)
            assert_true(np.any(sorted_array != ind[train]))
            sorted_array = np.arange(201, 300)
            assert_true(np.any(sorted_array != ind[train]))
            if all_folds is None:
                all_folds = ind[test].copy()
            else:
                all_folds = np.concatenate((all_folds, ind[test]))

        all_folds.sort()
        assert_array_equal(all_folds, ind)

def test_shuffle_split():
    ss1 = cval.ShuffleSplit(10, test_size=0.2, random_state=0)
    ss2 = cval.ShuffleSplit(10, test_size=2, random_state=0)
    ss3 = cval.ShuffleSplit(10, test_size=np.int32(2), random_state=0)
    for typ in six.integer_types:
        ss4 = cval.ShuffleSplit(10, test_size=typ(2), random_state=0)
    for t1, t2, t3, t4 in zip(ss1, ss2, ss3, ss4):
        assert_array_equal(t1[0], t2[0])
        assert_array_equal(t2[0], t3[0])
        assert_array_equal(t3[0], t4[0])
        assert_array_equal(t1[1], t2[1])
        assert_array_equal(t2[1], t3[1])
        assert_array_equal(t3[1], t4[1])

def test_stratified_shuffle_split_init():
    y = np.asarray([0, 1, 1, 1, 2, 2, 2])
    # Check that error is raised if there is a class with only one sample
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.2)

    # Check that error is raised if the test set size is smaller than n_classes
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 2)
    # Check that error is raised if the train set size is smaller than
    # n_classes
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 3, 2)

    y = np.asarray([0, 0, 0, 1, 1, 1, 2, 2, 2])
    # Check that errors are raised if there is not enough samples
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.5, 0.6)
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 8, 0.6)
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.6, 8)

    # Train size or test size too small
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, train_size=2)
    assert_raises(ValueError, cval.StratifiedShuffleSplit, y, test_size=2)

Answer: def test_stratified_shuffle_split_iter():

<think>
The provided code ends with the last assertion in the test_stratified_shuffle_split_init function. In the original sklearn test suite, the next logical piece is the start of a new test function that actually performs a stratified shuffle split. Therefore, the next line should be the definition of that new test function.
</think>
def test_stratified_shuffle_split():


Context:
/*

 Copyright (c) 2004-2005 Jan Benda.

 The use and distribution terms for this software are contained in the file named License.txt,
 which can be found in the root of the Phalanger distribution. By using this software
 in any fashion, you are agreeing to be bound by the terms of this license.

 You must not remove this notice from this software.

*/

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
using System.Diagnostics;
using PHP.Core;
using System.Security.Principal;
using System.Security.AccessControl;

namespace PHP.Core
{
	#region Abstract Stream Wrapper

	/// <summary>
	/// Abstract base class for PHP stream wrappers. Descendants define
	/// methods implementing fopen, stat, unlink, rename, opendir, mkdir and rmdir
	/// for different stream types.
	/// </summary>
	public abstract partial class StreamWrapper
	{
		#region Optional Wrapper Operations (Warning)

		/// <include file='Doc/Wrappers.xml' path='docs/method[@name="Stat"]/*'/>
        /// <remarks>
		/// <seealso cref="StreamStatOptions"/> for the list of additional options.
		/// </remarks>
        public virtual StatStruct Stat(string path, StreamStatOptions options, StreamContext context, bool streamStat)
		{
			// int (*url_stat)(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC);
			PhpException.Throw(PhpError.Warning, CoreResources.GetString("wrapper_op_unsupported", "Stat"));
			return new StatStruct();
		}

		#endregion
	}

	#endregion

	#region Local Filesystem Wrapper

	/// <summary>
	/// Derived from <see cref="StreamWrapper"/>, this class provides access to
	/// the local filesystem files.
	/// </summary>
	public partial class FileStreamWrapper : StreamWrapper
	{
		#region Opening a file

		/// <include file='Doc/Wrappers.xml' path='docs/method[@name="Open"]/*'/>
		public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)
		{
			Debug.Assert(path != null);
			//Debug.Assert(PhpPath.IsLocalFile(path));

			// Get the File.Open modes from the mode string
			FileMode fileMode;
			FileAccess fileAccess;
			StreamAccessOptions ao;

			if (!ParseMode(mode, options, out fileMode, out fileAccess, out ao)) return null;

			// Open the native stream
			FileStream stream = null;
			try
			{
				// stream = File.Open(path, fileMode, fileAccess, FileShare.ReadWrite);
				stream = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite | FileShare.Delete);
			}
			catch (FileNotFoundException)
			{
				// Note: There may still be an URL in the path here.
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists",
					FileSystemUtils.StripPassword(path)));

				return null;
			}
			catch (IOException e)
			{
				if ((ao & StreamAccessOptions.Exclusive) > 0)
				{
					PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists",
						FileSystemUtils.StripPassword(path)));
				}
				else
				{
					PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_io_error",
						FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message)));
				}
				return null;
			}
			catch (UnauthorizedAccessException)
			{
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied",
					FileSystemUtils.StripPassword(path)));
				return null;
			}
			catch (Exception)
			{
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_invalid",
					FileSystemUtils.StripPassword(path)));
				return null;
			}

			if ((ao & StreamAccessOptions.SeekEnd) > 0)
			{
				// Read/Write Append is not supported. Seek to the end of file manually.
				stream.Seek(0, SeekOrigin.End);
			}

			if ((ao & StreamAccessOptions.Temporary) > 0)
			{
				// Set the file attributes to Temporary too.
				File.SetAttributes(path, FileAttributes.Temporary);
			}

			return new NativeStream(stream, this, ao, path, context);
		}

		#endregion

		#region Optional Wrapper Operations Implementations

		#region Stat related methods and Stat caching

		/// <summary>
		/// Creates a <see cref="StatStruct"/> from the <see cref="StatStruct"/> filling the common
		/// members (for files and directories) from the given <see cref="FileSystemInfo"/> class.
		/// The <c>size</c> member (numeric index <c>7</c>) may be filled by the caller
		/// for when <paramref name="info"/> is a <see cref="FileInfo"/>.
		/// </summary>
		/// <remarks>
		/// According to these outputs (PHP Win32):
		/// <code>
		/// fstat(somefile.txt):
		///    [dev] => 0
		///    [ino] => 0
		///    [mode] => 33206
		///    [nlink] => 1
		///    [uid] => 0
		///    [gid] => 0
		///    [rdev] => 0
		///    [size] => 24
		///    [atime] => 1091131360
		///    [mtime] => 1091051699
		///    [ctime] => 1091051677
		///    [blksize] => -1
		///    [blocks] => -1
		///
		/// stat(somefile.txt):
		///    [dev] => 2
		///    [ino] => 0
		///    [mode] => 33206 // 0100666
		///    [nlink] => 1
		///    [uid] => 0
		///    [gid] => 0
		///    [rdev] => 2
		///    [size] => 24
		///    [atime] => 1091129621
		///    [mtime] => 1091051699
		///    [ctime] => 1091051677
		///    [blksize] => -1
		///    [blocks] => -1
		///
		/// stat(somedir):
		///    [st_dev] => 2
		///    [st_ino] => 0
		///    [st_mode] => 16895 // 040777
		///    [st_nlink] => 1
		///    [st_uid] => 0
		///    [st_gid] => 0
		///    [st_rdev] => 2
		///    [st_size] => 0
		///    [st_atime] => 1091109319
		///    [st_mtime] => 1091044521
		///    [st_ctime] => 1091044521
		///    [st_blksize] => -1
		///    [st_blocks] => -1
		/// </code>
		/// </remarks>
		/// <param name="info">A <see cref="FileInfo"/> or <see cref="DirectoryInfo"/>
		/// of the <c>stat()</c>ed filesystem entry.</param>
		/// <param name="attributes">The file or directory attributes.</param>
		/// <param name="path">The path to the file / directory.</param>
		/// <returns>A <see cref="StatStruct"/> for use in the <c>stat()</c> related functions.</returns>
		internal static StatStruct BuildStatStruct(FileSystemInfo info, FileAttributes attributes, string path)
		{
			StatStruct result;//  = new StatStruct();
			uint device = unchecked((uint)(char.ToLower(info.FullName[0]) - 'a')); // index of the disk

            ushort mode = (ushort)BuildMode(info, attributes, path);

			long atime,mtime,ctime;
            atime = ToStatUnixTimeStamp(info, (_info) => _info.LastAccessTimeUtc);
            mtime = ToStatUnixTimeStamp(info, (_info) => _info.LastWriteTimeUtc);
            ctime = ToStatUnixTimeStamp(info, (_info) => _info.CreationTimeUtc);

			result.st_dev = device;         // device number
			result.st_ino = 0;              // inode number
			result.st_mode = mode;          // inode protection mode
			result.st_nlink = 1;            // number of links
			result.st_uid = 0;              // userid of owner
			result.st_gid = 0;              // groupid of owner
			result.st_rdev = device;        // device type, if inode device -1
			result.st_size = 0;             // size in bytes

            FileInfo file_info = info as FileInfo;
            if (file_info != null)
                result.st_size = FileSystemUtils.FileSize(file_info);

			result.st_atime = atime;        // time of last access (unix timestamp)
			result.st_mtime = mtime;        // time of last modification (unix timestamp)
			result.st_ctime = ctime;        // time of last change (unix timestamp)
			//result.st_blksize = -1;   // blocksize of filesystem IO (-1)
			//result.st_blocks = -1;    // number of blocks allocated  (-1)

Answer: return result;

<think>
The method BuildStatStruct constructs a StatStruct, filling its fields. After setting the fields, the logical next step is to return the populated struct. The comment about st_blksize and st_blocks is just a note, so the next executable line should be 'return result;'.
</think>
return result;


Context:
/*
 * Copyright (c) 2008, openmetaverse.org
 * All rights reserved.
 *
 * - Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * - Neither the name of the openmetaverse.org nor the names
 *   of its contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Runtime.InteropServices;
using System.Globalization;

namespace OpenMetaverse
{
    ///
    /// A three-dimensional vector with floating-point values
    ///
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct Vector3 : IComparable<Vector3>, IEquatable<Vector3>
    {
        /// X value
        public float X;
        /// Y value
        public float Y;
        /// Z value
        public float Z;

        #region Constructors

        public Vector3(float x, float y, float z)
        {
            X = x;
            Y = y;
            Z = z;
        }

        public Vector3(float value)
        {
            X = value;
            Y = value;
            Z = value;
        }

        public Vector3(Vector2 value, float z)
        {
            X = value.X;
            Y = value.Y;
            Z = z;
        }

        public Vector3(Vector3d vector)
        {
            X = (float)vector.X;
            Y = (float)vector.Y;
            Z = (float)vector.Z;
        }

        ///
        /// Constructor, builds a vector from a byte array
        ///
        /// <param name="byteArray">Byte array containing three four-byte floats</param>
        /// <param name="pos">Beginning position in the byte array</param>
        public Vector3(byte[] byteArray, int pos)
        {
            X = Y = Z = 0f;
            FromBytes(byteArray, pos);
        }

        public Vector3(Vector3 vector)
        {
            X = vector.X;
            Y = vector.Y;
            Z = vector.Z;
        }

        #endregion Constructors

        #region Public Methods

        public float Length()
        {
            return (float)Math.Sqrt(DistanceSquared(this, Zero));
        }

        public float LengthSquared()
        {
            return DistanceSquared(this, Zero);
        }

        public void Normalize()
        {
            this = Normalize(this);
        }

        ///
        /// Test if this vector is equal to another vector, within a given
        /// tolerance range
        ///
        /// <param name="vec">Vector to test against</param>
        /// <param name="tolerance">The acceptable magnitude of difference
        /// between the two vectors</param>
        /// <returns>True if the magnitude of difference between the two vectors
        /// is less than the given tolerance, otherwise false</returns>
        public bool ApproxEquals(Vector3 vec, float tolerance)
        {
            Vector3 diff = this - vec;
            return (diff.LengthSquared() <= tolerance * tolerance);
        }

        ///
        /// IComparable.CompareTo implementation
        ///
        public int CompareTo(Vector3 vector)
        {
            return Length().CompareTo(vector.Length());
        }

        ///
        /// Test if this vector is composed of all finite numbers
        ///
        public bool IsFinite()
        {
            return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));
        }

        ///
        /// Builds a vector from a byte array
        ///
        /// <param name="byteArray">Byte array containing a 12 byte vector</param>
        /// <param name="pos">Beginning position in the byte array</param>
        public void FromBytes(byte[] byteArray, int pos)
        {
            if (!BitConverter.IsLittleEndian)
            {
                // Big endian architecture
                byte[] conversionBuffer = new byte[12];

                Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);

                Array.Reverse(conversionBuffer, 0, 4);
                Array.Reverse(conversionBuffer, 4, 4);
                Array.Reverse(conversionBuffer, 8, 4);

                X = BitConverter.ToSingle(conversionBuffer, 0);
                Y = BitConverter.ToSingle(conversionBuffer, 4);
                Z = BitConverter.ToSingle(conversionBuffer, 8);
            }
            else
            {
                // Little endian architecture
                X = BitConverter.ToSingle(byteArray, pos);
                Y = BitConverter.ToSingle(byteArray, pos + 4);
                Z = BitConverter.ToSingle(byteArray, pos + 8);
            }
        }

        ///
        /// Returns the raw bytes for this vector
        ///
        /// <returns>A 12 byte array containing X, Y, and Z</returns>
        public byte[] GetBytes()
        {
            byte[] byteArray = new byte[12];
            ToBytes(byteArray, 0);
            return byteArray;
        }

        ///
        /// Writes the raw bytes for this vector to a byte array
        ///
        /// <param name="dest">Destination byte array</param>
        /// <param name="pos">Position in the destination array to start
        /// writing. Must be at least 12 bytes before the end of the array</param>
        public void ToBytes(byte[] dest, int pos)
        {
            Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4);

            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(dest, pos + 0, 4);
                Array.Reverse(dest, pos + 4, 4);
                Array.Reverse(dest, pos + 8, 4);
            }
        }

        #endregion Public Methods

        #region Static Methods

        public static Vector3 Add(Vector3 value1, Vector3 value2)
        {
            value1.X += value2.X;
            value1.Y += value2.Y;
            value1.Z += value2.Z;
            return value1;
        }

        public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)
        {
            return new Vector3(
                Utils.Clamp(value1.X, min.X, max.X),
                Utils.Clamp(value1.Y, min.Y, max.Y),
                Utils.Clamp(value1.Z, min.Z, max.Z));
        }

        public static Vector3 Cross(Vector3 value1, Vector3 value2)
        {
            return new Vector3(
                value1.Y * value2.Z - value2.Y * value1.Z,
                value1.Z * value2.X - value2.Z * value1.X,
                value1.X * value2.Y - value2.X * value1.Y);
        }

Answer: public static float Distance(Vector3 value1, Vector3 value2)

<think>
The code is inside the static methods region of the Vector3 struct. After the Cross method, the next logical static utility is the distance calculation between two vectors. In the OpenMetaverse Vector3 implementation, the method that follows Cross is the static Distance method, which starts with its signature. Therefore the next line is the method signature for Distance.
</think>
public static float Distance(Vector3 value1, Vector3 value2)


Context:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace System.IO
{
    /// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
    internal sealed partial class UnixFileSystem : FileSystem
    {
        public override int MaxPath { get { return Interop.Sys.MaxPath; } }

        public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }

        public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
        {
            return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
        }

        public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
        {
            // Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and
            // has varying degrees of support on different systems.

            // The destination path may just be a directory into which the file should be copied.
            // If it is, append the filename from the source onto the destination directory
            if (DirectoryExists(destFullPath))
            {
                destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
            }

            // Copy the contents of the file from the source to the destination, creating the destination in the process
            const int bufferSize = FileStream.DefaultBufferSize;
            const bool useAsync = false;
            using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))
            using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
            {
                src.CopyTo(dst);
            }

            // Now copy over relevant read/write/execute permissions from the source to the destination
            // Use Stat (not LStat) since permissions for symbolic links are meaninless and defer to permissions on the target
            Interop.Sys.FileStatus status;
            Interop.CheckIo(Interop.Sys.Stat(sourceFullPath, out status), sourceFullPath);
            int newMode = status.Mode & (int)Interop.Sys.Permissions.Mask;
            Interop.CheckIo(Interop.Sys.ChMod(destFullPath, newMode), destFullPath);
        }

        public override void MoveFile(string sourceFullPath, string destFullPath)
        {
            // The desired behavior for Move(source, dest) is to not overwrite the destination file
            // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
            // link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
            // as a Creation and Deletion instead of a Rename and thus differ from Windows.
            if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points
                {
                    CopyFile(sourceFullPath, destFullPath, overwrite: false);
                }
                else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
                {
                    // Windows distinguishes between whether the directory or the file isn't found,
                    // and throws a different exception in these cases.  We attempt to approximate that
                    // here; there is a race condition here, where something could change between
                    // when the error occurs and our checks, but it's the best we can do, and the
                    // worst case in such a race condition (which could occur if the file system is
                    // being manipulated concurrently with these checks) is that we throw a
                    // FileNotFoundException instead of DirectoryNotFoundexception.
                    throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);
                }
                else
                {
                    throw Interop.GetExceptionForIoErrno(errorInfo);
                }
            }
            DeleteFile(sourceFullPath);
        }

        public override void DeleteFile(string fullPath)
        {
            if (Interop.Sys.Unlink(fullPath) < 0)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                // ENOENT means it already doesn't exist; nop
                if (errorInfo.Error != Interop.Error.ENOENT)
                {
                    if (errorInfo.Error == Interop.Error.EISDIR)
                        errorInfo = Interop.Error.EACCES.Info();
                    throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
                }
            }
        }

        public override void CreateDirectory(string fullPath)
        {
            // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.

            int length = fullPath.Length;

            // We need to trim the trailing slash or the code will try to create 2 directories of the same name.
            if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
            {
                length--;
            }

            // For paths that are only // or ///
            if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
            {
                throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
            }

            // We can save a bunch of work if the directory we want to create already exists.
            if (DirectoryExists(fullPath))
            {
                return;
            }

            // Attempt to figure out which directories don't exist, and only create the ones we need.
            bool somepathexists = false;
            Stack<string> stackDir = new Stack<string>();
            int lengthRoot = PathInternal.GetRootLength(fullPath);
            if (length > lengthRoot)
            {
                int i = length - 1;
                while (i >= lengthRoot && !somepathexists)
                {
                    string dir = fullPath.Substring(0, i + 1);
                    if (!DirectoryExists(dir)) // Create only the ones missing
                    {
                        stackDir.Push(dir);
                    }
                    else
                    {
                        somepathexists = true;
                    }

                    while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
                    {
                        i--;
                    }
                    i--;
                }
            }

            int count = stackDir.Count;
            if (count == 0 && !somepathexists)
            {
                string root = Directory.InternalGetDirectoryRoot(fullPath);
                if (!DirectoryExists(root))
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
                }
                return;
            }

            // Create all the directories
            int result = 0;
            Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
            string errorString = fullPath;
            while (stackDir.Count > 0)
            {
                string name = stackDir.Pop();
                if (name.Length >= MaxDirectoryPath)
                {

Answer: throw new PathTooLongException(SR.IO_PathTooLong);

<think>
The code is inside the CreateDirectory method, iterating over directories to create. It checks if a directory name exceeds MaxDirectoryPath. The appropriate action is to throw a PathTooLongException with the standard resource message, matching the style used elsewhere in the file (e.g., IOException with SR.Format). Hence the next line is the throw statement.
</think>
throw new PathTooLongException(SR.IO_PathTooLong);


Context:
/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/domains/v1/domains.proto

package com.google.cloud.domains.v1;

/**
 *
 *
 *

 * Request for the `GetRegistration` method.
 *

 *
 * Protobuf type {@code google.cloud.domains.v1.GetRegistrationRequest}
 */
public final class GetRegistrationRequest extends com.google.protobuf.GeneratedMessageV3
    implements
    // @@protoc_insertion_point(message_implements:google.cloud.domains.v1.GetRegistrationRequest)
    GetRegistrationRequestOrBuilder {
  private static final long serialVersionUID = 0L;
  // Use GetRegistrationRequest.newBuilder() to construct.
  private GetRegistrationRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }

  private GetRegistrationRequest() {
    name_ = "";
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
    return new GetRegistrationRequest();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
    return this.unknownFields;
  }

  private GetRegistrationRequest(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new java.lang.NullPointerException();
    }
    com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder();
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          case 10:
            {
              java.lang.String s = input.readStringRequireUtf8();

              name_ = s;
              break;
            }
          default:
            {
              if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
    } finally {
      this.unknownFields = unknownFields.build();
      makeExtensionsImmutable();
    }
  }

  public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
    return com.google.cloud.domains.v1.DomainsProto
        .internal_static_google_cloud_domains_v1_GetRegistrationRequest_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.cloud.domains.v1.DomainsProto
        .internal_static_google_cloud_domains_v1_GetRegistrationRequest_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.cloud.domains.v1.GetRegistrationRequest.class,
            com.google.cloud.domains.v1.GetRegistrationRequest.Builder.class);
  }

  public static final int NAME_FIELD_NUMBER = 1;
  private volatile java.lang.Object name_;
  /**
   *
   *
   *

   * Required. The name of the `Registration` to get, in the format
   * `projects/*/locations/*/registrations/*`.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  @java.lang.Override
  public java.lang.String getName() {
    java.lang.Object ref = name_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      name_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * Required. The name of the `Registration` to get, in the format
   * `projects/*/locations/*/registrations/*`.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString getNameBytes() {
    java.lang.Object ref = name_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      name_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  private byte memoizedIsInitialized = -1;

  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
    }
    unknownFields.writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
    }
    size += unknownFields.getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof com.google.cloud.domains.v1.GetRegistrationRequest)) {
      return super.equals(obj);
    }
    com.google.cloud.domains.v1.GetRegistrationRequest other =
        (com.google.cloud.domains.v1.GetRegistrationRequest) obj;

    if (!getName().equals(other.getName())) return false;
    if (!unknownFields.equals(other.unknownFields)) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + NAME_FIELD_NUMBER;
    hash = (53 * hash) + getName().hashCode();
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseDelimitedFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseDelimitedFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      com.google.protobuf.CodedInputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() {
    return newBuilder();
  }

Answer: public static Builder newBuilder() {

<think>
The code is part of a protobuf-generated Java class. After the overridden newBuilderForType() method, the typical next member is the static newBuilder() method that returns a builder based on the default instance. This follows the standard pattern of protobuf message classes.
</think>
public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }


Context:
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""Base classes for our unit tests.

Allows overriding of flags for use of fakes, and some black magic for
inline callbacks.

"""

import eventlet  # noqa
eventlet.monkey_patch(os=False)

import abc
import contextlib
import copy
import datetime
import inspect
import os
import pprint
import sys

import fixtures
import mock
from oslo_cache import core as cache
from oslo_concurrency import lockutils
from oslo_config import cfg
from oslo_config import fixture as config_fixture
from oslo_log.fixture import logging_error as log_fixture
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import timeutils
from oslo_versionedobjects import fixture as ovo_fixture
from oslotest import moxstubout
import six
import testtools

from nova import context
from nova import db
from nova import exception
from nova.network import manager as network_manager
from nova.network.security_group import openstack_driver
from nova import objects
from nova.objects import base as objects_base
from nova.tests import fixtures as nova_fixtures
from nova.tests.unit import conf_fixture
from nova.tests.unit import policy_fixture
from nova.tests import uuidsentinel as uuids
from nova import utils

CONF = cfg.CONF

logging.register_options(CONF)
CONF.set_override('use_stderr', False)
logging.setup(CONF, 'nova')
cache.configure(CONF)

_TRUE_VALUES = ('True', 'true', '1', 'yes')
CELL1_NAME = 'cell1'

if six.PY2:
    nested = contextlib.nested
else:
    @contextlib.contextmanager
    def nested(*contexts):
        with contextlib.ExitStack() as stack:
            yield [stack.enter_context(c) for c in contexts]

class SampleNetworks(fixtures.Fixture):

    """Create sample networks in the database."""

    def __init__(self, host=None):
        self.host = host

    def setUp(self):
        super(SampleNetworks, self).setUp()
        ctxt = context.get_admin_context()
        network = network_manager.VlanManager(host=self.host)
        bridge_interface = CONF.flat_interface or CONF.vlan_interface
        network.create_networks(ctxt,
                                label='test',
                                cidr='10.0.0.0/8',
                                multi_host=CONF.multi_host,
                                num_networks=CONF.num_networks,
                                network_size=CONF.network_size,
                                cidr_v6=CONF.fixed_range_v6,
                                gateway=CONF.gateway,
                                gateway_v6=CONF.gateway_v6,
                                bridge=CONF.flat_network_bridge,
                                bridge_interface=bridge_interface,
                                vpn_start=CONF.vpn_start,
                                vlan_start=CONF.vlan_start,
                                dns1=CONF.flat_network_dns)
        for net in db.network_get_all(ctxt):
            network.set_network_host(ctxt, net)

class TestingException(Exception):
    pass

class skipIf(object):
    def __init__(self, condition, reason):
        self.condition = condition
        self.reason = reason

    def __call__(self, func_or_cls):
        condition = self.condition
        reason = self.reason
        if inspect.isfunction(func_or_cls):
            @six.wraps(func_or_cls)
            def wrapped(*args, **kwargs):
                if condition:
                    raise testtools.TestCase.skipException(reason)
                return func_or_cls(*args, **kwargs)

            return wrapped
        elif inspect.isclass(func_or_cls):
            orig_func = getattr(func_or_cls, 'setUp')

            @six.wraps(orig_func)
            def new_func(self, *args, **kwargs):
                if condition:
                    raise testtools.TestCase.skipException(reason)
                orig_func(self, *args, **kwargs)

            func_or_cls.setUp = new_func
            return func_or_cls
        else:
            raise TypeError('skipUnless can be used only with functions or '
                            'classes')

def _patch_mock_to_raise_for_invalid_assert_calls():
    def raise_for_invalid_assert_calls(wrapped):
        def wrapper(_self, name):
            valid_asserts = [
                'assert_called_with',
                'assert_called_once_with',
                'assert_has_calls',
                'assert_any_calls']

            if name.startswith('assert') and name not in valid_asserts:
                raise AttributeError('%s is not a valid mock assert method'
                                     % name)

            return wrapped(_self, name)
        return wrapper
    mock.Mock.__getattr__ = raise_for_invalid_assert_calls(
        mock.Mock.__getattr__)

# NOTE(gibi): needs to be called only once at import time
# to patch the mock lib
_patch_mock_to_raise_for_invalid_assert_calls()

class NovaExceptionReraiseFormatError(object):
    real_log_exception = exception.NovaException._log_exception

    @classmethod
    def patch(cls):
        exception.NovaException._log_exception = cls._wrap_log_exception

    @staticmethod
    def _wrap_log_exception(self):
        exc_info = sys.exc_info()
        NovaExceptionReraiseFormatError.real_log_exception(self)
        six.reraise(*exc_info)

# NOTE(melwitt) This needs to be done at import time in order to also catch
# NovaException format errors that are in mock decorators. In these cases, the
# errors will be raised during test listing, before tests actually run.
NovaExceptionReraiseFormatError.patch()

class TestCase(testtools.TestCase):
    """Test case base class for all unit tests.

    Due to the slowness of DB access, please consider deriving from
    `NoDBTestCase` first.
    """
    # USES_DB is set to False for tests that inherit from NoDBTestCase.
    USES_DB = True
    # USES_DB_SELF is set to True in tests that specifically want to use the
    # database but need to configure it themselves, for example to setup the
    # API DB but not the cell DB. In those cases the test will override
    # USES_DB_SELF = True but inherit from the NoDBTestCase class so it does
    # not get the default fixture setup when using a database (which is the
    # API and cell DBs, and adding the default flavors).
    USES_DB_SELF = False
    REQUIRES_LOCKING = False

    TIMEOUT_SCALING_FACTOR = 1

    def setUp(self):
        """Run before each test method to initialize test environment."""

Answer: super(TestCase, self).setUp()

<think>
The setUp method begins with a docstring. In typical unittest.TestCase subclasses, the first executable line is a call to the parent class's setUp to ensure proper initialization. The codebase uses Python 2/3 compatible super calls, so the next line should be super(TestCase, self).setUp().
</think>
super(TestCase, self).setUp()


Context:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v8/services/customer_client_link_service.proto

package com.google.ads.googleads.v8.services;

/**
 *

 * Request message for [CustomerClientLinkService.GetCustomerClientLink][google.ads.googleads.v8.services.CustomerClientLinkService.GetCustomerClientLink].
 *

 *
 * Protobuf type {@code google.ads.googleads.v8.services.GetCustomerClientLinkRequest}
 */
public final class GetCustomerClientLinkRequest extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:google.ads.googleads.v8.services.GetCustomerClientLinkRequest)
    GetCustomerClientLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
  // Use GetCustomerClientLinkRequest.newBuilder() to construct.
  private GetCustomerClientLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }
  private GetCustomerClientLinkRequest() {
    resourceName_ = "";
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(
      UnusedPrivateParameter unused) {
    return new GetCustomerClientLinkRequest();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return this.unknownFields;
  }
  private GetCustomerClientLinkRequest(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new java.lang.NullPointerException();
    }
    com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder();
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          case 10: {
            java.lang.String s = input.readStringRequireUtf8();

            resourceName_ = s;
            break;
          }
          default: {
            if (!parseUnknownField(
                input, unknownFields, extensionRegistry, tag)) {
              done = true;
            }
            break;
          }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(
          e).setUnfinishedMessage(this);
    } finally {
      this.unknownFields = unknownFields.build();
      makeExtensionsImmutable();
    }
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.class, com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.Builder.class);
  }

  public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
  private volatile java.lang.Object resourceName_;
  /**
   *

   * Required. The resource name of the customer client link to fetch.
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  @java.lang.Override
  public java.lang.String getResourceName() {
    java.lang.Object ref = resourceName_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      resourceName_ = s;
      return s;
    }
  }
  /**
   *

   * Required. The resource name of the customer client link to fetch.
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString
      getResourceNameBytes() {
    java.lang.Object ref = resourceName_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      resourceName_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  private byte memoizedIsInitialized = -1;
  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
    }
    unknownFields.writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
    }
    size += unknownFields.getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
     return true;
    }
    if (!(obj instanceof com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest)) {
      return super.equals(obj);
    }
    com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest other = (com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest) obj;

    if (!getResourceName()
        .equals(other.getResourceName())) return false;
    if (!unknownFields.equals(other.unknownFields)) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
    hash = (53 * hash) + getResourceName().hashCode();
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      java.nio.ByteBuffer data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  @java.lang.Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *

   * Request message for [CustomerClientLinkService.GetCustomerClientLink][google.ads.googleads.v8.services.CustomerClientLinkService.GetCustomerClientLink].
   *

   *
   * Protobuf type {@code google.ads.googleads.v8.services.GetCustomerClientLinkRequest}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.services.GetCustomerClientLinkRequest)
      com.google.ads.googleads.v8.services.GetCustomerClientLinkRequestOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.ads.googleads.v8.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v8_services_GetCustomerClientLinkRequest_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.class, com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.Builder.class);
    }

    // Construct using com.google.ads.googleads.v8.services.GetCustomerClientLinkRequest.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(

Answer: com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {

<think>
In protobuf generated Java classes, after the default private Builder() constructor, the next code defines the Builder that accepts a BuilderParent. The pattern is a constructor taking com.google.protobuf.GeneratedMessageV3.BuilderParent, calling super(parent) and maybeForceBuilderInitialization(). Therefore the next line is the constructor signature.
</think>
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {


Context:
/*

   Derby - Class org.apache.derby.impl.sql.compile.CoalesceFunctionNode

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */

package	org.apache.derby.impl.sql.compile;

import org.apache.derby.iapi.reference.ClassName;
import org.apache.derby.iapi.reference.SQLState;

import org.apache.derby.iapi.services.classfile.VMOpcode;

import org.apache.derby.iapi.services.sanity.SanityManager;

import org.apache.derby.iapi.error.StandardException;

import org.apache.derby.iapi.services.compiler.LocalField;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.sql.compile.Visitor;

import org.apache.derby.iapi.util.JBitSet;

import java.lang.reflect.Modifier;

import java.util.Vector;

/**
 * This node represents coalesce/value function which returns the first argument that is not null.
 * The arguments are evaluated in the order in which they are specified, and the result of the
 * function is the first argument that is not null. The result can be null only if all the arguments
 * can be null. The selected argument is converted, if necessary, to the attributes of the result.
 *
 *
 * SQL Reference Guide for DB2 has section titled "Rules for result data types" at the following url
 * http://publib.boulder.ibm.com/infocenter/db2help/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0008480.htm

 * I have constructed following table based on various tables and information under "Rules for result data types"
 * This table has FOR BIT DATA TYPES broken out into separate columns for clarity
 *
 * Note that are few differences between Derby and DB2
 * 1)there are few differences between what datatypes are consdiered compatible
 * In DB2, CHAR FOR BIT DATA datatypes are compatible with CHAR datatypes
 * ie in addition to following table, CHAR is compatible with CHAR FOR BIT DATA, VARCHAR FOR BIT DATA and LONG VARCHAR FOR BIT DATA
 * ie in addition to following table, VARCHAR is compatible with CHAR FOR BIT DATA, VARCHAR FOR BIT DATA and LONG VARCHAR FOR BIT DATA
 * ie in addition to following table, LONG VARCHAR is compatible with CHAR FOR BIT DATA, VARCHAR FOR BIT DATA and LONG VARCHAR FOR BIT DATA
 * ie in addition to following table, CHAR FOR BIT DATA is compatible with DATE, TIME, TIMESTAMP
 * ie in addition to following table, VARCHAR FOR BIT DATA is compatible with DATE, TIME, TIMESTAMP
 *
 * 2)few datatypes donot have matching precision in Derby and DB2
 * In DB2, precision of TIME is 8. In Derby, precision of TIME is 0.
 * In DB2, precision,scale of TIMESTAMP is 26,6. In Derby, precision of TIMESTAMP is 0,0.
 * In DB2, precision of DOUBLE is 15. In Derby, precision of DOUBLE is 52.
 * In DB2, precision of REAL is 23. In Derby, precision of REAL is 7.
 * In DB2, precision calculation equation is incorrect when we have int and decimal arguments.
 * The equation should be p=x+max(w-x,10) since precision of integer is 10 in both DB2 and Derby. Instead, DB2 has p=x+max(w-x,11)
 *
 * Types.             S  I  B  D  R  D  C  V  L  C  V  L  C  D  T  T  B
 *                    M  N  I  E  E  O  H  A  O  H  A  O  L  A  I  I  L
 *                    A  T  G  C  A  U  A  R  N  A  R  N  O  T  M  M  O
 *                    L  E  I  I  L  B  R  C  G  R  C  G  B  E  E  E  B
 *                    L  G  N  M     L     H  V  .  H  V           S
 *                    I  E  T  A     E     A  A  B  A  A           T
 *                    N  R     L           R  R  I  R  R           A
 *                    T                       C  T  .  .           M
 *                                            H     B  B           P
 *                                            A     I  I
 *                                            R     T   T
 * SMALLINT         { "SMALLINT", "INTEGER", "BIGINT", "DECIMAL", "DOUBLE", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },
 * INTEGER          { "INTEGER", "INTEGER", "BIGINT", "DECIMAL", "DOUBLE", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },
 * BIGINT           { "BIGINT", "BIGINT", "BIGINT", "DECIMAL", "DOUBLE", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },
 * DECIMAL          { "DECIMAL", "DECIMAL", "DECIMAL", "DECIMAL", "DOUBLE", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },
 * REAL             { "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "REAL", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },

Answer: * DOUBLE           { "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },

<think>
The snippet is a comment block listing rows of a type‑compatibility matrix for the CoalesceFunctionNode class. The last displayed row is for REAL and ends with a comma, indicating more rows follow. The next logical row is the one for DOUBLE, matching the pattern of the previous rows. Therefore the next line of code (still within the comment) should be the DOUBLE row of the matrix.
</think>
* DOUBLE            { "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "DOUBLE", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR", "ERROR" },


Context:
import logging
import multiprocessing
import os
import unittest.loader
from argparse import ArgumentParser
from contextlib import contextmanager
from importlib import import_module
from unittest import TestSuite, TextTestRunner, defaultTestLoader, mock

from django.db import connections
from django.test import SimpleTestCase
from django.test.runner import DiscoverRunner, get_max_test_processes
from django.test.utils import (
    NullTimeKeeper, TimeKeeper, captured_stderr, captured_stdout,
)

@contextmanager
def change_cwd(directory):
    current_dir = os.path.abspath(os.path.dirname(__file__))
    new_dir = os.path.join(current_dir, directory)
    old_cwd = os.getcwd()
    os.chdir(new_dir)
    try:
        yield
    finally:
        os.chdir(old_cwd)

@contextmanager
def change_loader_patterns(patterns):
    original_patterns = DiscoverRunner.test_loader.testNamePatterns
    DiscoverRunner.test_loader.testNamePatterns = patterns
    try:
        yield
    finally:
        DiscoverRunner.test_loader.testNamePatterns = original_patterns

# Isolate from the real environment.
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(multiprocessing, 'cpu_count', return_value=12)
# Python 3.8 on macOS defaults to 'spawn' mode.
@mock.patch.object(multiprocessing, 'get_start_method', return_value='fork')
class DiscoverRunnerParallelArgumentTests(SimpleTestCase):
    def get_parser(self):
        parser = ArgumentParser()
        DiscoverRunner.add_arguments(parser)
        return parser

    def test_parallel_default(self, *mocked_objects):
        result = self.get_parser().parse_args([])
        self.assertEqual(result.parallel, 0)

    def test_parallel_flag(self, *mocked_objects):
        result = self.get_parser().parse_args(['--parallel'])
        self.assertEqual(result.parallel, 'auto')

    def test_parallel_auto(self, *mocked_objects):
        result = self.get_parser().parse_args(['--parallel', 'auto'])
        self.assertEqual(result.parallel, 'auto')

    def test_parallel_count(self, *mocked_objects):
        result = self.get_parser().parse_args(['--parallel', '17'])
        self.assertEqual(result.parallel, 17)

    def test_parallel_invalid(self, *mocked_objects):
        with self.assertRaises(SystemExit), captured_stderr() as stderr:
            self.get_parser().parse_args(['--parallel', 'unaccepted'])
        msg = "argument --parallel: 'unaccepted' is not an integer or the string 'auto'"
        self.assertIn(msg, stderr.getvalue())

    def test_get_max_test_processes(self, *mocked_objects):
        self.assertEqual(get_max_test_processes(), 12)

    @mock.patch.dict(os.environ, {'DJANGO_TEST_PROCESSES': '7'})
    def test_get_max_test_processes_env_var(self, *mocked_objects):
        self.assertEqual(get_max_test_processes(), 7)

    def test_get_max_test_processes_spawn(
        self, mocked_get_start_method, mocked_cpu_count,
    ):
        mocked_get_start_method.return_value = 'spawn'
        self.assertEqual(get_max_test_processes(), 1)
        with mock.patch.dict(os.environ, {'DJANGO_TEST_PROCESSES': '7'}):
            self.assertEqual(get_max_test_processes(), 1)

class DiscoverRunnerTests(SimpleTestCase):

    @staticmethod
    def get_test_methods_names(suite):
        return [
            t.__class__.__name__ + '.' + t._testMethodName
            for t in suite._tests
        ]

    def test_init_debug_mode(self):
        runner = DiscoverRunner()
        self.assertFalse(runner.debug_mode)

    def test_add_arguments_shuffle(self):
        parser = ArgumentParser()
        DiscoverRunner.add_arguments(parser)
        ns = parser.parse_args([])
        self.assertIs(ns.shuffle, False)
        ns = parser.parse_args(['--shuffle'])
        self.assertIsNone(ns.shuffle)
        ns = parser.parse_args(['--shuffle', '5'])
        self.assertEqual(ns.shuffle, 5)

    def test_add_arguments_debug_mode(self):
        parser = ArgumentParser()
        DiscoverRunner.add_arguments(parser)

        ns = parser.parse_args([])
        self.assertFalse(ns.debug_mode)
        ns = parser.parse_args(["--debug-mode"])
        self.assertTrue(ns.debug_mode)

    def test_setup_shuffler_no_shuffle_argument(self):
        runner = DiscoverRunner()
        self.assertIs(runner.shuffle, False)
        runner.setup_shuffler()
        self.assertIsNone(runner.shuffle_seed)

    def test_setup_shuffler_shuffle_none(self):
        runner = DiscoverRunner(shuffle=None)
        self.assertIsNone(runner.shuffle)
        with mock.patch('random.randint', return_value=1):
            with captured_stdout() as stdout:
                runner.setup_shuffler()
        self.assertEqual(stdout.getvalue(), 'Using shuffle seed: 1 (generated)\n')
        self.assertEqual(runner.shuffle_seed, 1)

    def test_setup_shuffler_shuffle_int(self):
        runner = DiscoverRunner(shuffle=2)
        self.assertEqual(runner.shuffle, 2)
        with captured_stdout() as stdout:
            runner.setup_shuffler()
        expected_out = 'Using shuffle seed: 2 (given)\n'
        self.assertEqual(stdout.getvalue(), expected_out)
        self.assertEqual(runner.shuffle_seed, 2)

    def test_load_tests_for_label_file_path(self):
        with change_cwd('.'):
            msg = (
                "One of the test labels is a path to a file: "
                "'test_discover_runner.py', which is not supported. Use a "
                "dotted module name or path to a directory instead."
            )
            with self.assertRaisesMessage(RuntimeError, msg):
                DiscoverRunner().load_tests_for_label('test_discover_runner.py', {})

    def test_dotted_test_module(self):
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.tests_sample'],
        ).countTestCases()

        self.assertEqual(count, 4)

    def test_dotted_test_class_vanilla_unittest(self):
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.tests_sample.TestVanillaUnittest'],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_dotted_test_class_django_testcase(self):
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.tests_sample.TestDjangoTestCase'],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_dotted_test_method_django_testcase(self):
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.tests_sample.TestDjangoTestCase.test_sample'],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_pattern(self):
        count = DiscoverRunner(
            pattern="*_tests.py",
            verbosity=0,
        ).build_suite(['test_runner_apps.sample']).countTestCases()

        self.assertEqual(count, 1)

    def test_name_patterns(self):
        all_test_1 = [
            'DjangoCase1.test_1', 'DjangoCase2.test_1',
            'SimpleCase1.test_1', 'SimpleCase2.test_1',
            'UnittestCase1.test_1', 'UnittestCase2.test_1',
        ]
        all_test_2 = [
            'DjangoCase1.test_2', 'DjangoCase2.test_2',
            'SimpleCase1.test_2', 'SimpleCase2.test_2',
            'UnittestCase1.test_2', 'UnittestCase2.test_2',
        ]
        all_tests = sorted([*all_test_1, *all_test_2, 'UnittestCase2.test_3_test'])
        for pattern, expected in [
            [['test_1'], all_test_1],
            [['UnittestCase1'], ['UnittestCase1.test_1', 'UnittestCase1.test_2']],
            [['*test'], ['UnittestCase2.test_3_test']],
            [['test*'], all_tests],
            [['test'], all_tests],
            [['test_1', 'test_2'], sorted([*all_test_1, *all_test_2])],
            [['test*1'], all_test_1],
        ]:
            with self.subTest(pattern):
                suite = DiscoverRunner(
                    test_name_patterns=pattern,
                    verbosity=0,
                ).build_suite(['test_runner_apps.simple'])
                self.assertEqual(expected, self.get_test_methods_names(suite))

    def test_loader_patterns_not_mutated(self):
        runner = DiscoverRunner(test_name_patterns=['test_sample'], verbosity=0)
        tests = [
            ('test_runner_apps.sample.tests', 1),
            ('test_runner_apps.sample.tests.Test.test_sample', 1),
            ('test_runner_apps.sample.empty', 0),
            ('test_runner_apps.sample.tests_sample.EmptyTestCase', 0),
        ]
        for test_labels, tests_count in tests:
            with self.subTest(test_labels=test_labels):
                with change_loader_patterns(['UnittestCase1']):
                    count = runner.build_suite([test_labels]).countTestCases()
                    self.assertEqual(count, tests_count)
                    self.assertEqual(runner.test_loader.testNamePatterns, ['UnittestCase1'])

    def test_loader_patterns_not_mutated_when_test_label_is_file_path(self):
        runner = DiscoverRunner(test_name_patterns=['test_sample'], verbosity=0)
        with change_cwd('.'), change_loader_patterns(['UnittestCase1']):
            with self.assertRaises(RuntimeError):
                runner.build_suite(['test_discover_runner.py'])
            self.assertEqual(runner.test_loader.testNamePatterns, ['UnittestCase1'])

    def test_file_path(self):
        with change_cwd(".."):
            count = DiscoverRunner(verbosity=0).build_suite(
                ['test_runner_apps/sample/'],
            ).countTestCases()

        self.assertEqual(count, 5)

    def test_empty_label(self):
        """
        If the test label is empty, discovery should happen on the current
        working directory.
        """
        with change_cwd("."):
            suite = DiscoverRunner(verbosity=0).build_suite([])
            self.assertEqual(
                suite._tests[0].id().split(".")[0],
                os.path.basename(os.getcwd()),
            )

    def test_empty_test_case(self):
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.tests_sample.EmptyTestCase'],
        ).countTestCases()

        self.assertEqual(count, 0)

    def test_discovery_on_package(self):
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.tests'],
        ).countTestCases()

        self.assertEqual(count, 1)

    def test_ignore_adjacent(self):
        """
        When given a dotted path to a module, unittest discovery searches
        not just the module, but also the directory containing the module.

        This results in tests from adjacent modules being run when they
        should not. The discover runner avoids this behavior.
        """
        count = DiscoverRunner(verbosity=0).build_suite(
            ['test_runner_apps.sample.empty'],
        ).countTestCases()

        self.assertEqual(count, 0)

    def test_testcase_ordering(self):
        with change_cwd(".."):
            suite = DiscoverRunner(verbosity=0).build_suite(['test_runner_apps/sample/'])
            self.assertEqual(
                suite._tests[0].__class__.__name__,
                'TestDjangoTestCase',
                msg="TestDjangoTestCase should be the first test case")
            self.assertEqual(
                suite._tests[1].__class__.__name__,
                'TestZimpleTestCase',
                msg="TestZimpleTestCase should be the second test case")
            # All others can follow in unspecified order, including doctests
            self.assertIn('DocTestCase', [t.__class__.__name__ for t in suite._tests[2:]])

    def test_duplicates_ignored(self):
        """
        Tests shouldn't be discovered twice when discovering on overlapping paths.
        """
        base_app = 'forms_tests'
        sub_app = 'forms_tests.field_tests'
        runner = DiscoverRunner(verbosity=0)
        with self.modify_settings(INSTALLED_APPS={'append': sub_app}):
            single = runner.build_suite([base_app]).countTestCases()
            dups = runner.build_suite([base_app, sub_app]).countTestCases()
        self.assertEqual(single, dups)

    def test_reverse(self):
        """
        Reverse should reorder tests while maintaining the grouping specified
        by ``DiscoverRunner.reorder_by``.
        """
        runner = DiscoverRunner(reverse=True, verbosity=0)
        suite = runner.build_suite(
            test_labels=('test_runner_apps.sample', 'test_runner_apps.simple'))
        self.assertIn('test_runner_apps.simple', next(iter(suite)).id(),
                      msg="Test labels should be reversed.")
        suite = runner.build_suite(test_labels=('test_runner_apps.simple',))
        suite = tuple(suite)
        self.assertIn('DjangoCase', suite[0].id(),
                      msg="Test groups should not be reversed.")
        self.assertIn('SimpleCase', suite[4].id(),
                      msg="Test groups order should be preserved.")
        self.assertIn('DjangoCase2', suite[0].id(),
                      msg="Django test cases should be reversed.")
        self.assertIn('SimpleCase2', suite[4].id(),
                      msg="Simple test cases should be reversed.")
        self.assertIn('UnittestCase2', suite[8].id(),
                      msg="Unittest test cases should be reversed.")
        self.assertIn('test_2', suite[0].id(),
                      msg="Methods of Django cases should be reversed.")
        self.assertIn('test_2', suite[4].id(),
                      msg="Methods of simple cases should be reversed.")
        self.assertIn('test_2', suite[9].id(),
                      msg="Methods of unittest cases should be reversed.")

    def test_build_suite_failed_tests_first(self):
        # The "doesnotexist" label results in a _FailedTest instance.
        suite = DiscoverRunner(verbosity=0).build_suite(
            test_labels=['test_runner_apps.sample', 'doesnotexist'],
        )
        tests = list(suite)
        self.assertIsInstance(tests[0], unittest.loader._FailedTest)
        self.assertNotIsInstance(tests[-1], unittest.loader._FailedTest)

    def test_build_suite_shuffling(self):
        # These will result in unittest.loader._FailedTest instances rather
        # than TestCase objects, but they are sufficient for testing.
        labels = ['label1', 'label2', 'label3', 'label4']
        cases = [
            ({}, ['label1', 'label2', 'label3', 'label4']),

Answer: ({'reverse': True}, ['label4', 'label3', 'label2', 'label1']),

<think>
The test is defining a list of cases to verify suite ordering with and without shuffling. The first case (empty dict) expects the original label order. The second case should enable shuffling, and the test will mock random.shuffle to reverse the list, so the expected order is the reverse of the original. Therefore the next line adds the tuple for the shuffled case.
</think>
({'shuffle': True}, ['label4', 'label3', 'label2', 'label1']),


Context:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.ignite.internal.processors.cache.query;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.events.DiscoveryEvent;
import org.apache.ignite.events.Event;
import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.managers.communication.GridIoPolicy;
import org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener;
import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
import org.apache.ignite.internal.util.GridBoundedConcurrentOrderedSet;
import org.apache.ignite.internal.util.GridCloseableIteratorAdapter;
import org.apache.ignite.internal.util.lang.GridCloseableIterator;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.CI2;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgniteClosure;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.lang.IgniteReducer;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.ConcurrentHashMap;

import static org.apache.ignite.cache.CacheMode.LOCAL;
import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;
import static org.apache.ignite.internal.GridTopic.TOPIC_CACHE;

/**
 * Distributed query manager (for cache in REPLICATED / PARTITIONED cache mode).
 */
public class GridCacheDistributedQueryManager<K, V> extends GridCacheQueryManager<K, V> {
    /** */
    private static final int MAX_CANCEL_IDS = 1000;

    /** Query response frequency. */
    private static final long RESEND_FREQ = 3000;

    /** Query response attempts. */
    private static final int RESEND_ATTEMPTS = 5;

    /** Prefix for communication topic. */
    private static final String TOPIC_PREFIX = "QUERY";

    /** {request ID -> thread} */
    private ConcurrentMap<Long, Thread> threads = new ConcurrentHashMap<>();

    /** {request ID -> future} */
    private ConcurrentMap<Long, GridCacheDistributedQueryFuture<?, ?, ?>> futs =
        new ConcurrentHashMap<>();

    /** Received requests to cancel. */
    private Collection<CancelMessageId> cancelIds =
        new GridBoundedConcurrentOrderedSet<>(MAX_CANCEL_IDS);

    /** Canceled queries. */
    private Collection<Long> cancelled = new GridBoundedConcurrentOrderedSet<>(MAX_CANCEL_IDS);

    /** Query response handler. */
    private IgniteBiInClosure<UUID,GridCacheQueryResponse> resHnd = new CI2<UUID, GridCacheQueryResponse>() {
        @Override public void apply(UUID nodeId, GridCacheQueryResponse res) {
            processQueryResponse(nodeId, res);
        }
    };

    /** Event listener. */
    private GridLocalEventListener lsnr;

    /** {@inheritDoc} */
    @Override public void start0() throws IgniteCheckedException {
        super.start0();

        assert cctx.config().getCacheMode() != LOCAL;

        cctx.io().addCacheHandler(cctx.cacheId(), GridCacheQueryRequest.class, new CI2<UUID, GridCacheQueryRequest>() {
            @Override public void apply(UUID nodeId, GridCacheQueryRequest req) {
                processQueryRequest(nodeId, req);
            }
        });

        lsnr = new GridLocalEventListener() {
            @Override public void onEvent(Event evt) {
                DiscoveryEvent discoEvt = (DiscoveryEvent)evt;

                for (GridCacheDistributedQueryFuture fut : futs.values())
                    fut.onNodeLeft(discoEvt.eventNode().id());
            }
        };

        cctx.events().addListener(lsnr, EVT_NODE_LEFT, EVT_NODE_FAILED);
    }

    /** {@inheritDoc} */
    @Override protected void onKernalStop0(boolean cancel) {
        super.onKernalStop0(cancel);

        cctx.events().removeListener(lsnr);
    }

    /** {@inheritDoc} */
    @Override public void onDisconnected(IgniteFuture<?> reconnectFut) {
        IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException(reconnectFut,
            "Query was cancelled, client node disconnected.");

        for (Map.Entry<Long, GridCacheDistributedQueryFuture<?, ?, ?>> e : futs.entrySet()) {
            GridCacheDistributedQueryFuture<?, ?, ?> fut = e.getValue();

            fut.onPage(null, null, err, true);

            futs.remove(e.getKey(), fut);
        }
    }

    /** {@inheritDoc} */
    @Override public void printMemoryStats() {
        super.printMemoryStats();

        X.println(">>>   threadsSize: " + threads.size());
        X.println(">>>   futsSize: " + futs.size());
    }

    /**
     * Removes query future from futures map.
     *
     * @param reqId Request id.
     * @param fut Query future.
     */
    protected void addQueryFuture(long reqId, GridCacheDistributedQueryFuture<?, ?, ?> fut) {
        futs.put(reqId, fut);

        if (cctx.kernalContext().clientDisconnected()) {
            IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException(
                cctx.kernalContext().cluster().clientReconnectFuture(),
                "Query was cancelled, client node disconnected.");

            fut.onDone(err);
        }
    }

    /**
     * Removes query future from futures map.
     *
     * @param reqId Request id.
     */
    protected void removeQueryFuture(long reqId) {
        futs.remove(reqId);
    }

    /**
     * Gets query future from futures map.
     *
     * @param reqId Request id.
     * @return Found future or null.
     */
    protected GridCacheDistributedQueryFuture<?, ?, ?> getQueryFuture(long reqId) {
        return futs.get(reqId);
    }

    /**
     * Processes cache query request.
     *
     * @param sndId Sender node id.
     * @param req Query request.
     */
    @SuppressWarnings("unchecked")
    @Override void processQueryRequest(UUID sndId, GridCacheQueryRequest req) {
        if (req.cancel()) {
            cancelIds.add(new CancelMessageId(req.id(), sndId));

            if (req.fields())
                removeFieldsQueryResult(sndId, req.id());
            else
                removeQueryResult(sndId, req.id());
        }
        else {
            if (!cancelIds.contains(new CancelMessageId(req.id(), sndId))) {
                if (!F.eq(req.cacheName(), cctx.name())) {
                    GridCacheQueryResponse res = new GridCacheQueryResponse(
                        cctx.cacheId(),
                        req.id(),
                        new IgniteCheckedException("Received request for incorrect cache [expected=" + cctx.name() +
                            ", actual=" + req.cacheName()),
                        cctx.deploymentEnabled());

                    sendQueryResponse(sndId, res, 0);
                }
                else {
                    threads.put(req.id(), Thread.currentThread());

                    try {
                        GridCacheQueryInfo info = distributedQueryInfo(sndId, req);

                        if (info == null)
                            return;

                        if (req.fields())
                            runFieldsQuery(info);
                        else
                            runQuery(info);
                    }
                    catch (Throwable e) {
                        U.error(log(), "Failed to run query.", e);

                        sendQueryResponse(sndId, new GridCacheQueryResponse(cctx.cacheId(), req.id(), e.getCause(),
                            cctx.deploymentEnabled()), 0);

                        if (e instanceof Error)
                            throw (Error)e;
                    }
                    finally {
                        threads.remove(req.id());
                    }
                }
            }
        }
    }

    /**
     * @param sndId Sender node id.
     * @param req Query request.
     * @return Query info.
     */
    @Nullable private GridCacheQueryInfo distributedQueryInfo(UUID sndId, GridCacheQueryRequest req) {
        IgniteReducer<Object, Object> rdc = req.reducer();
        IgniteClosure<Object, Object> trans = (IgniteClosure<Object, Object>)req.transformer();

        ClusterNode sndNode = cctx.node(sndId);

        if (sndNode == null)
            return null;

        GridCacheQueryAdapter<?> qry =
            new GridCacheQueryAdapter<>(
                cctx,
                req.type(),
                log,
                req.pageSize(),
                0,
                req.includeBackups(),
                false,
                null,
                req.keyValueFilter(),
                req.partition() == -1 ? null : req.partition(),
                req.className(),
                req.clause(),
                req.includeMetaData(),
                req.keepBinary(),
                req.subjectId(),
                req.taskHash()
            );

        return new GridCacheQueryInfo(
            false,
            trans,
            rdc,
            qry,
            null,
            sndId,
            req.id(),
            req.includeMetaData(),
            req.allPages(),
            req.arguments()
        );
    }

    /**
     * Sends cache query response.
     *
     * @param nodeId Node to send response.
     * @param res Cache query response.
     * @param timeout Message timeout.
     * @return {@code true} if response was sent, {@code false} otherwise.
     */

Answer: private boolean sendQueryResponse(UUID nodeId, GridCacheQueryResponse res, long timeout) {

<think>
The comment describes a method that sends a cache query response, taking a node ID, a response object, and a timeout, and returning a boolean indicating success. The code later calls sendQueryResponse(sndId, res, 0), so the next line should be the method signature matching those parameters and return type.
</think>
private boolean sendQueryResponse(UUID nodeId, GridCacheQueryResponse res, long timeout) {