Context:
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
#     NScD Oak Ridge National Laboratory, European Spallation Source
#     & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#
from __future__ import (absolute_import, division, print_function)

import datetime
import unittest

import matplotlib
import numpy as np

import mantid.api
import mantid.plots.helperfunctions as funcs
from mantid.py3compat.mock import Mock
from mantid.kernel import config
from mantid.plots.utility import MantidAxType
from mantid.simpleapi import AddTimeSeriesLog, ConjoinWorkspaces, CreateMDHistoWorkspace, CreateSampleWorkspace, \
    CreateSingleValuedWorkspace, CreateWorkspace, DeleteWorkspace

matplotlib.use('AGG')

def add_workspace_with_data(func):
    def wrapper(self):
        dataX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
        dataY = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        dataE = dataY
        dX = dataY

        ws = CreateWorkspace(DataX=dataX, DataY=dataY, DataE=dataE, NSpec=4, UnitX="Wavelength", Dx=dX)
        return func(self, ws)

    return wrapper

def add_md_workspace_with_data(dimensions=2):
    def function_wrapper(func):
        def wrapper(self):
            if dimensions == 2:
                S = range(0, 100)
                ERR = range(0, 100)
                mdws = CreateMDHistoWorkspace(Dimensionality=2, Extents='-3,3,-10,10', SignalInput=S, ErrorInput=ERR,
                                              NumberOfBins='10,10', Names='Dim1,Dim2',
                                              Units='MomentumTransfer,EnergyTransfer')
            else:
                S = range(0, 1000)
                ERR = range(0, 1000)
                mdws = CreateMDHistoWorkspace(Dimensionality=3, Extents='-3,3,-10,10,-20,20', SignalInput=S,
                                              ErrorInput=ERR,
                                              NumberOfBins='10,10,10', Names='Dim1,Dim2,Dim3',
                                              Units='MomentumTransfer,EnergyTransfer,EnergyTransfer')
            return func(self, mdws)

        return wrapper

    return function_wrapper

class HelperFunctionsTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.g1da = config['graph1d.autodistribution']
        config['graph1d.autodistribution'] = 'On'
        cls.ws2d_histo = CreateWorkspace(DataX=[10, 20, 30, 10, 20, 30],
                                         DataY=[2, 3, 4, 5],
                                         DataE=[1, 2, 3, 4],
                                         NSpec=2,
                                         Distribution=True,
                                         UnitX='Wavelength',
                                         VerticalAxisUnit='DeltaE',
                                         VerticalAxisValues=[4, 6, 8],
                                         OutputWorkspace='ws2d_histo')
        cls.ws2d_point = CreateWorkspace(DataX=[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
                                         DataY=[2] * 12,
                                         NSpec=3,
                                         OutputWorkspace='ws2d_point')
        cls.ws1d_point = CreateWorkspace(DataX=[1, 2],
                                         DataY=[1, 2],
                                         NSpec=1,
                                         Distribution=False,
                                         OutputWorkspace='ws1d_point')
        cls.ws2d_histo_rag = CreateWorkspace(DataX=[1, 2, 3, 4, 5, 2, 4, 6, 8, 10],
                                             DataY=[2] * 8,
                                             NSpec=2,
                                             VerticalAxisUnit='DeltaE',
                                             VerticalAxisValues=[5, 7, 9],
                                             OutputWorkspace='ws2d_histo_rag')
        cls.ws2d_point_rag = CreateWorkspace(DataX=[1, 2, 3, 4, 2, 4, 6, 8],
                                             DataY=[2] * 8,
                                             NSpec=2,
                                             OutputWorkspace='ws2d_point_rag')
        cls.ws_MD_2d = CreateMDHistoWorkspace(Dimensionality=3,
                                              Extents='-3,3,-10,10,-1,1',
                                              SignalInput=range(25),
                                              ErrorInput=range(25),
                                              NumberOfEvents=10 * np.ones(25),
                                              NumberOfBins='5,5,1',
                                              Names='Dim1,Dim2,Dim3',
                                              Units='MomentumTransfer,EnergyTransfer,Angstrom',
                                              OutputWorkspace='ws_MD_2d')
        cls.ws_MD_1d = CreateMDHistoWorkspace(Dimensionality=3,
                                              Extents='-3,3,-10,10,-1,1',
                                              SignalInput=range(5),
                                              ErrorInput=range(5),
                                              NumberOfEvents=10 * np.ones(5),
                                              NumberOfBins='1,5,1',
                                              Names='Dim1,Dim2,Dim3',
                                              Units='MomentumTransfer,EnergyTransfer,Angstrom',
                                              OutputWorkspace='ws_MD_1d')
        cls.ws2d_point_uneven = CreateWorkspace(DataX=[10, 20, 30],
                                                DataY=[1, 2, 3],
                                                NSpec=1,
                                                OutputWorkspace='ws2d_point_uneven')
        wp = CreateWorkspace(DataX=[15, 25, 35, 45], DataY=[1, 2, 3, 4], NSpec=1)
        ConjoinWorkspaces(cls.ws2d_point_uneven, wp, CheckOverlapping=False)
        cls.ws2d_point_uneven = mantid.mtd['ws2d_point_uneven']
        cls.ws2d_histo_uneven = CreateWorkspace(DataX=[10, 20, 30, 40],
                                                DataY=[1, 2, 3],
                                                NSpec=1,
                                                OutputWorkspace='ws2d_histo_uneven')
        wp = CreateWorkspace(DataX=[15, 25, 35, 45, 55], DataY=[1, 2, 3, 4], NSpec=1)
        ConjoinWorkspaces(cls.ws2d_histo_uneven, wp, CheckOverlapping=False)
        cls.ws2d_histo_uneven = mantid.mtd['ws2d_histo_uneven']
        newYAxis = mantid.api.NumericAxis.create(3)
        newYAxis.setValue(0, 10)
        newYAxis.setValue(1, 15)
        newYAxis.setValue(2, 25)
        cls.ws2d_histo_uneven.replaceAxis(1, newYAxis)
        AddTimeSeriesLog(cls.ws2d_histo, Name="my_log", Time="2010-01-01T00:00:00", Value=100)
        AddTimeSeriesLog(cls.ws2d_histo, Name="my_log", Time="2010-01-01T00:30:00", Value=15)
        AddTimeSeriesLog(cls.ws2d_histo, Name="my_log", Time="2010-01-01T00:50:00", Value=100.2)

    @classmethod
    def tearDownClass(cls):
        config['graph1d.autodistribution'] = cls.g1da
        DeleteWorkspace('ws2d_histo')
        DeleteWorkspace('ws2d_point')
        DeleteWorkspace('ws1d_point')
        DeleteWorkspace('ws_MD_2d')
        DeleteWorkspace('ws_MD_1d')
        DeleteWorkspace('ws2d_histo_rag')
        DeleteWorkspace('ws2d_point_rag')
        DeleteWorkspace('ws2d_point_uneven')
        DeleteWorkspace('ws2d_histo_uneven')

    def test_get_wksp_index_dist_and_label(self):
        # fail case
        self.assertRaises(RuntimeError, funcs.get_wksp_index_dist_and_label, self.ws2d_histo)
        # get info from a 2d workspace
        index, dist, kwargs = funcs.get_wksp_index_dist_and_label(self.ws2d_histo, specNum=2)
        self.assertEqual(index, 1)
        self.assertTrue(dist)
        self.assertEqual(kwargs['label'], 'ws2d_histo: spec 2')
        # get info from default spectrum in the 1d case
        index, dist, kwargs = funcs.get_wksp_index_dist_and_label(self.ws1d_point)
        self.assertEqual(index, 0)
        self.assertFalse(dist)
        self.assertEqual(kwargs['label'], 'ws1d_point: spec 1')

    def test_get_axes_labels(self):
        axs = funcs.get_axes_labels(self.ws2d_histo)
        self.assertEqual(axs, ('', 'Wavelength ($\\AA$)', 'Energy transfer ($meV$)'))

    def test_get_axes_label_2d_MDWS(self):
        axs = funcs.get_axes_labels(self.ws_MD_2d)
        # should get the first two dimension labels only
        self.assertEqual(axs, ('Intensity', 'Dim1 ($\\AA^{-1}$)', 'Dim2 (EnergyTransfer)'))

    def test_get_data_uneven_flag(self):
        flag, kwargs = funcs.get_data_uneven_flag(self.ws2d_histo_rag, axisaligned=True, other_kwarg=1)
        self.assertTrue(flag)
        self.assertEquals(kwargs, {'other_kwarg': 1})
        flag, kwargs = funcs.get_data_uneven_flag(self.ws2d_histo_rag, other_kwarg=2)
        self.assertFalse(flag)
        self.assertEquals(kwargs, {'other_kwarg': 2})
        flag, kwargs = funcs.get_data_uneven_flag(self.ws2d_histo_uneven, axisaligned=False, other_kwarg=3)
        self.assertTrue(flag)
        self.assertEquals(kwargs, {'other_kwarg': 3})

    def test_boundaries_from_points(self):
        centers = np.array([1., 2., 4., 8.])
        bounds = funcs.boundaries_from_points(centers)
        self.assertTrue(np.array_equal(bounds, np.array([0.5, 1.5, 3, 6, 10])))

    def test_points_from_boundaries(self):
        bounds = np.array([1., 3, 4, 10])
        centers = funcs.points_from_boundaries(bounds)
        self.assertTrue(np.array_equal(centers, np.array([2., 3.5, 7])))

    def test_get_spectrum(self):
        # get data divided by bin width
        x, y, dy, dx = funcs.get_spectrum(self.ws2d_histo, 1, False, withDy=True, withDx=True)
        self.assertTrue(np.array_equal(x, np.array([15., 25.])))
        self.assertTrue(np.array_equal(y, np.array([.4, .5])))
        self.assertTrue(np.array_equal(dy, np.array([.3, .4])))
        self.assertEqual(dx, None)
        # get data not divided by bin width
        x, y, dy, dx = funcs.get_spectrum(self.ws2d_histo, 0, True, withDy=True, withDx=True)
        self.assertTrue(np.array_equal(x, np.array([15., 25.])))
        self.assertTrue(np.array_equal(y, np.array([2, 3])))
        self.assertTrue(np.array_equal(dy, np.array([1, 2])))
        self.assertEqual(dx, None)
        # fail case - try to find spectrum out of range
        self.assertRaises(RuntimeError, funcs.get_spectrum, self.ws2d_histo, 10, True)

    def test_get_md_data2d_bin_bounds(self):
        x, y, data = funcs.get_md_data2d_bin_bounds(self.ws_MD_2d, mantid.api.MDNormalization.NoNormalization)
        # logger.error(str(coords))
        np.testing.assert_allclose(x, np.array([-3, -1.8, -0.6, 0.6, 1.8, 3]), atol=1e-10)
        np.testing.assert_allclose(y, np.array([-10, -6, -2, 2, 6, 10.]), atol=1e-10)
        np.testing.assert_allclose(data, np.arange(25).reshape(5, 5), atol=1e-10)

    def test_get_md_data2d_bin_centers(self):
        x, y, data = funcs.get_md_data2d_bin_centers(self.ws_MD_2d, mantid.api.MDNormalization.NumEventsNormalization)
        np.testing.assert_allclose(x, np.array([-2.4, -1.2, 0, 1.2, 2.4]), atol=1e-10)
        np.testing.assert_allclose(y, np.array([-8, -4, 0, 4, 8]), atol=1e-10)
        np.testing.assert_allclose(data, np.arange(25).reshape(5, 5) * 0.1, atol=1e-10)

    def test_get_md_data1d(self):
        coords, data, err = funcs.get_md_data1d(self.ws_MD_1d, mantid.api.MDNormalization.NumEventsNormalization)
        np.testing.assert_allclose(coords, np.array([-8, -4, 0, 4, 8]), atol=1e-10)

    def test_get_matrix_2d_data_rect(self):
        # contour from aligned point data
        x, y, z = funcs.get_matrix_2d_data(self.ws2d_point, True, histogram2D=False)
        np.testing.assert_allclose(x, np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]))
        np.testing.assert_allclose(y, np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]))
        # mesh from aligned point data
        x, y, z = funcs.get_matrix_2d_data(self.ws2d_point, True, histogram2D=True)
        np.testing.assert_allclose(x, np.array(
            [[0.5, 1.5, 2.5, 3.5, 4.5], [0.5, 1.5, 2.5, 3.5, 4.5], [0.5, 1.5, 2.5, 3.5, 4.5],
             [0.5, 1.5, 2.5, 3.5, 4.5]]))
        np.testing.assert_allclose(y, np.array(
            [[0.5, 0.5, 0.5, 0.5, 0.5], [1.5, 1.5, 1.5, 1.5, 1.5], [2.5, 2.5, 2.5, 2.5, 2.5],
             [3.5, 3.5, 3.5, 3.5, 3.5]]))
        # contour from aligned histo data
        x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=False)
        np.testing.assert_allclose(x, np.array([[15, 25], [15, 25]]))
        np.testing.assert_allclose(y, np.array([[5, 5], [7, 7]]))
        # mesh from aligned histo data

Answer: x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=True)

<think>
After the comment '# mesh from aligned histo data', the test should call the same helper function with the histogram workspace and histogram2D=True, mirroring the previous pattern for point data. The next line therefore invokes funcs.get_matrix_2d_data on self.ws2d_histo with the appropriate flags.
</think>
x, y, z = funcs.get_matrix_2d_data(self.ws2d_histo, True, histogram2D=True)


Context:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.RecoveryServices;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for ReplicationStorageClassificationMappingsOperations.
    /// </summary>
    public static partial class ReplicationStorageClassificationMappingsOperationsExtensions
    {
            /// <summary>
            /// Gets the details of a storage classification mapping.
            /// </summary>
            /// <remarks>
            /// Gets the details of the specified storage classification mapping.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classification name.
            /// </param>
            /// <param name='storageClassificationMappingName'>
            /// Storage classification mapping name.
            /// </param>
            public static StorageClassificationMapping Get(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)
            {
                return operations.GetAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets the details of a storage classification mapping.
            /// </summary>
            /// <remarks>
            /// Gets the details of the specified storage classification mapping.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classification name.
            /// </param>
            /// <param name='storageClassificationMappingName'>
            /// Storage classification mapping name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<StorageClassificationMapping> GetAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Create storage classification mapping.
            /// </summary>
            /// <remarks>
            /// The operation to create a storage classification mapping.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classification name.
            /// </param>
            /// <param name='storageClassificationMappingName'>
            /// Storage classification mapping name.
            /// </param>
            /// <param name='pairingInput'>
            /// Pairing input.
            /// </param>
            public static StorageClassificationMapping Create(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput)
            {
                return operations.CreateAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Create storage classification mapping.
            /// </summary>
            /// <remarks>
            /// The operation to create a storage classification mapping.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classification name.
            /// </param>
            /// <param name='storageClassificationMappingName'>
            /// Storage classification mapping name.
            /// </param>
            /// <param name='pairingInput'>
            /// Pairing input.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<StorageClassificationMapping> CreateAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Delete a storage classification mapping.
            /// </summary>
            /// <remarks>
            /// The operation to delete a storage classification mapping.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classification name.
            /// </param>
            /// <param name='storageClassificationMappingName'>
            /// Storage classification mapping name.
            /// </param>
            public static void Delete(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)
            {
                operations.DeleteAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Delete a storage classification mapping.
            /// </summary>
            /// <remarks>
            /// The operation to delete a storage classification mapping.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classification name.
            /// </param>
            /// <param name='storageClassificationMappingName'>
            /// Storage classification mapping name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task DeleteAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.DeleteWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Gets the list of storage classification mappings objects under a storage.
            /// </summary>
            /// <remarks>
            /// Lists the storage classification mappings for the fabric.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classfication name.
            /// </param>
            public static IPage<StorageClassificationMapping> ListByReplicationStorageClassifications(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName)
            {
                return operations.ListByReplicationStorageClassificationsAsync(fabricName, storageClassificationName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets the list of storage classification mappings objects under a storage.
            /// </summary>
            /// <remarks>
            /// Lists the storage classification mappings for the fabric.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='fabricName'>
            /// Fabric name.
            /// </param>
            /// <param name='storageClassificationName'>
            /// Storage classfication name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>

Answer: public static async Task<IPage<StorageClassificationMapping>> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))

<think>
The code defines a synchronous ListByReplicationStorageClassifications method that calls an async counterpart. The comment block just above ends with the cancellationToken param, so the next line should be the async method signature that includes the cancellation token with a default value, matching the pattern of other async methods in the file.
</think>
public static async Task<IPage<StorageClassificationMapping>> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))


Context:
#!/usr/bin/python
#======================================================================
#
# Project	 : hpp_IOStressTest
# File 		 : Libs/IOST_Testcase/IOST_WSetupTestcase.py
# Date		 : Sep 27, 2016
# Author	 : HuuHoang Nguyen
# Contact	 : hhnguyen@apm.com
#            : hoangnh.hpp@gmail.com
# License    : MIT License
# Copyright  : 2016
# Description: The hpp_IOStressTest is under the MIT License, a copy of license which may be found in LICENSE
#
#======================================================================

import io
import os
import re
import operator
import sys
import base64
import time
from pprint import pprint

from IOST_Basic         import *
from IOST_Config        import *
from IOST_Terminal      import *

import gtk
import gtk.glade
import gobject
import pango
import vte

#======================================================================
try:
    IOST_DBG_EN
    if IOST_DBG_EN:
        IOST_WSetupTestcase_DebugEnable =1
        IOST_WSetupTestcase_DebugLevel  = IOST_DBG_L06
    else:
        IOST_WSetupTestcase_DebugEnable =0
        IOST_WSetupTestcase_DebugLevel  = IOST_DBG_L01
except:
    IOST_DBG_EN = False
    IOST_WSetupTestcase_DebugEnable =0
    IOST_WSetupTestcase_DebugLevel  = IOST_DBG_L01

#======================================================================
class IOST_WSetupTestcase():
    """
    """
    def __init__(self, glade_filename, window_name, object_name, builder=None ):
        ""
        self.IOST_WSetupTestcas_glade_filename = glade_filename
        self.IOST_WSetupTestcase_window = window_name
        self.IOST_WSetupTestcase_object = object_name

        if not builder:
            self.WRun_WSetupTestcase_Builder = gtk.Builder()
            self.WRun_WSetupTestcase_Builder.add_from_file(glade_filename)
            self.WRun_WSetupTestcase_Builder.connect_signals(self)
        else:
            self.WRun_WSetupTestcase_Builder = builder

        # self.IOST_Objs[window_name][window_name+object_name]  = self.WRun_WSetupTestcase_Builder.get_object(window_name+object_name)

    #----------------------------------------------------------------------
    def WSetupTestcase_Get_Objs(self, window_name):
        ""
        # self.CreateObjs(self.IOST_Objs[window_name], self.WRun_WSetupTestcase_Builder, 2)

        self.CreateObjsDictFromDict(window_name, self.IOST_Objs[window_name], self.WRun_WSetupTestcase_Builder, 0)

        if IOST_WSetupTestcase_DebugEnable and 0:
            pprint(self.IOST_Objs[window_name])

    #----------------------------------------------------------------------
    def WSetupTestcase_Clear(self, window_name):
        """
        """
        self.IOST_Objs[window_name]["_SelectAll_CB"].set_active(False)
        self.IOST_Objs[window_name]["_ResetAll_CB"].set_active(False)
        for i in range(0, self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseListDefault"] ):
            # print "At horizontal ", i
            # print window_name+"_"+str(i+1)+"_Enable_CB"
            self.IOST_Objs[window_name]["_"+str(i+1)+"_Enable_CB"].set_sensitive(False)
            self.IOST_Objs[window_name]["_"+str(i+1)+"_Enable_CB"].set_active(False)
            self.IOST_Objs[window_name]["_"+str(i+1)+"_Cmd_TE"].set_text("")
            self.IOST_Objs[window_name]["_"+str(i+1)+"_Description_TE"].set_text("")
            self.IOST_Objs[window_name]["_"+str(i+1)+"_RunTimes_TE"].set_text("")
            self.IOST_Objs[window_name]["_"+str(i+1)+"_ResetBoard_CB"].set_active(False)
            self.IOST_Objs[window_name]["_"+str(i+1)+"_ResetBoard_CB"].set_sensitive(False)

    #----------------------------------------------------------------------
    def WSetupTestcase_SetCallback(self, window_name, object_name, number):
        """
        """
        # for i in range(0, self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]):
        self.IOST_Objs[window_name]["_"+str(number)+"_Enable_CB"].connect('toggled', \
        self.WSetupTestcase_Enable_CB_Callback, \
        self.IOST_Objs[window_name]["_"+str(number)+"_Enable_CB"], \
        object_name, number)

        self.IOST_Objs[window_name]["_"+str(number)+"_Cmd_TE"].connect('focus-out-event', \
        self.WSetupTestcase_CMD_TE_Callback, \
        self.IOST_Objs[window_name]["_"+str(number)+"_Cmd_TE"], \
        object_name, number, self.IOST_Objs[window_name]["_"+str(number)+"_Enable_CB"], \
        self.IOST_Objs[window_name]["_"+str(number)+"_ResetBoard_CB"])

        self.IOST_Objs[window_name]["_"+str(number)+"_Description_TE"].connect('focus-out-event', \
        self.WSetupTestcase_Description_TE_Callback, \
        self.IOST_Objs[window_name]["_"+str(number)+"_Description_TE"], \
        object_name, number, self.IOST_Objs[window_name]["_"+str(number)+"_Enable_CB"], \
        self.IOST_Objs[window_name]["_"+str(number)+"_ResetBoard_CB"])

        self.IOST_Objs[window_name]["_"+str(number)+"_RunTimes_TE"].connect('focus-out-event', \
        self.WSetupTestcase_RunTimes_TE_Callback, \
        self.IOST_Objs[window_name]["_"+str(number)+"_RunTimes_TE"], \
        object_name, number, self.IOST_Objs[window_name]["_"+str(number)+"_Enable_CB"], \
        self.IOST_Objs[window_name]["_"+str(number)+"_ResetBoard_CB"])

        self.IOST_Objs[window_name]["_"+str(number)+"_ResetBoard_CB"].connect('toggled', \
        self.WSetupTestcase_ResetBoard_CB_Callback,
        self.IOST_Objs[window_name]["_"+str(number)+"_ResetBoard_CB"],
        object_name, number)

    #----------------------------------------------------------------------
    def WSetupTestcase_Enable_CB_Callback(self, object, object_active, data=None, number=None):
        ""

        if number > self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]:
            data.append( self.IOST_Data["IP_N"][1] )
            self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"] +=1
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_E_Testcase"] =0
        if IOST_WSetupTestcase_DebugEnable:
            iost_print(IOST_WSetupTestcase_DebugLevel, None, "0-0-0-0-0-0-0-0-0")
            iost_print(IOST_WSetupTestcase_DebugLevel, number, "WSetupTestcase_Enable_CB -> number")
            iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"], "WSetupTestcase_Enable_CB -> numbTestcaseNumber")
            iost_print(IOST_WSetupTestcase_DebugLevel, number, "WSetupTestcase_Enable_CB -> TestcaseList")

        Res = object_active.get_active()
        if Res:
            data[int(number)]["Active"] = 'Enable'
        else:
            data[int(number)]["Active"] = 'Disable'

    #----------------------------------------------------------------------
    def WSetupTestcase_CMD_TE_Callback(self, object, event, object_active, data=None, number=None, set_object_1=None, set_object_2=None):
        "Callback function when CMD text entry of a testcase have changed"

        #______________________________________________________________________
        try:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"]
        except KeyError:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] = 0

        try:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"]
        except KeyError:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"] = 0

        try:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"]
        except KeyError:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] = 0

        #______________________________________________________________________
        if IOST_WSetupTestcase_DebugEnable:
            iost_print(IOST_WSetupTestcase_DebugLevel, None, "1-1-1-1-1-1-1-1-1" )
            iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"], "WSetupTestcase_CMD_TE->TestcaseNumber")

        test_segment = 0
        if number > self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]:
            test_segment = number - self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]
            for i in range(0, test_segment):
                data.append( self.IOST_Data["IP_N"][1] )
                self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"] +=1

            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] = 0

        #______________________________________________________________________
        if IOST_WSetupTestcase_DebugEnable:
            print "number          = ", number
            iost_print(IOST_WSetupTestcase_DebugLevel, number, "WSetupTestcase_CMD_TE->number")
            iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"], "WSetupTestcase_CMD_TE->TestcaseNumber")
            iost_print(IOST_WSetupTestcase_DebugLevel, self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"], "WSetupTestcase_CMD_TE->TestcaseList")

        #______________________________________________________________________
        text = object_active.get_text()

        if text and text.strip():   # string NOT empty"
            set_object_1.set_sensitive(True)
            set_object_2.set_sensitive(True)
            data[number]["Testcase"] = text
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] = 1

        #______________________________________________________________________
        else: # string empty"
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] = 0

        #______________________________________________________________________
        if ((self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] == 1) and
            (self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] == 1)):
            print "x1"
            set_object_1.set_active(True)
            set_object_1.set_sensitive(True)
            data[number]["Active"] = 'Enable'

        elif ((self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] == 0) or
            (self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] == 0)):

            data[number]["Active"] = 'Disable'

        #______________________________________________________________________
        if ((self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] == 0) and
            (self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"] == 0) and
            (self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] == 0)):

            set_object_1.set_active(False)
            set_object_1.set_sensitive(False)
            set_object_2.set_active(False)
            set_object_2.set_sensitive(False)
            self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"] -= test_segment
            for i in range(test_segment, 0, -1):
                del data[self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]+i]

        if IOST_WSetupTestcase_DebugEnable:
            print "-------------------------------------------"
            print "testcase number = ", self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]
            print "len data = ", len(data)
            print "_CMD_Testcase = ", self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"]
            print "_DES_Testcase = ", self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"]
            print "_RT_Testcase = ", self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"]

            print "------------------debug-------------------------"
            print number
            print self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"]

        if number == self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"]:
            self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"] +=1
            self.WSetupTestcase_CreateTestListMore(self.IOST_Objs[self.IOST_WSetupTestcase_window], self.IOST_Objs["SetupTestcaseTemplate"], self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"])
            self.WSetupTestcase_SetCallback(self.IOST_WSetupTestcase_window, self.IOST_Data[self.IOST_WSetupTestcase_ip_name], self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"])

            # adjustment = yourScrolledWindow.get_vadjustment()
            # adjustment.set_value(adjustment.get_upper())

            adjustment = self.IOST_Objs[self.IOST_WSetupTestcase_window]["_TestcaseList_SW"].get_vadjustment()
            adjustment.set_value(adjustment.get_upper())
            self.IOST_Objs[self.IOST_WSetupTestcase_window]["_TestcaseList_SW"].set_vadjustment(adjustment)

            self.IOST_Objs[self.IOST_WSetupTestcase_window]["_TestcaseList_SW"].set_placement(gtk.CORNER_BOTTOM_LEFT)
            self.IOST_Objs[self.IOST_WSetupTestcase_window][self.IOST_WSetupTestcase_object].show_all()
        if IOST_WSetupTestcase_DebugEnable:
            print "1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1"

    #----------------------------------------------------------------------
    def WSetupTestcase_Description_TE_Callback(self, object, event, object_active, data=None, number=None, set_object_1=None, set_object_2=None):
        "Callback function when Description text entry of a testcase have changed"
        #______________________________________________________________________
        try:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"]
        except KeyError:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] = 0

        try:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"]
        except KeyError:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"] = 0

        try:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"]
        except KeyError:
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] = 0

        #______________________________________________________________________
        test_segment = 0
        if number > self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]:
            test_segment = number - self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]
            for i in range(0, test_segment):
                data.append( self.IOST_Data["IP_N"][1] )
                self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"] +=1

            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"] = 0

        #______________________________________________________________________
        if IOST_WSetupTestcase_DebugEnable:
            print "2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2-2"
            print "number          = ", number
            print "testcase number = ", self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseNum"]
            print "testcase list   = ", self.IOST_Objs["SetupTestcaseTemplate"]["TestcaseList"]

        #______________________________________________________________________
        text = object_active.get_text()

        if text and text.strip():        # string NOT empty"
            set_object_1.set_sensitive(True)
            set_object_2.set_sensitive(True)
            data[number]["Description"] = text
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"] = 1

        #______________________________________________________________________
        else:       # string empty"
            self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_DES_Testcase"] = 0

         #______________________________________________________________________
        if ((self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_CMD_Testcase"] == 1) and

Answer: (self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] == 1)):

<think>
In the Description callback, after setting the DES flag, the code mirrors the logic from the CMD callback. It starts an if statement checking whether the CMD flag is 1 and needs to continue checking the RT flag. The next line completes the condition by adding the RT_Testcase check and closing the parentheses.
</think>
(self.IOST_Objs["SetupTestcaseTemplate"]["_"+str(number)+"_RT_Testcase"] == 1)):


Context:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.Networks;
using NBitcoin.Protocol;
using NLog.Extensions.Logging;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Utilities;

namespace Stratis.Bitcoin.Configuration
{
    internal static class NormalizeDirectorySeparatorExt
    {
        ///
        /// Fixes incorrect directory separator characters in path (if any)
        ///
        public static string NormalizeDirectorySeparator(this string path)
        {
            // Replace incorrect with correct
            return path.Replace((Path.DirectorySeparatorChar == '/') ? '\\' : '/', Path.DirectorySeparatorChar);
        }
    }

    ///
    /// Node configuration complied from both the application command line arguments and the configuration file.
    ///
    public class NodeSettings : IDisposable
    {
        /// Version of the protocol the current implementation supports.
        public const ProtocolVersion SupportedProtocolVersion = ProtocolVersion.SENDHEADERS_VERSION;

        /// Factory to create instance logger.
        public ILoggerFactory LoggerFactory { get; private set; }

        /// Instance logger.
        public ILogger Logger { get; private set; }

        /// Configuration related to logging.
        public LogSettings Log { get; private set; }

        /// List of paths to important files and folders.
        public DataFolder DataFolder { get; private set; }

        /// Path to the data directory. This value is read-only and is set in the constructor's args.
        public string DataDir { get; private set; }

        /// Path to the root data directory. This value is read-only and is set in the constructor's args.
        public string DataDirRoot { get; private set; }

        /// Path to the configuration file. This value is read-only and is set in the constructor's args.
        public string ConfigurationFile { get; private set; }

        /// Combined command line arguments and configuration file settings.
        public TextFileConfiguration ConfigReader { get; private set; }

        /// Supported protocol version.
        public ProtocolVersion ProtocolVersion { get; private set; }

        /// Lowest supported protocol version.
        public ProtocolVersion? MinProtocolVersion { get; set; }

        /// Specification of the network the node runs on - regtest/testnet/mainnet.
        public Network Network { get; private set; }

        /// The node's user agent.
        public string Agent { get; private set; }

        /// Minimum transaction fee for network.
        public FeeRate MinTxFeeRate { get; private set; }

        /// Fall back transaction fee for network.
        public FeeRate FallbackTxFeeRate { get; private set; }

        /// Minimum relay transaction fee for network.
        public FeeRate MinRelayTxFeeRate { get; private set; }

        ///
        /// Initializes a new instance of the object.
        ///
        /// <param name="network">The network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="protocolVersion">Supported protocol version for which to create the configuration.</param>
        /// <param name="agent">The nodes user agent that will be shared with peers.</param>
        /// <param name="args">The command-line arguments.</param>
        /// <param name="networksSelector">A selector class that delayed load a network for either - regtest/testnet/mainnet.</param>
        /// <exception cref="ConfigurationException">Thrown in case of any problems with the configuration file or command line arguments.</exception>
        /// <remarks>
        /// Processing depends on whether a configuration file is passed via the command line.
        /// There are two main scenarios here:
        /// - The configuration file is passed via the command line. In this case we need
        ///   to read it earlier so that it can provide defaults for "testnet" and "regtest".
        /// - Alternatively, if the file name is not supplied then a network-specific file
        ///   name would be determined. In this case we first need to determine the network.
        /// </remarks>
        public NodeSettings(Network network = null, ProtocolVersion protocolVersion = SupportedProtocolVersion,
            string agent = "StratisNode", string[] args = null, NetworksSelector networksSelector = null)
        {
            // Create the default logger factory and logger.
            var loggerFactory = new ExtendedLoggerFactory();
            this.LoggerFactory = loggerFactory;
            this.LoggerFactory.AddConsoleWithFilters();
            this.LoggerFactory.AddNLog();
            this.Logger = this.LoggerFactory.CreateLogger(typeof(NodeSettings).FullName);

            // Record arguments.
            this.Network = network;
            this.ProtocolVersion = protocolVersion;
            this.Agent = agent;
            this.ConfigReader = new TextFileConfiguration(args ?? new string[] { });

            // Log arguments.
            this.Logger.LogDebug("Arguments: network='{0}', protocolVersion='{1}', agent='{2}', args='{3}'.",
                this.Network == null ? "(None)" : this.Network.Name,
                this.ProtocolVersion,
                this.Agent,
                args == null ? "(None)" : string.Join(" ", args));

            // By default, we look for a file named '<network>.conf' in the network's data directory,
            // but both the data directory and the configuration file path may be changed using the -datadir and -conf command-line arguments.
            this.ConfigurationFile = this.ConfigReader.GetOrDefault<string>("conf", null, this.Logger)?.NormalizeDirectorySeparator();
            this.DataDir = this.ConfigReader.GetOrDefault<string>("datadir", null, this.Logger)?.NormalizeDirectorySeparator();
            this.DataDirRoot = this.ConfigReader.GetOrDefault<string>("datadirroot", "StratisNode", this.Logger);

            // If the configuration file is relative then assume it is relative to the data folder and combine the paths.
            if (this.DataDir != null && this.ConfigurationFile != null)
            {
                bool isRelativePath = Path.GetFullPath(this.ConfigurationFile).Length > this.ConfigurationFile.Length;
                if (isRelativePath)
                    this.ConfigurationFile = Path.Combine(this.DataDir, this.ConfigurationFile);
            }

            // If the configuration file has been specified on the command line then read it now
            // so that it can provide the defaults for testnet and regtest.

Answer: if (this.ConfigurationFile != null)

<think>
The comment explains that when a configuration file path was supplied via the command line, the code should now read that file so its settings can affect defaults for testnet/regtest. The next logical step is to check whether ConfigurationFile is non‑null before loading it. Therefore the next line is the conditional that begins this operation.
</think>
if (this.ConfigurationFile != null)


Context:
// Copyright 2020 The Bazel Authors. 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.

package com.google.devtools.build.lib.skyframe;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.AnalysisEnvironment;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.analysis.util.MockRule;
import com.google.devtools.build.lib.analysis.util.MockRuleDefaults;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.FlagGuardedValue;
import net.starlark.java.eval.Mutability;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkList;
import net.starlark.java.eval.StarlarkThread;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for Starlark builtin injection.
 *
 *
Essentially these are integration tests between {@link StarlarkBuiltinsFunction}, {@link
 * BzlLoadFunction}, and the rest of package loading.
 */
@RunWith(JUnit4.class)
public class BuiltinsInjectionTest extends BuildViewTestCase {

  /** A simple dummy rule that doesn't do anything. */
  private static final MockRule OVERRIDABLE_RULE = () -> MockRule.define("overridable_rule");

  /**
   * A dummy native rule that reads from exported_to_java the symbol "builtins_defined_symbol", and
   * prints its value to the event handler.
   */
  private static final MockRule SANDWICH_RULE =
      () -> MockRule.factory(SandwichFactory.class).define("sandwich_rule");

  // Must be public due to reflective construction of rule factories.
  /** Factory for SANDWICH_RULE. (Javadoc'd to pacify linter.) */
  public static class SandwichFactory extends MockRuleDefaults.DefaultConfiguredTargetFactory {
    @Override
    public ConfiguredTarget create(RuleContext ruleContext)
        throws InterruptedException, RuleErrorException, ActionConflictException {
      AnalysisEnvironment env = ruleContext.getAnalysisEnvironment();

      Object value = env.getStarlarkDefinedBuiltins().get("builtins_defined_symbol");

      env.getEventHandler().handle(Event.info("builtins_defined_symbol :: " + value.toString()));
      return super.create(ruleContext);
    }
  }

  /**
   * A dummy rule that dispatches to {@code @_builtins}-defined code. It looks up the function
   * listed as "builtins_defined_logic" in exported_to_java, and calls it twice on an initially
   * empty list. It prints both return values and the final value of the list.
   */
  private static final MockRule SANDWICH_LOGIC_RULE =
      () -> MockRule.factory(SandwichLogicFactory.class).define("sandwich_logic_rule");

  // Must be public due to reflective construction of rule factories.
  /** Factory for SANDWICH_LOGIC_RULE. (Javadoc'd to pacify linter.) */
  public static class SandwichLogicFactory extends MockRuleDefaults.DefaultConfiguredTargetFactory {
    @Override
    public ConfiguredTarget create(RuleContext ruleContext)
        throws InterruptedException, RuleErrorException, ActionConflictException {
      AnalysisEnvironment env = ruleContext.getAnalysisEnvironment();
      StarlarkThread thread = ruleContext.getStarlarkThread();
      Mutability mu = thread.mutability();

      Object func = env.getStarlarkDefinedBuiltins().get("builtins_defined_logic");
      Object arg = StarlarkList.newList(mu);
      Object return1;
      Object return2;
      try {
        return1 = Starlark.call(thread, func, ImmutableList.of(arg), ImmutableMap.of());
        return2 = Starlark.call(thread, func, ImmutableList.of(arg), ImmutableMap.of());
      } catch (EvalException e) {
        throw new AssertionError("Failure during Starlark evaluation", e);
      }

      EventHandler handler = env.getEventHandler();
      handler.handle(Event.info("builtins_defined_logic call 1 :: " + return1.toString()));
      handler.handle(Event.info("builtins_defined_logic call 2 :: " + return2.toString()));
      handler.handle(Event.info("final list value :: " + arg.toString()));
      return super.create(ruleContext);
    }
  }

  @Override
  protected Iterable<String> getDefaultsForConfiguration() {
    // Override BuildViewTestCase's behavior of setting all sorts of extra options that don't exist
    // on our minimal rule class provider.
    // We do need the host platform. Set it to something trivial.
    return ImmutableList.of("--host_platform=//minimal_buildenv/platforms:default_host");
  }

  @Override
  protected void initializeMockClient() throws IOException {
    // Don't let the AnalysisMock sneak in any WORKSPACE file content, which may depend on
    // repository rules that our minimal rule class provider doesn't have.
    analysisMock.setupMockClient(mockToolsConfig, ImmutableList.of());
    // Provide a trivial platform definition.
    mockToolsConfig.create(
        "minimal_buildenv/platforms/BUILD", //
        "platform(name = 'default_host')");
  }

  @Override
  protected ConfiguredRuleClassProvider createRuleClassProvider() {
    // Set up a bare-bones ConfiguredRuleClassProvider. Aside from being minimalistic, this heads
    // off the possibility that we somehow grow an implicit dependency on production builtins code,
    // which would break since we're overwriting --experimental_builtins_bzl_path.
    ConfiguredRuleClassProvider.Builder builder = new ConfiguredRuleClassProvider.Builder();
    TestRuleClassProvider.addMinimalRules(builder);
    // Add some mock symbols to override.
    builder
        .addRuleDefinition(OVERRIDABLE_RULE)
        .addRuleDefinition(SANDWICH_RULE)
        .addRuleDefinition(SANDWICH_LOGIC_RULE)
        .addStarlarkAccessibleTopLevels("overridable_symbol", "original_value")
        .addStarlarkAccessibleTopLevels(
            "flag_guarded_symbol",
            // For this mock symbol, we reuse the same flag that guards the production
            // _builtins_dummy symbol.
            FlagGuardedValue.onlyWhenExperimentalFlagIsTrue(
                BuildLanguageOptions.EXPERIMENTAL_BUILTINS_DUMMY, "original value"));
    return builder.build();
  }

  @Before
  public void setUp() throws Exception {
    setBuildLanguageOptions("--experimental_builtins_bzl_path=tools/builtins_staging");
  }

  /**
   * Writes an exports.bzl file with the given content, in the builtins location.
   *
   *
See {@link StarlarkBuiltinsFunction#EXPORTS_ENTRYPOINT} for the significance of exports.bzl.
   */
  private void writeExportsBzl(String... lines) throws Exception {
    scratch.file("tools/builtins_staging/exports.bzl", lines);
  }

  /**
   * Writes a pkg/dummy.bzl file that prints a marker phrase when it finishes evaluating, and an
   * accompanying BUILD file that loads it.
   */
  private void writePkgBzl(String... lines) throws Exception {
    scratch.file("pkg/BUILD", "load(':dummy.bzl', 'dummy_symbol')");
    scratch.file("pkg/dummy");
    List<String> modifiedLines = new ArrayList<>(Arrays.asList(lines));
    modifiedLines.add("dummy_symbol = None");
    // The marker phrase might not be needed, but I don't entirely trust BuildViewTestCase.
    modifiedLines.add("print('dummy.bzl evaluation completed')");
    scratch.file("pkg/dummy.bzl", modifiedLines.toArray(lines));
  }

  /** Builds {@code //pkg} and asserts success, including that the marker print() event occurs. */

Answer: private void buildAndAssertSuccess() throws Exception {

<think>
The comment just introduced a helper method that builds the //pkg target and checks that the build succeeded and that the dummy.bzl print marker was emitted. Following the naming style of the other helper methods (writeExportsBzl, writePkgBzl), the next line should be the method signature for this helper. A suitable signature is a private method returning void, throwing Exception, named to reflect its purpose, e.g., assertPkgBuildSucceeds().
</think>
private void assertPkgBuildSucceeds() throws Exception {


Context:
namespace com.snippets.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using com.snippets.Data.Entities;

    internal sealed class Configuration : DbMigrationsConfiguration<com.snippets.Data.Entities.snippetsDb>
    {
        public Configuration()
        {
            Database.SetInitializer<snippetsDb>(new DropCreateDatabaseIfModelChanges<snippetsDb>());
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(com.snippets.Data.Entities.snippetsDb context)
        {

            #region Populating Post Types Table

            context.Posts_Types.AddOrUpdate(

                p => p.TypeName,
                new Post_Type { TypeName = "Status" },
                new Post_Type { TypeName = "Photo" },
                new Post_Type { TypeName = "Snippets" }
            );

            #endregion

            #region Populating Genders Table
            context.Genders.AddOrUpdate(

                p => p.GenderName,
                new Gender { GenderName = "Male" },
                new Gender { GenderName = "Female" }
            );
            #endregion

            #region Populating Preference Types Table
            context.PreferenceTypes.AddOrUpdate(

                p=>p.Type,
                new PreferenceType{Type="Language", PreferenceTypeId=1}
            );
            #endregion

            #region Populating Preferences Table

            context.Preferences.AddOrUpdate(

                p=>p.PreferenceName,
                new Preference{PreferenceTypeId=1, PreferenceName="C", LanguageCode="c",
                               photo_url=@"~\Content\images\langs\lang-c.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="C++", LanguageCode="cpp",
                               photo_url=@"~\Content\images\langs\lang-cpp.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="C#", LanguageCode="csharp",
                               photo_url=@"~\Content\images\langs\lang-csharp.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="CSS", LanguageCode="css",
                               photo_url=@"~\Content\images\langs\lang-css.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Flex", LanguageCode="flex",
                               photo_url=@"~\Content\images\langs\lang-flex.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="HTML", LanguageCode="html",
                               photo_url=@"~\Content\images\langs\lang-html.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Java", LanguageCode="java",
                               photo_url=@"~\Content\images\langs\lang-java.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Javascript", LanguageCode="javascript",
                               photo_url=@"~\Content\images\langs\lang-js.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Javascript With DOM", LanguageCode="javascript_dom",
                               photo_url=@"~\Content\images\langs\lang-js_dom.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Perl", LanguageCode="perl",
                               photo_url=@"~\Content\images\langs\lang-perl.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="PHP", LanguageCode="php",
                               photo_url=@"~\Content\images\langs\lang-php.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Python", LanguageCode="python",
                               photo_url=@"~\Content\images\langs\lang-python.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="Ruby", LanguageCode="ruby",
                               photo_url=@"~\Content\images\langs\lang-ruby.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="SQL", LanguageCode="sql",
                               photo_url=@"~\Content\images\langs\lang-sql.png"},

                new Preference{PreferenceTypeId=1, PreferenceName="XML", LanguageCode="xml",
                               photo_url=@"~\Content\images\langs\lang-xml.png"}
            );
            #endregion

            #region Populating Countries Table
            context.Countries.AddOrUpdate(
                p=>p.CountryName,
                new Country { CountryName= "Afghanistan", CountryCode="AF" },
                new Country { CountryName= "Aland Islands", CountryCode="AX" },
                new Country { CountryName= "Albania", CountryCode="AL" },
                new Country { CountryName= "Algeria", CountryCode="DZ" },
                new Country { CountryName= "American Samoa", CountryCode="AS" },
                new Country { CountryName= "Andorra", CountryCode="AD" },
                new Country { CountryName= "Angola", CountryCode="AO" },
                new Country { CountryName= "Anguilla", CountryCode="AI" },
                new Country { CountryName= "Antarctica", CountryCode="AQ" },
                new Country { CountryName= "Antigua And Barbuda", CountryCode="AG" },
                new Country { CountryName= "Argentina", CountryCode="AR" },
                new Country { CountryName= "Armenia", CountryCode="AM" },
                new Country { CountryName= "Aruba", CountryCode="AW" },
                new Country { CountryName= "Australia", CountryCode="AU" },
                new Country { CountryName= "Austria", CountryCode="AT" },
                new Country { CountryName= "Azerbaijan", CountryCode="AZ" },
                new Country { CountryName= "Bahamas", CountryCode="BS" },
                new Country { CountryName= "Bahrain", CountryCode="BH" },
                new Country { CountryName= "Bangladesh", CountryCode="BD" },
                new Country { CountryName= "Barbados", CountryCode="BB" },
                new Country { CountryName= "Belarus", CountryCode="BY" },
                new Country { CountryName= "Belgium", CountryCode="BE" },
                new Country { CountryName= "Belize", CountryCode="BZ" },
                new Country { CountryName= "Benin", CountryCode="BJ" },
                new Country { CountryName= "Bermuda", CountryCode="BM" },
                new Country { CountryName= "Bhutan", CountryCode="BT" },
                new Country { CountryName= "Bolivia", CountryCode="BO" },
                new Country { CountryName= "Bosnia And Herzegovina", CountryCode="BA" },
                new Country { CountryName= "Botswana", CountryCode="BW" },
                new Country { CountryName= "Bouvet Island", CountryCode="BV" },
                new Country { CountryName= "Brazil", CountryCode="BR" },
                new Country { CountryName= "British Indian Ocean Territory", CountryCode="IO" },
                new Country { CountryName= "Brunei Darussalam", CountryCode="BN" },
                new Country { CountryName= "Bulgaria", CountryCode="BG" },
                new Country { CountryName= "Burkina Faso", CountryCode="BF" },
                new Country { CountryName= "Burundi", CountryCode="BI" },
                new Country { CountryName= "Cambodia", CountryCode="KH" },
                new Country { CountryName= "Cameroon", CountryCode="CM" },
                new Country { CountryName= "Canada", CountryCode="CA" },
                new Country { CountryName= "Cape Verde", CountryCode="CV" },
                new Country { CountryName= "Cayman Islands", CountryCode="KY" },
                new Country { CountryName= "Central African Republic", CountryCode="CF" },
                new Country { CountryName= "Chad", CountryCode="TD" },
                new Country { CountryName= "Chile", CountryCode="CL" },
                new Country { CountryName= "China", CountryCode="CN" },
                new Country { CountryName= "Christmas Island", CountryCode="CX" },
                new Country { CountryName= "Cocos (Keeling) Islands", CountryCode="CC" },
                new Country { CountryName= "Colombia", CountryCode="CO" },
                new Country { CountryName= "Comoros", CountryCode="KM" },
                new Country { CountryName= "Congo", CountryCode="CG" },
                new Country { CountryName= "Congo, The Democratic Republic Of The", CountryCode="CD" },
                new Country { CountryName= "Cook Islands", CountryCode="CK" },
                new Country { CountryName= "Costa Rica", CountryCode="CR" },
                new Country { CountryName= "Cote D'Ivoire", CountryCode="CI" },
                new Country { CountryName= "Croatia", CountryCode="HR" },
                new Country { CountryName= "Cuba", CountryCode="CU" },
                new Country { CountryName= "Cyprus", CountryCode="CY" },
                new Country { CountryName= "Czech Republic", CountryCode="CZ" },
                new Country { CountryName= "Denmark", CountryCode="DK" },
                new Country { CountryName= "Djibouti", CountryCode="DJ" },
                new Country { CountryName= "Dominica", CountryCode="DM" },
                new Country { CountryName= "Dominican Republic", CountryCode="DO" },
                new Country { CountryName= "Ecuador", CountryCode="EC" },
                new Country { CountryName= "Egypt", CountryCode="EG" },
                new Country { CountryName= "El Salvador", CountryCode="SV" },
                new Country { CountryName= "Equatorial Guinea", CountryCode="GQ" },
                new Country { CountryName= "Eritrea", CountryCode="ER" },
                new Country { CountryName= "Estonia", CountryCode="EE" },
                new Country { CountryName= "Ethiopia", CountryCode="ET" },
                new Country { CountryName= "Falkland Islands (Malvinas)", CountryCode="FK" },
                new Country { CountryName= "Faroe Islands", CountryCode="FO" },
                new Country { CountryName= "Fiji", CountryCode="FJ" },
                new Country { CountryName= "Finland", CountryCode="FI" },
                new Country { CountryName= "France", CountryCode="FR" },
                new Country { CountryName= "French Guiana", CountryCode="GF" },
                new Country { CountryName= "French Polynesia", CountryCode="PF" },
                new Country { CountryName= "French Southern Territories", CountryCode="TF" },
                new Country { CountryName= "Gabon", CountryCode="GA" },
                new Country { CountryName= "Gambia", CountryCode="GM" },
                new Country { CountryName= "Georgia", CountryCode="GE" },
                new Country { CountryName= "Germany", CountryCode="DE" },
                new Country { CountryName= "Ghana", CountryCode="GH" },
                new Country { CountryName= "Gibraltar", CountryCode="GI" },
                new Country { CountryName= "Greece", CountryCode="GR" },
                new Country { CountryName= "Greenland", CountryCode="GL" },
                new Country { CountryName= "Grenada", CountryCode="GD" },
                new Country { CountryName= "Guadeloupe", CountryCode="GP" },
                new Country { CountryName= "Guam", CountryCode="GU" },
                new Country { CountryName= "Guatemala", CountryCode="GT" },
                new Country { CountryName= "Guernsey", CountryCode=" GG" },
                new Country { CountryName= "Guinea", CountryCode="GN" },
                new Country { CountryName= "Guinea-Bissau", CountryCode="GW" },

Answer: new Country { CountryName= "Guyana", CountryCode="GY" },

<think>
The Seed method is populating the Countries table using AddOrUpdate with a list of Country objects. The list is alphabetical and currently ends with Guinea-Bissau. The next country alphabetically is Guyana, so the next line should add a new Country entry for Guyana with its ISO code.
</think>
new Country { CountryName= "Guyana", CountryCode="GY" },


Context:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
    /// <summary>
    ///     Parameter Sets used for Azure Site Recovery commands.
    /// </summary>
    internal static class ASRParameterSets
    {
        /// <summary>
        ///     Add protected entities to RP
        /// </summary>
        internal const string AddProtectedEntities = "AddProtectedEntities";

        /// <summary>
        ///     Add  replication protected items to RP
        /// </summary>
        internal const string AddReplicationProtectedItems = "AddReplicationProtectedItems";

        /// <summary>
        ///     To append group to RP.
        /// </summary>
        internal const string AppendGroup = "AppendGroup";

        /// <summary>
        ///     Handle ARS Vault.
        /// </summary>
        internal const string ARSVault = "AzureRecoveryServicesVault";

        /// </summary>
        /// Handle ASR Vault.
        /// </summary>
        internal const string ASRVault = "AzureSiteRecoveryVault";

        /// </summary>
        /// Handle ASR Vault - Azure Fabric.
        /// </summary>
        internal const string Azure = "Azure";

        /// </summary>
        /// Handle ASR Vault - A2A Fabric.
        /// </summary>
        internal const string AzureToAzure = "AzureToAzure";

        /// </summary>
        /// Handle ASR Vault - A2A Fabric.
        /// </summary>
        internal const string AzureToAzureWithoutDiskDetails = "AzureToAzureWithoutDiskDetails";

        /// </summary>
        /// Handle ASR Vault - Paramset for A2a ManagedDisk.
        /// </summary>
        internal const string AzureToAzureManagedDisk = "AzureToAzureManagedDisk";

        /// </summary>
        /// Handle ASR Vault - A2A Fabric name.
        /// </summary>
        internal const string AzureToAzureWithFabricName = "AzureToAzureWithFabricName";

        /// </summary>
        /// Handle ASR Vault - A2A Fabric -AzureToAzureWithMultipleStorageAccount.
        /// </summary>
        internal const string AzureToAzureWithMultipleStorageAccount = "AzureToAzureWithMultipleStorageAccount";

        /// </summary>
        /// Handle ASR Vault.
        /// </summary>
        internal const string AzureToVMware = "AzureToVMware";

        /// <summary>
        ///     When only Name is passed to the command.
        /// </summary>
        internal const string ByFabricObject = "ByFabricObject";

        /// <summary>
        ///     When FabricId is passed to the command.
        /// </summary>
        internal const string ByFabricId = "ByFabricId";

        /// <summary>
        ///     When only Name is passed to the command.
        /// </summary>
        internal const string ByFabricName = "ByFabricName";

        /// <summary>
        ///     When only Name is passed to the command.
        /// </summary>
        internal const string ByFriendlyName = "ByFriendlyName";

        /// <summary>
        ///     When only Friendly Name is passed to the command Legacy.
        /// </summary>
        internal const string ByFriendlyNameLegacy = "ByFriendlyNameLegacy";

        /// <summary>
        ///     When only ID is passed to the command.
        /// </summary>
        internal const string ById = "ById";

        /// <summary>
        ///     When group of IDs are passed to the command.
        /// </summary>
        internal const string ByIDs = "ByIDs";

        /// <summary>
        ///     When group of IDs and ID are passed to the command.
        /// </summary>
        internal const string ByIDsWithId = "ByIDsWithId";

        /// <summary>
        ///     When group of IDs and Name are passed to the command.
        /// </summary>
        internal const string ByIDsWithName = "ByIDsWithName";

        /// <summary>
        ///     When only Name is passed to the command.
        /// </summary>
        internal const string ByName = "ByName";

        /// <summary>
        ///     When only NetworkName Fabric is passed to the command.
        /// </summary>
        internal const string ByNetworkNameFabric = "ByNetworkNameFabric";

        /// <summary>
        ///     When only NetworkName FabricName is passed to the command.
        /// </summary>
        internal const string ByNetworkNameFabricName = "ByNetworkNameFabricName";

        /// <summary>
        ///     When only Name is passed to the command Legacy.
        /// </summary>
        internal const string ByNameLegacy = "ByNameLegacy";

        /// <summary>
        ///     To define parameter set containing network object.
        /// </summary>
        internal const string ByNetworkObject = "ByNetworkObject";

        /// <summary>
        ///     When only Object is passed to the command.
        /// </summary>
        internal const string ByObject = "ByObject";

        /// <summary>
        ///     When Object and Name are passed to the command.
        /// </summary>
        internal const string ByObjectWithFriendlyName = "ByObjectWithFriendlyName";

        /// <summary>
        ///     When Object and Name are passed to the command Legacy.
        /// </summary>
        internal const string ByObjectWithFriendlyNameLegacy = "ByObjectWithFriendlyNameLegacy";

        /// <summary>
        ///     When Object and ID are passed to the command.
        /// </summary>
        internal const string ByObjectWithId = "ByObjectWithId";

        /// <summary>
        ///     When Object and Name are passed to the command.
        /// </summary>
        internal const string ByObjectWithName = "ByObjectWithName";

        /// <summary>
        ///     When Object and Name are passed to the command Legacy.
        /// </summary>
        internal const string ByObjectWithNameLegacy = "ByObjectWithNameLegacy";

        /// <summary>
        ///     When parameters are passed to the command.
        /// </summary>
        internal const string ByParam = "ByParam";

        /// <summary>
        ///     When only PC and PE ids are passed to the command.
        /// </summary>
        internal const string ByPEId = "ByPEId";

        /// <summary>
        ///     When only PC and PE ids are passed along with logical network ID to the command.
        /// </summary>
        internal const string ByPEIdWithLogicalNetworkID = "ByPEIdWithLogicalNetworkID";

        /// <summary>
        ///     When only PC and PE ids are passed along with VM network to the command.
        /// </summary>
        internal const string ByPEIdWithVMNetwork = "ByPEIdWithVMNetwork";

        /// <summary>
        ///     When only PC and PE ids are passed along with VM network ID to the command.
        /// </summary>
        internal const string ByPEIdWithVMNetworkID = "ByPEIdWithVMNetworkID";

        /// <summary>
        ///     When only PE Object is passed to the command.
        /// </summary>

Answer: internal const string ByPEObject = "ByPEObject";

<think>
The code defines a series of internal constant strings representing parameter set names, each preceded by an XML summary comment. The last comment describes a parameter set for when only a PE (Protected Entity) object is passed. Following the established pattern, the next line should declare the corresponding constant string named ByPEObject with its value "ByPEObject".
</think>
internal const string ByPEObject = "ByPEObject";


Context:
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings

from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models
from ..._vendor import _convert_request
from ...operations._virtual_clusters_operations import build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_dns_servers_request, build_update_request_initial
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class VirtualClustersOperations:
    """VirtualClustersOperations async operations.

    You should not instantiate this class directly. Instead, you should create a Client instance that
    instantiates it for you and attaches it as an attribute.

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~azure.mgmt.sql.models
    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = _models

    def __init__(self, client, config, serializer, deserializer) -> None:
        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self._config = config

    @distributed_trace_async
    async def update_dns_servers(
        self,
        resource_group_name: str,
        virtual_cluster_name: str,
        **kwargs: Any
    ) -> "_models.UpdateManagedInstanceDnsServersOperation":
        """Synchronizes the DNS server settings used by the managed instances inside the given virtual
        cluster.

        :param resource_group_name: The name of the resource group that contains the resource. You can
         obtain this value from the Azure Resource Manager API or the portal.
        :type resource_group_name: str
        :param virtual_cluster_name: The name of the virtual cluster.
        :type virtual_cluster_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: UpdateManagedInstanceDnsServersOperation, or the result of cls(response)
        :rtype: ~azure.mgmt.sql.models.UpdateManagedInstanceDnsServersOperation
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.UpdateManagedInstanceDnsServersOperation"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        request = build_update_dns_servers_request(
            resource_group_name=resource_group_name,
            virtual_cluster_name=virtual_cluster_name,
            subscription_id=self._config.subscription_id,
            template_url=self.update_dns_servers.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

        pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize('UpdateManagedInstanceDnsServersOperation', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    update_dns_servers.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/virtualClusters/{virtualClusterName}/updateManagedInstanceDnsServers'}  # type: ignore

    @distributed_trace
    def list(
        self,
        **kwargs: Any
    ) -> AsyncIterable["_models.VirtualClusterListResult"]:
        """Gets a list of all virtualClusters in the subscription.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either VirtualClusterListResult or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.VirtualClusterListResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualClusterListResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_request(
                    subscription_id=self._config.subscription_id,
                    template_url=self.list.metadata['url'],
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)

            else:

                request = build_list_request(
                    subscription_id=self._config.subscription_id,
                    template_url=next_link,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("VirtualClusterListResult", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(
            get_next, extract_data
        )
    list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/virtualClusters'}  # type: ignore

    @distributed_trace
    def list_by_resource_group(
        self,
        resource_group_name: str,
        **kwargs: Any
    ) -> AsyncIterable["_models.VirtualClusterListResult"]:
        """Gets a list of virtual clusters in a resource group.

        :param resource_group_name: The name of the resource group that contains the resource. You can
         obtain this value from the Azure Resource Manager API or the portal.
        :type resource_group_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either VirtualClusterListResult or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.VirtualClusterListResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualClusterListResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_resource_group_request(
                    resource_group_name=resource_group_name,
                    subscription_id=self._config.subscription_id,
                    template_url=self.list_by_resource_group.metadata['url'],
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)

            else:

                request = build_list_by_resource_group_request(
                    resource_group_name=resource_group_name,
                    subscription_id=self._config.subscription_id,
                    template_url=next_link,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("VirtualClusterListResult", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

Answer: return AsyncItemPaged(

<think>
The method list_by_resource_group defines inner functions prepare_request, extract_data, and get_next, mirroring the pattern used in the list method above. After defining get_next, the method should return an AsyncItemPaged instance constructed with get_next and extract_data, just as in the earlier list implementation. Therefore the next line is the return statement for AsyncItemPaged.
</think>
return AsyncItemPaged(
    get_next, extract_data
)