Context:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
python %prog study.file population.file gene-association.file

This program returns P-values for functional enrichment in a cluster of
study genes using Fisher's exact test, and corrected for multiple testing
(including Bonferroni, Holm, Sidak, and false discovery rate)
"""

from __future__ import absolute_import

__copyright__ = "Copyright (C) 2010-2017, H Tang et al., All rights reserved."
__author__ = "various"

import sys
import collections as cx
import datetime

from .multiple_testing import Methods, Bonferroni, Sidak, HolmBonferroni, FDR, calc_qval
from .ratio import get_terms, count_terms, is_ratio_different
from . import wr_tbl as RPT
from .pvalcalc import FisherFactory

class GOEnrichmentRecord(object):
    """Represents one result (from a single GOTerm) in the GOEnrichmentStudy
    """
    namespace2NS = cx.OrderedDict([
        ('biological_process', 'BP'),
        ('molecular_function', 'MF'),
        ('cellular_component', 'CC')])

    # Fields seen in every enrichment result
    _fldsdefprt = [
        "GO",
        "NS",
        "enrichment",
        "name",
        "ratio_in_study",
        "ratio_in_pop",
        "p_uncorrected",
        "depth",
        "study_count",
        "study_items"]
    _fldsdeffmt = ["%s"]*3 + ["%-30s"] + ["%d/%d"] * 2 + ["%.3g"] + ["%d"] * 2 + ["%15s"]

    _flds = set(_fldsdefprt).intersection(
        set(['study_items', 'study_count', 'study_n', 'pop_items', 'pop_count', 'pop_n']))

    def __init__(self, **kwargs):
        # Methods seen in current enrichment result
        self._methods = []
        for k, v in kwargs.items():
            setattr(self, k, v)
            if k == 'ratio_in_study':
                setattr(self, 'study_count', v[0])
                setattr(self, 'study_n', v[1])
            if k == 'ratio_in_pop':
                setattr(self, 'pop_count', v[0])
                setattr(self, 'pop_n', v[1])
        self._init_enrichment()
        self.goterm = None  # the reference to the GOTerm

    def get_method_name(self):
        """Return name of first method in the _methods list."""
        return self._methods[0].fieldname

    def get_pvalue(self):
        """Returns pval for 1st method, if it exists. Else returns uncorrected pval."""
        if self._methods:
            return getattr(self, "p_{m}".format(m=self.get_method_name()))
        return getattr(self, "p_uncorrected")

    def set_corrected_pval(self, nt_method, pvalue):
        """Add object attribute based on method name."""
        self._methods.append(nt_method)
        fieldname = "".join(["p_", nt_method.fieldname])
        setattr(self, fieldname, pvalue)

    def __str__(self, indent=False):
        field_data = [getattr(self, f, "n.a.") for f in self._fldsdefprt[:-1]] + \
                     [getattr(self, "p_{}".format(m.fieldname)) for m in self._methods] + \
                     [", ".join(sorted(getattr(self, self._fldsdefprt[-1], set())))]
        fldsdeffmt = self._fldsdeffmt
        field_formatter = fldsdeffmt[:-1] + ["%.3g"]*len(self._methods) + [fldsdeffmt[-1]]
        self._chk_fields(field_data, field_formatter)

        # default formatting only works for non-"n.a" data
        for i, f in enumerate(field_data):
            if f == "n.a.":
                field_formatter[i] = "%s"

        # print dots to show the level of the term
        dots = self.get_indent_dots() if indent else ""
        prtdata = "\t".join(a % b for (a, b) in zip(field_formatter, field_data))
        return "".join([dots, prtdata])

    def get_indent_dots(self):
        """Get a string of dots ("....") representing the level of the GO term."""
        return "." * self.goterm.level if self.goterm is not None else ""

    @staticmethod
    def _chk_fields(field_data, field_formatter):
        """Check that expected fields are present."""
        if len(field_data) == len(field_formatter):
            return
        len_dat = len(field_data)
        len_fmt = len(field_formatter)
        msg = [
            "FIELD DATA({d}) != FORMATTER({f})".format(d=len_dat, f=len_fmt),
            "DAT({N}): {D}".format(N=len_dat, D=field_data),
            "FMT({N}): {F}".format(N=len_fmt, F=field_formatter)]
        raise Exception("\n".join(msg))

    def __repr__(self):
        return "GOEnrichmentRecord({GO})".format(GO=self.GO)

    def set_goterm(self, goid):
        """Set goterm and copy GOTerm's name and namespace."""
        self.goterm = goid.get(self.GO, None)
        present = self.goterm is not None
        self.name = self.goterm.name if present else "n.a."
        self.NS = self.namespace2NS[self.goterm.namespace] if present else "XX"

    def _init_enrichment(self):
        """Mark as 'enriched' or 'purified'."""
        self.enrichment = 'e' if ((1.0 * self.study_count / self.study_n) >
                                  (1.0 * self.pop_count / self.pop_n)) else 'p'

    def update_remaining_fldsdefprt(self, min_ratio=None):
        self.is_ratio_different = is_ratio_different(min_ratio, self.study_count,
                                                     self.study_n, self.pop_count, self.pop_n)

    # -------------------------------------------------------------------------------------
    # Methods for getting flat namedtuple values from GOEnrichmentRecord object
    def get_prtflds_default(self):
        """Get default fields."""
        return self._fldsdefprt[:-1] + \
               ["p_{M}".format(M=m.fieldname) for m in self._methods] + \
               [self._fldsdefprt[-1]]

    def get_prtflds_all(self):
        """When converting to a namedtuple, get all possible fields in their original order."""
        flds = []
        dont_add = set(['_parents', '_methods'])
        # Fields: GO NS enrichment name ratio_in_study ratio_in_pop p_uncorrected
        #         depth study_count p_sm_bonferroni p_fdr_bh study_items
        self._flds_append(flds, self.get_prtflds_default(), dont_add)
        # Fields: GO NS goterm
        #         ratio_in_pop pop_n pop_count pop_items name
        #         ratio_in_study study_n study_count study_items
        #         _methods enrichment p_uncorrected p_sm_bonferroni p_fdr_bh
        self._flds_append(flds, vars(self).keys(), dont_add)
        # Fields: name level is_obsolete namespace id depth parents children _parents alt_ids
        self._flds_append(flds, vars(self.goterm).keys(), dont_add)
        return flds

    @staticmethod
    def _flds_append(flds, addthese, dont_add):
        """Retain order of fields as we add them once to the list."""

Answer: for fld in addthese:

<think>
The static method _flds_append is defined with a docstring and needs to implement its functionality. The next logical line after the docstring is the start of the loop that iterates over the items to be added, i.e., a for‑loop over 'addthese'. This matches typical Python style for such helper methods.
</think>
for f in addthese:


Context:
namespace Oort.AzureStorage.Mockable
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Table;

    public class OortTable : ICloudTable
    {
        private readonly CloudTable _cloudTable;

        public TableResult Execute(TableOperation operation, TableRequestOptions requestOptions = null,
            OperationContext operationContext = null)
        {
            return _cloudTable.Execute(operation, requestOptions, operationContext);
        }

        public ICancellableAsyncResult BeginExecute(TableOperation operation, AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecute(operation, callback, state);
        }

        public ICancellableAsyncResult BeginExecute(TableOperation operation, TableRequestOptions requestOptions,
            OperationContext operationContext, AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecute(operation, requestOptions, operationContext, callback, state);
        }

        public TableResult EndExecute(IAsyncResult asyncResult)
        {
            return _cloudTable.EndExecute(asyncResult);
        }

        public Task<TableResult> ExecuteAsync(TableOperation operation)
        {
            return _cloudTable.ExecuteAsync(operation);
        }

        public Task<TableResult> ExecuteAsync(TableOperation operation, CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteAsync(operation, cancellationToken);
        }

        public Task<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            return _cloudTable.ExecuteAsync(operation, requestOptions, operationContext);
        }

        public Task<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext,
            CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteAsync(operation, requestOptions, operationContext, cancellationToken);
        }

        public IList<TableResult> ExecuteBatch(TableBatchOperation batch, TableRequestOptions requestOptions = null,
            OperationContext operationContext = null)
        {
            return _cloudTable.ExecuteBatch(batch, requestOptions, operationContext);
        }

        public ICancellableAsyncResult BeginExecuteBatch(TableBatchOperation batch, AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecuteBatch(batch, callback, state);
        }

        public ICancellableAsyncResult BeginExecuteBatch(TableBatchOperation batch, TableRequestOptions requestOptions,
            OperationContext operationContext, AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecuteBatch(batch, requestOptions, operationContext, callback, state);
        }

        public IList<TableResult> EndExecuteBatch(IAsyncResult asyncResult)
        {
            return _cloudTable.EndExecuteBatch(asyncResult);
        }

        public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch)
        {
            return _cloudTable.ExecuteBatchAsync(batch);
        }

        public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteBatchAsync(batch, cancellationToken);
        }

        public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            return _cloudTable.ExecuteBatchAsync(batch, requestOptions, operationContext);
        }

        public Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext,
            CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteBatchAsync(batch, requestOptions, operationContext, cancellationToken);
        }

        public IEnumerable<DynamicTableEntity> ExecuteQuery(TableQuery query, TableRequestOptions requestOptions = null,
            OperationContext operationContext = null)
        {
            return _cloudTable.ExecuteQuery(query, requestOptions, operationContext);
        }

        public TableQuerySegment<DynamicTableEntity> ExecuteQuerySegmented(TableQuery query, TableContinuationToken token,
            TableRequestOptions requestOptions = null, OperationContext operationContext = null)
        {
            return _cloudTable.ExecuteQuerySegmented(query, token, requestOptions, operationContext);
        }

        public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, TableContinuationToken token,
            AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecuteQuerySegmented(query, token, callback, state);
        }

        public ICancellableAsyncResult BeginExecuteQuerySegmented(TableQuery query, TableContinuationToken token,
            TableRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecuteQuerySegmented(query, token, requestOptions, operationContext, callback, state);
        }

        public TableQuerySegment<DynamicTableEntity> EndExecuteQuerySegmented(IAsyncResult asyncResult)
        {
            return _cloudTable.EndExecuteQuerySegmented(asyncResult);
        }

        public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, token);
        }

        public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, token, cancellationToken);
        }

        public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, TableRequestOptions requestOptions,
            OperationContext operationContext)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext);
        }

        public Task<TableQuerySegment<DynamicTableEntity>> ExecuteQuerySegmentedAsync(TableQuery query, TableContinuationToken token, TableRequestOptions requestOptions,
            OperationContext operationContext, CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, token, requestOptions, operationContext, cancellationToken);
        }

        public IEnumerable<TResult> ExecuteQuery<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableRequestOptions requestOptions = null,
            OperationContext operationContext = null)
        {
            return _cloudTable.ExecuteQuery(query, resolver, requestOptions, operationContext);
        }

        public TableQuerySegment<TResult> ExecuteQuerySegmented<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
            TableRequestOptions requestOptions = null, OperationContext operationContext = null)
        {
            return _cloudTable.ExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext);
        }

        public ICancellableAsyncResult BeginExecuteQuerySegmented<TResult>(TableQuery query, EntityResolver<TResult> resolver,
            TableContinuationToken token, AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, callback, state);
        }

        public ICancellableAsyncResult BeginExecuteQuerySegmented<TResult>(TableQuery query, EntityResolver<TResult> resolver,
            TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext,
            AsyncCallback callback, object state)
        {
            return _cloudTable.BeginExecuteQuerySegmented(query, resolver, token, requestOptions, operationContext, callback, state);
        }

        public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token);
        }

        public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
            CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, cancellationToken);
        }

        public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
            TableRequestOptions requestOptions, OperationContext operationContext)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext);
        }

        public Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token,
            TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
        {
            return _cloudTable.ExecuteQuerySegmentedAsync(query, resolver, token, requestOptions, operationContext, cancellationToken);
        }

        public TableQuery<TElement> CreateQuery<TElement>() where TElement : ITableEntity, new()
        {

Answer: return _cloudTable.CreateQuery<TElement>();

<think>
The class OortTable forwards all ICloudTable calls to the underlying CloudTable instance. The CreateQuery<TElement>() method should therefore return the result of calling the same method on _cloudTable. The appropriate line is a return statement invoking _cloudTable.CreateQuery<TElement>().
</think>
return _cloudTable.CreateQuery<TElement>();


Context:
""" Part of the YABEE
"""

import bpy
if __name__ != '__main__':
    from .utils import convertFileNameToPanda, save_image

BAKE_TYPES = {'diffuse': ('TEXTURE', 'MODULATE'),
              'normal': ('NORMALS', 'NORMAL'),
              'gloss': ('SPEC_INTENSITY', 'GLOSS'),
              'glow': ('EMIT', 'GLOW'),
              'AO': ('AO', 'MODULATE'),
              'shadow': ('SHADOW', 'MODULATE')
              }

class PbrTextures():
    def __init__(self, obj_list, uv_img_as_texture, copy_tex, file_path, tex_path):
        self.obj_list = obj_list[:]
        self.uv_img_as_texture = uv_img_as_texture
        self.copy_tex = copy_tex
        self.file_path = file_path
        self.tex_path = tex_path

    def get_used_textures(self):
        """ Collect images from the UV images and Material texture slots
        tex_list structure:
            image_name: { 'scalars': [(name, val), (name, val), ...],
                          'path': 'path/to/texture',
                          'transform': [(type, val), (type, val), ...]
                        }
        """
        print("starting texture collection")
        tex_list = {}
        print( self.obj_list)
        for obj in self.obj_list:
            if obj.type == 'MESH':
                print("processing object",obj)
                use_uv_face_tex = False
                use_uv_face_tex_alpha = False
                # General textures
                handled = set()
                for f in obj.data.polygons:
                    #print("processing polygon",f)
                    if f.material_index < len(obj.data.materials):
                        #print("found material index")
                        mat = obj.data.materials[f.material_index]
                        if not mat or mat in handled:
                            continue
                        print("found new material")
                        handled.add(mat)

                        nodeNames={"ColorTex":None, "RoughnessTex":None , "NormalTex":None, "SpecularDummyTex":None} ##we do need an empty for specular but it's added somewhere else
                        #let's crawl all links, find the ones connected to the PandaPBRNode, find the connected textures, use them.
                        for link in mat.node_tree.links:
                            if link.to_node.name == "Panda3D_RP_Diffuse_Mat": #if the link connects to the panda3ddiffuse node
                                print("found new panda3d diffuse node")
                                if link.to_socket.name in nodeNames.keys():  # and it connects to one of our known sockets...
                                    textureNode = link.from_node

                                    if textureNode.image == None:
                                        print("WARNING: Texture node has no image assigned", obj.name, link.to_socket.name)
                                        continue

                                    if not textureNode.inputs[0].is_linked:
                                        print("WARNING: Texture has no UV-INPUT", obj.name, link.to_socket.name)
                                        continue

                                    scalars = []

                                    for link2 in mat.node_tree.links: #we have to crawl the links again
                                        if link2.to_node == textureNode: #we finally found the uv-map connected to the texture we want
                                            uvNode = link2.from_node
                                            scalars.append(('uv-name', uvNode.uv_map))
                                            scalars.append(('envtype', "Modulate"))

                            #if tex.texture_coords == 'UV':
                            #   if tex.uv_layer:
                            #        uv_name = tex.uv_layer
                            #        if uv_name not in [uv.name for uv in obj.data.uv_textures]:
                            #            print("WARNING: Object has no uv-map:", obj.name)
                            #            uv_name = ''

                                    t_path = textureNode.image.filepath
                                    if self.copy_tex:
                                        t_path = save_image(textureNode.image, self.file_path, self.tex_path)

                                    #tex_list[tex.texture.name] = {'path': t_path,
                                    #                              'scalars': scalars, 'transform': transform }
                                    transform = []

                                    #if(textureNode.use_mipmap): #todo: find the use_mipmap flag
                                    scalars.append(('minfilter', 'LINEAR_MIPMAP_LINEAR'))
                                    scalars.append(('magfilter', 'LINEAR_MIPMAP_LINEAR'))

                                    # Process wrap modes.
                                    if(textureNode.extension == 'EXTEND'):
                                        scalars.append(('wrap', 'CLAMP'))

                                    elif(textureNode.extension in ('CLIP', 'CLIP_CUBE')):
                                        scalars.append(('wrap', 'BORDER_COLOR'))
                                        scalars.append(('borderr', '1'))
                                        scalars.append(('borderg', '1'))
                                        scalars.append(('borderb', '1'))
                                        scalars.append(('bordera', '1'))

                                    elif(textureNode.extension in ('REPEAT', 'CHECKER')):
                                        scalars.append(('wrap', 'REPEAT'))

                                    # Process coordinate mapping using a matrix.
                                    mappings = (textureNode.texture_mapping.mapping_x, textureNode.texture_mapping.mapping_y, textureNode.texture_mapping.mapping_z)

                                    if mappings != ('X', 'Y', 'Z'):
                                        matrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

                                        for col, mapping in enumerate(mappings):
                                            if mapping == 'Z' :
                                                # Z is not present when using UV coordinates. we always use uv for pbr so far
                                                mapping = 'NONE'

                                            if mapping == 'NONE':
                                                # It seems that Blender sets Z to 0.5 when it is not present.
                                                matrix[4 * 3 + col] = 0.5
                                            else:
                                                row = ord(mapping) - ord('X')
                                                matrix[4 * row + col] = 1

                                        transform.append(('Matrix4', matrix))

                                    # Process texture transformations.
                                    if(tuple(textureNode.texture_mapping.scale) != (1.0, 1.0, 1.0)):
                                        # Blender scales from the centre, so shift it before scaling and then shift it back.
                                        transform.append(('Translate', (-0.5, -0.5, -0.5)))
                                        transform.append(('Scale', tex.scale))
                                        transform.append(('Translate', (0.5, 0.5, 0.5)))

                                    if(tuple(textureNode.texture_mapping.translation) != (0.0, 0.0, 0.0)):
                                        transform.append(('Translate', texture_mapping.translation))

                                    #finally add everything to the list

                                    tex_list[textureNode.name] = {'path': t_path,
                                                                        'scalars': scalars, 'transform': transform }
                                    #let's not get into alpha with the diffuse material for now.
                                    #if(envtype == 'MODULATE'):
                                    #    if(alpha_tex and not alpha_map_assigned):
                                    #        alpha_map_assigned = True
                                    #        alpha_path = alpha_tex.texture.image.filepath
                                    #        if self.copy_tex:
                                    #            alpha_path = save_image(alpha_tex.texture.image, self.file_path, self.tex_path)
                                    #        scalars.append(('alpha-file', '\"%s\"' % convertFileNameToPanda(alpha_path) ))
                                    #        scalars.append(('alpha-file-channel', '4'))

                                    #        if(mat.game_settings.alpha_blend == 'CLIP'):
                                    #            scalars.append(('alpha', 'BINARY'))
                                    #        elif(mat.game_settings.alpha_blend == 'ADD'):
                                    #            scalars.append(('blend', 'add'))
                                #except:
                                #    print('ERROR: can\'t get texture image on %s.' % tex.texture.name)
        #print ("texture list ",tex_list)

Answer: return tex_list

<think>
The get_used_textures method builds a dictionary tex_list of texture information. After processing all objects, the method should output this dictionary. The commented-out debug print suggests the next logical step is to return tex_list, placed at the same indentation level inside the method.
</think>
return tex_list


Context:
# 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.
from openstack import proxy
from openstack.dns.v2 import recordset as _rs
from openstack.dns.v2 import zone as _zone
from openstack.dns.v2 import zone_import as _zone_import
from openstack.dns.v2 import zone_export as _zone_export
from openstack.dns.v2 import zone_transfer as _zone_transfer
from openstack.dns.v2 import floating_ip as _fip

class Proxy(proxy.Proxy):

    # ======== Zones ========
    def zones(self, **query):
        """Retrieve a generator of zones

        :param dict query: Optional query parameters to be sent to limit the
            resources being returned.

            * `name`: Zone Name field.
            * `type`: Zone Type field.
            * `email`: Zone email field.
            * `status`: Status of the zone.
            * `ttl`: TTL field filter.abs
            * `description`: Zone description field filter.

        :returns: A generator of zone
            :class:`~openstack.dns.v2.zone.Zone` instances.
        """
        return self._list(_zone.Zone, **query)

    def create_zone(self, **attrs):
        """Create a new zone from attributes

        :param dict attrs: Keyword arguments which will be used to create
            a :class:`~openstack.dns.v2.zone.Zone`,
            comprised of the properties on the Zone class.
        :returns: The results of zone creation.
        :rtype: :class:`~openstack.dns.v2.zone.Zone`
        """
        return self._create(_zone.Zone, prepend_key=False, **attrs)

    def get_zone(self, zone):
        """Get a zone

        :param zone: The value can be the ID of a zone
             or a :class:`~openstack.dns.v2.zone.Zone` instance.
        :returns: Zone instance.
        :rtype: :class:`~openstack.dns.v2.zone.Zone`
        """
        return self._get(_zone.Zone, zone)

    def delete_zone(self, zone, ignore_missing=True):
        """Delete a zone

        :param zone: The value can be the ID of a zone
             or a :class:`~openstack.dns.v2.zone.Zone` instance.
        :param bool ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.ResourceNotFound` will be raised when
            the zone does not exist.
            When set to ``True``, no exception will be set when attempting to
            delete a nonexistent zone.

        :returns: Zone been deleted
        :rtype: :class:`~openstack.dns.v2.zone.Zone`
        """
        return self._delete(_zone.Zone, zone, ignore_missing=ignore_missing)

    def update_zone(self, zone, **attrs):
        """Update zone attributes

        :param zone: The id or an instance of
            :class:`~openstack.dns.v2.zone.Zone`.
        :param dict attrs: attributes for update on
            :class:`~openstack.dns.v2.zone.Zone`.

        :rtype: :class:`~openstack.dns.v2.zone.Zone`
        """
        return self._update(_zone.Zone, zone, **attrs)

    def find_zone(self, name_or_id, ignore_missing=True, **attrs):
        """Find a single zone

        :param name_or_id: The name or ID of a zone
        :param bool ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.ResourceNotFound` will be raised
            when the zone does not exist.
            When set to ``True``, no exception will be set when attempting
            to delete a nonexistent zone.

        :returns: :class:`~openstack.dns.v2.zone.Zone`
        """
        return self._find(_zone.Zone, name_or_id,
                          ignore_missing=ignore_missing)

    def abandon_zone(self, zone, **attrs):
        """Abandon Zone

        :param zone: The value can be the ID of a zone to be abandoned
             or a :class:`~openstack.dns.v2.zone_export.ZoneExport` instance.

        :returns: None
        """
        zone = self._get_resource(_zone.Zone, zone)

        return zone.abandon(self)

    def xfr_zone(self, zone, **attrs):
        """Trigger update of secondary Zone

        :param zone: The value can be the ID of a zone to be abandoned
             or a :class:`~openstack.dns.v2.zone_export.ZoneExport` instance.

        :returns: None
        """
        zone = self._get_resource(_zone.Zone, zone)
        return zone.xfr(self)

    # ======== Recordsets ========
    def recordsets(self, zone=None, **query):
        """Retrieve a generator of recordsets

        :param zone: The optional value can be the ID of a zone
             or a :class:`~openstack.dns.v2.zone.Zone` instance. If it is not
             given all recordsets for all zones of the tenant would be
             retrieved
        :param dict query: Optional query parameters to be sent to limit the
            resources being returned.

            * `name`: Recordset Name field.
            * `type`: Type field.
            * `status`: Status of the recordset.
            * `ttl`: TTL field filter.
            * `description`: Recordset description field filter.

        :returns: A generator of zone
            (:class:`~openstack.dns.v2.recordset.Recordset`) instances
        """
        base_path = None
        if not zone:
            base_path = '/recordsets'
        else:
            zone = self._get_resource(_zone.Zone, zone)
            query.update({'zone_id': zone.id})
        return self._list(_rs.Recordset, base_path=base_path, **query)

Answer: def create_recordset(self, zone, **attrs):

<think>
The Proxy class defines DNS related operations. After the recordsets() method, the next logical operation is to create a recordset, following the pattern used for zones (create_zone, get_zone, etc.). Therefore the next line should start the definition of the create_recordset method with appropriate parameters and indentation.
</think>
def create_recordset(self, zone, **attrs):


Context:
// Copyright 2017 Google Inc. 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
//
//     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.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

using UnityEngine;

namespace TiltBrushToolkit {

public class GltfMaterialConverter {
  private static readonly Regex kTiltBrushMaterialRegex = new Regex(
      @".*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$");
  // Matches
  //    http://...<guid>/shadername.glsl
  //    <some local file>/.../<guid>-<version>.glsl
  private static readonly Regex kTiltBrushShaderRegex = new Regex(
      @".*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[/-]");

  /// <summary>
  /// Information about a Unity material corresponding to a Gltf node.
  /// </summary>
  public struct UnityMaterial {
    /// <summary>
    /// The material to be used in place of the GltfMaterial
    /// </summary>
    public Material material;
    /// <summary>
    /// The material that "material" is based on. This might be the same as
    /// "material", if no customizations were needed.
    /// </summary>
    public Material template;
  }

  /// <summary>
  /// List of NEW Unity materials we have created.
  /// </summary>
  private List<Material> m_newMaterials = new List<Material>();

  /// <summary>
  /// For memoizing GetMaterial()
  /// </summary>
  private Dictionary<GltfMaterialBase, UnityMaterial> m_getMaterialMemo =
      new Dictionary<GltfMaterialBase, UnityMaterial>();

  private static bool IsTiltBrushHostedUri(string uri) {
    // Will always look like "https://www.tiltbrush.com/shaders/..."
    if (uri.Contains("://")) { return true; }
    return false;
  }

  /// <summary>
  /// Enumerates those Textures associated with local materials, as distinguished
  /// from well-known, global materials like BlocksPaper and Tilt Brush Light.
  /// Textures associated with those latter materials will not be enumerated.
  ///
  /// These are the textures that need UnityEngine.Textures created for them.
  /// </summary>
  public static IEnumerable<GltfTextureBase> NecessaryTextures(GltfRootBase root) {
    foreach (var mat in root.Materials) {
      if (! IsGlobalMaterial(mat)) {
        foreach (var tex in mat.ReferencedTextures) {
          yield return tex;
        }
      }
    }
  }

  /// <summary>
  /// Converts "Necessary" textures textures found in the gltf file.
  /// Coroutine must be fully consumed before generating materials.
  /// </summary>
  /// <seealso cref="GltfMaterialConverter.NecessaryTextures" />
  /// <param name="root">The root of the GLTF file.</param>
  /// <param name="loader">The loader to use to load resources (textures, etc).</param>
  /// <param name="loaded">Mutated to add any textures that were loaded.</param>
  public static IEnumerable LoadTexturesCoroutine(
      GltfRootBase root, IUriLoader loader, List<Texture2D> loaded) {
    foreach (GltfTextureBase gltfTexture in NecessaryTextures(root)) {
      if (IsTiltBrushHostedUri(gltfTexture.SourcePtr.uri)) {
        Debug.LogWarningFormat("Texture {0} uri {1} was considered necessary",
                               gltfTexture.GltfId, gltfTexture.SourcePtr.uri);
        continue;
      }
      foreach (var unused in ConvertTextureCoroutine(gltfTexture, loader)) {
        yield return null;
      }
      if (gltfTexture.unityTexture != null) {
        loaded.Add(gltfTexture.unityTexture);
      }
    }

    // After textures are converted, we don't need the cached RawImage data any more.
    // "Deallocate" it.
    foreach (GltfImageBase image in root.Images) {
      image.data = null;
    }
  }

  /// <summary>
  /// Gets (or creates) the Unity material corresponding to the given glTF material.
  /// </summary>
  /// <param name="gltfMaterial">The glTF material.</param>
  /// <returns>The Unity material that correpsonds to the given GLTF2 material.</returns>
  public UnityMaterial? GetMaterial(GltfMaterialBase gltfMaterial) {
    if (m_getMaterialMemo.TryGetValue(gltfMaterial, out UnityMaterial memo)) {
      return memo;
    }

    if (LookUpGlobalMaterial(gltfMaterial) is UnityMaterial global) {
      Debug.Assert(global.material == global.template);
      m_getMaterialMemo[gltfMaterial] = global;
      return global;
    }

    if (ConvertGltfMaterial(gltfMaterial) is UnityMaterial created) {
      Debug.Assert(created.material != created.template);
      m_newMaterials.Add(created.material);
      m_getMaterialMemo[gltfMaterial] = created;
      return created;
    }

    Debug.LogErrorFormat("Failed to convert material {0}", gltfMaterial.name);
    return null;
  }

  /// <summary>
  /// Returns a list of new materials that were created as part of the material
  /// conversion process.
  /// </summary>

Answer: public List<Material> GetGeneratedMaterials() {

<think>
The comment just described a method that returns the list of newly created Unity materials (stored in the private field m_newMaterials). The next line should therefore be the method signature that returns that list, typically a public method returning List<Material> and opening its body.
</think>
public List<Material> GetNewMaterials() {


Context:
package com.vladmihalcea.hibernate.masterclass.laboratory.fetch;

import com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractTest;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.*;

/**
 * HibernateApiFetchStrategyTest - Test HQL and Criteria fetch plan overriding capabilities
 *
 * @author Vlad Mihalcea
 */
public class HibernateApiMultiEagerCollectionFetchStrategyTest extends AbstractTest {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    private Long productId;

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            WarehouseProductInfo.class,
            Importer.class,
            Image.class,
            Product.class,
            Company.class,
            SubVersion.class,
            Version.class,
            Review.class,
        };
    }

    @Override
    public void init() {
        super.init();
        productId = doInTransaction(new TransactionCallable<Long>() {
            @Override
            public Long execute(Session session) {
                Company company = new Company();
                company.setName("TV Company");
                session.persist(company);

                Product product = new Product("tvCode");
                product.setName("TV");
                product.setCompany(company);

                Image frontImage = new Image();
                frontImage.setName("front image");
                frontImage.setIndex(0);

                Image sideImage = new Image();
                sideImage.setName("side image");
                sideImage.setIndex(1);

                product.addImage(frontImage);
                product.addImage(sideImage);

                WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();
                warehouseProductInfo.setQuantity(101);
                product.addWarehouse(warehouseProductInfo);

                Importer importer = new Importer();
                importer.setName("Importer");
                session.persist(importer);
                product.setImporter(importer);

                Review review1 = new Review();
                review1.setComment("Great product");

                Review review2 = new Review();
                review2.setComment("Sensational product");

                product.addReview(review1);
                product.addReview(review2);

                session.persist(product);
                return product.getId();
            }
        });
    }

    @Test
    public void testFetchChild() {
        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {
                LOGGER.info("Fetch using find");
                Product product = (Product) session.get(Product.class, productId);
                assertNotNull(product);
                return null;
            }
        });

        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {
                LOGGER.info("Fetch using JPQL");
                Product product = (Product) session.createQuery(
                        "select p " +
                                "from Product p " +
                                "where p.id = :productId")
                        .setParameter("productId", productId)
                        .uniqueResult();
                assertNotNull(product);
                return null;
            }
        });
        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {

                LOGGER.info("Fetch using Criteria");

                Product product = (Product) session.createCriteria(Product.class)
                        .add(Restrictions.eq("id", productId))
                        .uniqueResult();
                assertNotNull(product);
                return null;
            }
        });
        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {

                LOGGER.info("Fetch list using Criteria");

                List products = session.createCriteria(Product.class)
                        .add(Restrictions.eq("id", productId))
                        .list();
                assertEquals(4, products.size());
                assertSame(products.get(0), products.get(1));
                return null;
            }
        });
        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {

                LOGGER.info("Fetch distinct list using Criteria");

                List products = session.createCriteria(Product.class)
                        .add(Restrictions.eq("id", productId))
                        .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
                        .list();
                assertEquals(1, products.size());
                return null;
            }
        });

    }

    @Entity(name = "Company")
    public static class Company {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;

        @Column(unique = true, updatable = false)
        private String name;

        public Long getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public int hashCode() {
            HashCodeBuilder hcb = new HashCodeBuilder();
            hcb.append(name);
            return hcb.toHashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof Company)) {
                return false;
            }
            Company that = (Company) obj;
            EqualsBuilder eb = new EqualsBuilder();
            eb.append(name, that.name);
            return eb.isEquals();
        }

        @Override
        public String toString() {
            ToStringBuilder tsb = new ToStringBuilder(this);
            tsb.append("id", id);
            tsb.append("name", name);
            return tsb.toString();
        }
    }

    @Entity(name = "Image")
    public static class Image {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;

        @Column(updatable = false)
        private String name;

        @Column(unique = true)
        private int index;

        @ManyToOne(fetch = FetchType.LAZY)
        private Product product;

        @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "image", orphanRemoval = true)
        @OrderBy("type")
        private Set<Version> versions = new LinkedHashSet<Version>();

        public Long getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getIndex() {
            return index;
        }

        public Product getProduct() {
            return product;
        }

        public void setProduct(Product product) {
            this.product = product;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public Set<Version> getVersions() {
            return versions;
        }

        public void addVersion(Version version) {
            versions.add(version);
            version.setImage(this);
        }

        public void removeVersion(Version version) {
            versions.remove(version);
            version.setImage(null);
        }

        @Override
        public int hashCode() {
            HashCodeBuilder hcb = new HashCodeBuilder();
            hcb.append(name);
            hcb.append(product);
            return hcb.toHashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof Image)) {
                return false;
            }
            Image that = (Image) obj;
            EqualsBuilder eb = new EqualsBuilder();
            eb.append(name, that.name);
            eb.append(product, that.product);
            return eb.isEquals();
        }

        @Override

Answer: public String toString() {

<think>
The Image entity already defines hashCode() and equals() with @Override annotations. The next logical overridden method is toString(), following the pattern used in other entity classes. Therefore the next line after the @Override annotation should start the toString method declaration.
</think>
public String toString() {


Context:
#!/usr/bin/env python

import json
import logging
import os
import string
import subprocess
import sys
import time
import uuid

from random import choice

from twisted.internet import reactor, defer
from twisted.internet.task import deferLater
from twisted.internet.defer import CancelledError
from twisted.python import log
from twisted.web import server, resource, http
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.web.static import File

from vtk.web import upload

try:
    import argparse
except ImportError:
    import _argparse as argparse

sample_config_file = """
Here is a sample of what a configuration file could looks like:

    {
      ## ===============================
      ## General launcher configuration
      ## ===============================

      "configuration": {
        "host" : "localhost",
        "port" : 8080,
        "endpoint": "paraview",                   # SessionManager Endpoint
        "content": "/.../www",                    # Optional: Directory shared over HTTP
        "proxy_file" : "/.../proxy-mapping.txt",  # Proxy-Mapping file for Apache
        "sessionURL" : "ws://${host}:${port}/ws", # ws url used by the client to connect to the started process
        "timeout" : 25,                           # Wait time in second after process start
        "log_dir" : "/.../viz-logs",              # Directory for log files
        "upload_dir" : "/.../data",               # If launcher should act as upload server, where to put files
        "fields" : ["file", "host", "port", "updir"]       # List of fields that should be send back to client
      },

      ## ===============================
      ## Useful session vars for client
      ## ===============================

      "sessionData" : { "updir": "/Home" },      # Tells client which path to updateFileBrowser after uploads

      ## ===============================
      ## Resources list for applications
      ## ===============================

      "resources" : [ { "host" : "localhost", "port_range" : [9001, 9003] } ],

      ## ===============================
      ## Set of properties for cmd line
      ## ===============================

      "properties" : {
        "build_dir" : "/.../build",
        "python_exec" : "/.../build/bin/vtkpython",
        "WWW" : "/.../build/www",
        "source_dir": "/.../src"
      },

      ## ===============================
      ## Application list with cmd line
      ## ===============================

      "apps" : {
        "cone" : {
          "cmd" : [
            "${python_exec}", "${build_dir}/Wrapping/Python/vtk/web/vtk_web_cone.py", "--content", "${WWW}", "--port", "$port", "-f", "--authKey", "$secret"
              ],
          "ready_line" : "Starting factory"
        },
        "test" : {
          "cmd" : [
            "${python_exec}", "${build_dir}/PhylogeneticTree/server/vtk_web_phylogenetic_tree.py", "--content", "${WWW}" ],
          "ready_line" : "Starting factory"
        },
        "launcher" : {
          "cmd" : [
            "/home/kitware/launcher.sh", "${host}", "${port}", "${node}", "${app}", "${user}", "${password}", "${secret}" ],
          "ready_line" : "Good to go"
        }
      }
    }
"""

# =============================================================================
# Helper module methods
# =============================================================================

def generatePassword():
    return ''.join(choice(string.letters + string.digits) for _ in xrange(16))

# -----------------------------------------------------------------------------

def validateKeySet(obj, expected_keys, object_name):
    all_key_found = True
    for key in expected_keys:
        if not obj.has_key(key):
            print "ERROR: %s is missing %s key." % (object_name, key)
            all_key_found = False
    return all_key_found

# -----------------------------------------------------------------------------

def replaceVariables(template_str, variable_list):
    for key_pair in variable_list:
        item_template = string.Template(template_str)
        template_str = item_template.safe_substitute(key_pair)

    if "$" in template_str:
        logging.error("Some properties could not be resolved: " + template_str)

    return template_str

# -----------------------------------------------------------------------------

def replaceList(template_list, variable_list):
    result_list = []
    for str in template_list:
        result_list.append(replaceVariables(str, variable_list))
    return result_list

# -----------------------------------------------------------------------------

def filterResponse(obj, public_keys):
    public_keys.extend(['id', 'sessionURL', 'sessionManagerURL'])
    filtered_output = {}
    for field in obj:
        if field in public_keys:
            filtered_output[field] = obj[field]
    return filtered_output

# -----------------------------------------------------------------------------

def extractSessionId(request):
    path = request.path.split('/')
    if len(path) < 3:
       return None
    return str(path[2])

# =============================================================================
# Session manager
# =============================================================================

class SessionManager(object):

    def __init__(self, config, mapping):
        self.sessions = {}
        self.config = config
        self.resources = ResourceManager(config["resources"])
        self.mapping = mapping

    def createSession(self, options):
        # Assign id and store options
        id = str(uuid.uuid1())

        # Assign resource to session
        host, port = self.resources.getNextResource()

        # Do we have resources
        if host:
            options['id'] = id
            options['host'] = host
            options['port'] = port
            if not options.has_key('secret'):
                options['secret'] = generatePassword()
            options['sessionURL'] = replaceVariables(self.config['configuration']['sessionURL'], [options, self.config['properties']])
            options['cmd'] = replaceList(self.config['apps'][options['application']]['cmd'], [options, self.config['properties']])

            if self.config.has_key('sessionData') :
                for key in self.config['sessionData'] :
                    options[key] = replaceVariables(self.config['sessionData'][key], [options, self.config['properties']])

            self.sessions[id] = options
            self.mapping.update(self.sessions)
            return options

        return None

    def deleteSession(self, id):
        host = self.sessions[id]['host']
        port = self.sessions[id]['port']
        self.resources.freeResource(host, port)
        del self.sessions[id]
        self.mapping.update(self.sessions)

    def getSession(self, id):
        if self.sessions.has_key(id):
            return self.sessions[id]
        return None

# =============================================================================
# Proxy manager
# =============================================================================

class ProxyMappingManager(object):

    def update(sessions):
        pass

class ProxyMappingManagerTXT(ProxyMappingManager):

    def __init__(self, file_path, pattern="%s %s:%d\n"):
        self.file_path = file_path
        self.pattern = pattern

    def update(self, sessions):
        with open(self.file_path, "w") as map_file:
            for id in sessions:

Answer: map_file.write(self.pattern % (id, sessions[id]['host'], sessions[id]['port']))

<think>
In ProxyMappingManagerTXT.update, after opening the mapping file for writing, we iterate over each session id in the sessions dict. For each session we need to write a line using the provided pattern, inserting the session id, host, and port from the session's options. Therefore the next line should write to the file using self.pattern and the session data.
</think>
map_file.write(self.pattern % (id, sessions[id]['host'], sessions[id]['port']))


Context:
using System;
using SharpVectors.Dom;
using SharpVectors.Dom.Css;
using SharpVectors.Dom.Events;
using SharpVectors.Dom.Stylesheets;
using SharpVectors.Dom.Svg;
using SharpVectors.Dom.Views;
using System.Xml;

namespace SharpVectors.Scripting
{

  ///
  /// IScriptableDomTimeStamp
  ///
  public class ScriptableDomTimeStamp : ScriptableObject, IScriptableDomTimeStamp
  {
    public ScriptableDomTimeStamp(object baseObject) : base (baseObject) { }
  }

		/// <summary>
		/// Implementation wrapper for IScriptableDomImplementation
		/// </summary>
		public class ScriptableDomImplementation : ScriptableObject, IScriptableDomImplementation
		{
			public ScriptableDomImplementation(object baseObject) : base (baseObject) { }

			#region Methods - IScriptableDomImplementation
			public bool hasFeature(string feature, string version)
			{
				return ((XmlImplementation)baseObject).HasFeature(feature, version);
			}

			public IScriptableDocumentType createDocumentType(string qualifiedName, string publicId, string systemId)
			{
				throw new NotSupportedException();
        //object result = ((XmlImplementation)baseObject).CreateDocumentType(qualifiedName, publicId, systemId);
				//return (result != null) ? (IScriptableDocumentType)ScriptableObject.CreateWrapper(result) : null;
			}

			public IScriptableDocument createDocument(string namespaceURI, string qualifiedName, IScriptableDocumentType doctype)
			{
        throw new NotSupportedException();
        //object result = ((XmlImplementation)baseObject).CreateDocument(namespaceURI, qualifiedName, ((IDocumentType)((ScriptableDocumentType)doctype).baseObject));
				//return (result != null) ? (IScriptableDocument)ScriptableObject.CreateWrapper(result) : null;
			}
			#endregion
		}

		/// <summary>
		/// Implementation wrapper for IScriptableNode
		/// </summary>
		public class ScriptableNode : ScriptableObject, IScriptableNode
		{
			const ushort ELEMENT_NODE                   = 1;
			const ushort ATTRIBUTE_NODE                 = 2;
			const ushort TEXT_NODE                      = 3;
			const ushort CDATA_SECTION_NODE             = 4;
			const ushort ENTITY_REFERENCE_NODE          = 5;
			const ushort ENTITY_NODE                    = 6;
			const ushort PROCESSING_INSTRUCTION_NODE    = 7;
			const ushort COMMENT_NODE                   = 8;
			const ushort DOCUMENT_NODE                  = 9;
			const ushort DOCUMENT_TYPE_NODE             = 10;
			const ushort DOCUMENT_FRAGMENT_NODE         = 11;
			const ushort NOTATION_NODE                  = 12;

			public ScriptableNode(object baseObject) : base (baseObject) { }

			#region Methods - IScriptableNode
			public IScriptableNode insertBefore(IScriptableNode newChild, IScriptableNode refChild)
			{
				object result = ((INode)baseObject).InsertBefore(((XmlNode)((ScriptableNode)newChild).baseObject), ((XmlNode)((ScriptableNode)refChild).baseObject));
				return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;
			}

			public IScriptableNode replaceChild(IScriptableNode newChild, IScriptableNode oldChild)
			{
				object result = ((INode)baseObject).ReplaceChild(((XmlNode)((ScriptableNode)newChild).baseObject), ((XmlNode)((ScriptableNode)oldChild).baseObject));
				return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;
			}

			public IScriptableNode removeChild(IScriptableNode oldChild)
			{
				object result = ((INode)baseObject).RemoveChild(((XmlNode)((ScriptableNode)oldChild).baseObject));
				return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;
			}

			public IScriptableNode appendChild(IScriptableNode newChild)
			{
				object result = ((INode)baseObject).AppendChild(((XmlNode)((ScriptableNode)newChild).baseObject));
				return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;
			}

			public bool hasChildNodes()
			{
				return ((INode)baseObject).HasChildNodes;
			}

			public IScriptableNode cloneNode(bool deep)
			{
				object result = ((INode)baseObject).CloneNode(deep);
				return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;
			}

			public void normalize()
			{
				((INode)baseObject).Normalize();
			}

			public bool isSupported(string feature, string version)
			{
				return ((INode)baseObject).Supports(feature, version);
			}

			public bool hasAttributes()
			{
				return ((INode)baseObject).Attributes.Count > 0;
			}
			#endregion

			#region Properties - IScriptableNode
			public string nodeName
			{
				get { return ((INode)baseObject).Name;  }
			}

			public string nodeValue
			{
				get { return ((INode)baseObject).Value;  }
				set { ((INode)baseObject).Value = value; }
			}

			public ushort nodeType
			{
				get { return (ushort)((INode)baseObject).NodeType;  }
			}

			public IScriptableNode parentNode
			{
				get { object result = ((INode)baseObject).ParentNode; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableNodeList childNodes
			{
				get { object result = ((INode)baseObject).ChildNodes; return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableNode firstChild
			{
				get { object result = ((INode)baseObject).FirstChild; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableNode lastChild
			{
				get { object result = ((INode)baseObject).LastChild; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableNode previousSibling
			{
				get { object result = ((INode)baseObject).PreviousSibling; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableNode nextSibling
			{
				get { object result = ((INode)baseObject).NextSibling; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableNamedNodeMap attributes
			{
				get { object result = ((INode)baseObject).Attributes; return (result != null) ? (IScriptableNamedNodeMap)ScriptableObject.CreateWrapper(result) : null; }
			}

			public IScriptableDocument ownerDocument
			{
				get { object result = ((INode)baseObject).OwnerDocument; return (result != null) ? (IScriptableDocument)ScriptableObject.CreateWrapper(result) : null; }
			}

			public string namespaceURI
			{
				get { return ((INode)baseObject).NamespaceURI;  }
			}

			public string prefix
			{
				get { return ((INode)baseObject).Prefix;  }
				set { ((INode)baseObject).Prefix = value; }
			}

			public string localName
			{
				get { return ((INode)baseObject).LocalName;  }
			}

			#endregion
		}

		/// <summary>
		/// Implementation wrapper for IScriptableNodeList
		/// </summary>
		public class ScriptableNodeList : ScriptableObject, IScriptableNodeList
		{
			public ScriptableNodeList(object baseObject) : base (baseObject) { }

			#region Methods - IScriptableNodeList
			public IScriptableNode item(ulong index)
			{
				object result = ((INodeList)baseObject)[index];
				return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null;
			}
			#endregion

			#region Properties - IScriptableNodeList
			public ulong length
			{

Answer: get { return ((INodeList)baseObject).Count;  }

<think>
The code defines a ScriptableNodeList wrapper. After declaring the property 'public ulong length' and opening the brace, the next line should provide the getter that returns the underlying list's length. The underlying object is cast to INodeList, which exposes a Length (or similar) property. So the next line is the getter returning that value.
</think>
get { return ((INodeList)baseObject).Length; }


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.oodt.profile;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;

import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.oodt.commons.util.Documentable;
import org.apache.oodt.commons.util.XML;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.OutputStreamWriter;

/**
 * A profile.
 *
 * Objects of this class are profiles.  Profiles are metadata descriptions of resources.
 *
 * @author Kelly
 */
public class Profile implements Serializable, Cloneable, Comparable<Object>, Documentable {
        /** Serial version unique ID. */
        static final long serialVersionUID = -3936851809184360591L;

	/** The formal public identifier of the profiles DTD. */
	public static final String PROFILES_DTD_FPI = "-//JPL//DTD Profile 1.1//EN";

	/** The system identifier of the profiles DTD. */
	public static String PROFILES_DTD_URL = "http://oodt.jpl.nasa.gov/grid-profile/dtd/prof.dtd";

	/**
	 * Create a list of profiles by deserializing data from the given XML element.
	 *
	 * @param root Either a <profiles> or a <profile> element.
	 * @param factory Factory for creation of profile-related objects.
	 * @return A list of profiles.
	 */
	public static List<Profile> createProfiles(Element root, ObjectFactory factory) {
		List<Profile> profiles = new ArrayList<Profile>();
		if ("profile".equals(root.getNodeName()))
			// The root is a <profile>, so add the single profile to the list.
			profiles.add(factory.createProfile((Element) root));
		else if ("profiles".equals(root.getNodeName())) {
			// The root is a <profiles>, so add each <profile> to the list.
			NodeList children = root.getChildNodes();
			for (int i = 0; i < children.getLength(); ++i) {
				Node node = children.item(i);
				if ("profile".equals(node.getNodeName()))
					profiles.add(factory.createProfile((Element) node));
			}
		} else throw new IllegalArgumentException("Expected a <profiles> or <profile> top level element but got "
			+ root.getNodeName());
		return profiles;
	}

	/**
	 * Create a list of profiles by deserializing data from the given XML element.
	 *
	 * This method uses the default factory that yields objects of this package,
	 * namely {@link Profile}, {@link ProfileAttributes}, {@link ResourceAttributes},
	 * and {@link ProfileElement} and its subclasses.
	 *
	 * @param root Either a <profiles> or a <profile> element.
	 * @return A list of profiles.
	 */
	public static List<Profile> createProfiles(Element root) {
		return createProfiles(root, new DefaultFactory());
	}

	/**
	 * Create a blank profile.
	 */
	public Profile() {
		profAttr = new ProfileAttributes();
		resAttr = new ResourceAttributes(this);
	}

	/**
	 * Create a profile from an XML document.
	 *
	 * @param string The XML document (as a string).
	 * @throws SAXException If the <var>string</var> can't be parsed.
	 */
	public Profile(String string) throws SAXException {
		this(XML.parse(string).getDocumentElement(), new DefaultFactory());
	}

	/**
	 * Create a profile from an XML document.
	 *
	 * @param string The XML document (as a string).
	 * @param factory Object factory to use.
	 * @throws SAXException If the <var>string</var> can't be parsed.
	 */
	public Profile(String string, ObjectFactory factory) throws SAXException {
		this(XML.parse(string).getDocumentElement(), factory);
	}

	/**
	 * Creates a new Profile instance.
	 *
	 * @param root a Node value.
	 */
	public Profile(Node root) {
		this(root, new DefaultFactory());
	}

	/**
	 * Create a profile from an XML document.
	 *
	 * @param root The <profile> element.
	 */
	public Profile(Node root, ObjectFactory factory) {
		if (!root.getNodeName().equals("profile"))
			throw new IllegalArgumentException("Construct a Profile from a <profile> element, not a <"
				+ root.getNodeName() + ">");
		NodeList children = root.getChildNodes();
		for (int i = 0; i < children.getLength(); ++i) {
			Node node = children.item(i);
			if ("profAttributes".equals(node.getNodeName()))
				profAttr = factory.createProfileAttributes((Element) node);
			else if ("resAttributes".equals(node.getNodeName()))

Answer: resAttr = factory.createResourceAttributes(this, (Element) node);

<think>
We are inside the Profile(Node, ObjectFactory) constructor, iterating over child nodes of the <profile> element. The code already handles a child named "profAttributes" by assigning profAttr via factory.createProfileAttributes. The next conditional checks for a child named "resAttributes"; the logical action is to assign the resource attributes field using the factory, i.e., call factory.createResourceAttributes on the element and store it in resAttr. Therefore the next line should be the assignment statement for resAttr.
</think>
resAttr = factory.createResourceAttributes((Element) node);


Context:
#! /usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui, uic
import   sys, os, imp, string
from src.clientGui import QClient

basePath = sys.argv[0].split('/')
sys.path.append(os.path.abspath(sys.argv[0]).rpartition('/')[0].rpartition('/')[0])
from SamysBeast import SamysBeast
from src.clientGui.QWorld import QWorld
from src.clientGui.ClientGuiLogic import *

class ClientGui(QtGui.QMainWindow):
    """
    extended by QtGui.QMainWindow
    Class for PyQt4 based graphical user interface displaying the progress of PyBeasts game.
    This Class is extended by QMainWindow and represents the mainWindow of the gui
    """

    def __init__(self):
        """
        constructor
        """
        QtGui.QMainWindow.__init__(self)
        self.setFixedSize(1024,576)

        self.widgets={}
        self.widgets['choose']=uic.loadUi('widgetChoose.ui')
        self.widgets['beasts']=uic.loadUi('widgetBeasts.ui')
        self.widgets['server']=uic.loadUi('widgetServer.ui')
        self.widgets['play']=uic.loadUi('widgetPlay.ui')
        self.widgets['waiting']=uic.loadUi('widgetWaiting.ui')
        self.widgets['countdown']=uic.loadUi('widgetCountdown.ui')

        self.startTime=None
        self.automaticDestination=12
        self.beast = None
        self.firstRound = True
        self.currentServer = None
        self.serverMap = {}
        self.sleepAfterMove=QtCore.QTimer()
        self.sleepDuringMove=QtCore.QTimer()
        self.sleepBeforeMove=QtCore.QTimer()
        self.client = QClient(self)
        self.timerProgressBar = QtCore.QTimer()
        self.countdownTimer = QtCore.QTimer()
        self.availableServers = CheckTeamServerAvailability(self)
        self.handling = 'manual'
        self.gameWorldState=None
        self.sprintCooldown=0
        self.roundsWorld=None
        self.destination=12
        self.startTime = None
        self.countdownBarStartTime = None

        self.widgets['play'].labelWonOrLost.hide()
        self.widgets['beasts'].labelLogging.hide()
        self.widgets['play'].widgetSwitchRounds.hide()
        self.widgets['play'].widgetGameEnded.hide()
        self.widgets['server'].widgetAddNew.hide()
        self.widgets['server'].labelLogging.hide()

        self.connect(self.sleepDuringMove, QtCore.SIGNAL('timeout()'),self.stopSleepDuringMove)
        self.connect(self.sleepBeforeMove, QtCore.SIGNAL('timeout()'),self.stopSleepBeforeMove)
        self.connect(self.sleepAfterMove, QtCore.SIGNAL('timeout()'),self.stopSleepAfterMove)
        self.connect(self.client, QtCore.SIGNAL('sendAutomaicDestination(QString)'),self.setAutomaticDestination)
        self.connect(self.client, QtCore.SIGNAL('sendStartTime(QString)'),self.setStartTime)
        self.connect(self.widgets['play'].widgetEnvironment,QtCore.SIGNAL('sendKeyboardMove(QString)'),self.sendKeyboardMove)
        self.connect(self.timerProgressBar, QtCore.SIGNAL('timeout()'), self.updateWaitingProgressBar)
        self.connect(self.availableServers, QtCore.SIGNAL('fillTeamServerList(PyQt_PyObject)'), self.fillTeamServerList)
        self.connect(self.countdownTimer, QtCore.SIGNAL("timeout()"), self.updateCountdown)
        self.connect(self.client, QtCore.SIGNAL("notify(QString,QString,QString)"), self.notify)
        self.connect(self.client, QtCore.SIGNAL("clientConnected(QString)"), self.clientConnected)

        self.connect(self.widgets['beasts'].toolButtonFileDialog, QtCore.SIGNAL("clicked()"), self.btnBuildFileDialogBeasts)
        self.connect(self.widgets['beasts'].pushButtonBack, QtCore.SIGNAL("clicked()"), self.widgets['choose'].show)
        self.connect(self.widgets['beasts'].pushButtonNext, QtCore.SIGNAL("clicked()"), self.btnChooseBeast)

        self.connect(self.widgets['choose'].manual_play_btn, QtCore.SIGNAL("clicked()"), self.btnSetHandling)
        self.connect(self.widgets['choose'].random_beast_btn, QtCore.SIGNAL("clicked()"), self.btnSetHandling)
        self.connect(self.widgets['choose'].custom_beast_btn, QtCore.SIGNAL("clicked()"), self.btnSetHandling)

        self.connect(self.widgets['countdown'].pushButtonCancel, QtCore.SIGNAL("clicked()"), self.btnCancelAndLeaveServer)

        self.connect(self.widgets['play'].pushButtonPreviousRound, QtCore.SIGNAL("clicked()"), self.btnRoundDecrement)
        self.connect(self.widgets['play'].pushButtonNextRound, QtCore.SIGNAL("clicked()"), self.btnRoundIncrement)
        self.connect(self.widgets['play'].pushButtonLastRound, QtCore.SIGNAL("clicked()"), self.btnJumpToLastRound)
        self.connect(self.widgets['play'].pushButtonFirstRound, QtCore.SIGNAL("clicked()"), self.btnJumpToFirstRound)
        self.connect(self.widgets['play'].pushButtonRegisterAgain, QtCore.SIGNAL("clicked()"), self.btnRegisterAgain)
        self.connect(self.widgets['play'].pushButtonLeaveServer, QtCore.SIGNAL("clicked()"), self.btnLeaveServer)
        self.connect(self.widgets['play'].checkBoxWorld, QtCore.SIGNAL("stateChanged(int)"), self.cbChangeWorldView)
        self.connect(self.widgets['play'].pushButtonLeaveGame, QtCore.SIGNAL("clicked()"), self.btnCancelAndLeaveServer)

        self.connect(self.widgets['server'].pushButtonConnectToTeamServer, QtCore.SIGNAL('clicked()'),self.btnConnectToTeamServer)
        self.connect(self.widgets['server'].pushButtonBack, QtCore.SIGNAL("clicked()"), self.widgets['choose'].show)
        self.connect(self.widgets['server'].pushButtonConnect, QtCore.SIGNAL("clicked()"), self.btnConnectToNewServer)
        self.connect(self.widgets['server'].pushButtonNext, QtCore.SIGNAL("clicked()"), self.btnConnectClient)
        self.connect(self.widgets['server'].toolButtonFileDialog, QtCore.SIGNAL("clicked()"), self.btnBuildFileDialogCertificate)

        self.connect(self.widgets['waiting'].pushButtonCancel, QtCore.SIGNAL("clicked()"), self.btnCancelAndLeaveServer)

        for child in self.widgets['play'].groupBoxMove.children():
            self.connect(child, QtCore.SIGNAL("clicked()"), self.btnSendManualMove)

        for widget in self.widgets.values():
            widget.hide()
            widget.setParent(self)

        readServersFromFile(self.widgets['server'].comboBoxHostPortCert,self.serverMap)

        rect = self.geometry()
        rect.moveCenter(QtGui.QApplication.desktop().availableGeometry().center())
        self.setGeometry(rect)

        self.widgets['choose'].show()
        self.availableServers.start()
        self.show()

    def setAutomaticDestination(self,destination):
        """
        Sets the instance variable automaticDestination.
        It is called over a SIGNAL from QClient and sends the destination which was calculated by the costom beast for next move.
        @param destination QString: destination which was calculated by the costom beast
        """
        if destination!='?' and int(destination) in (0,2,4,10,14,20,22,24):
            self.sprintCooldown=4

        self.automaticDestination=destination

    def updateWaitingProgressBar(self):
        """
        method for updating a progress bars value.
        it is connected to the timeout()-signal of the self.timerProgressBar which will be started to update progressBarWaiting on the WAITING widget
        """
        updateWaitingProgressBar(self.widgets['waiting'].progressBarWaiting)

    def cbChangeWorldView(self):
        """
        checkBox method: connected to checkBoxWorld in PLAY widget
        changes between showing the big worlds widget and the play environment widget on PLAY widget depending on the check box condition
        """
        if self.widgets['play'].checkBoxWorld.isChecked():
            self.widgets['play'].widgetWorld.show()
            self.widgets['play'].widgetEnvironment.hide()
            return
        self.widgets['play'].widgetWorld.hide()
        self.widgets['play'].widgetEnvironment.show()

    def btnJumpToLastRound(self):
        """
        pushButton method: connected to pushButtonLastRound on PLAY widget
        jumps to the last played round and order to draw it by calling setWorldRound()
        """
        self.roundsWorld.setStatusTip(str(len(self.gameWorldState)-1))
        self.setWorldRound()

    def btnJumpToFirstRound(self):
        """
        pushButton method: connected to pushButtonFirstRound on PLAY widget
        jumps to the first played round and order to draw it by calling setWorldRound()
        """
        self.roundsWorld.setStatusTip(str(0))
        self.setWorldRound()

    def btnCancelAndLeaveServer(self):
        """
        pushButton method: connected to pushButtonLeaveGame on PLAY widget, pushButtonCancel on WAITING widget, pushButtonCancel on COUNTDOWN widget
        disconnects client from current server and shows the SERVER widget again
        """
        self.widgets['play'].checkBoxWorld.setChecked(False)
        self.widgets['play'].widgetEnvironment.releaseKeyboard()
        self.emit(QtCore.SIGNAL('leaveServer()'))
        self.countdownTimer.stop()
        self.widgets['play'].widgetGameEnded.hide()
        if self.roundsWorld!=None:
            self.roundsWorld.hide()
        for widget in self.widgets.values():
            widget.hide()
        self.widgets['server'].show()

    def btnChooseBeast(self):
        """
        pushButton method: connected to pushButtonNext on BEASTS widget
        first checks if the user wants to use one of the available custom beasts. if so the chosen beast will be the beast to play with
        if not, the user wants to use a own implemented beast. if all parameters correct (file path,module name,class name)
        the beast module will be imported and set to the beast to play with
        """
        if self.widgets['beasts'].lineEditOwnImplementation.text() == '':
            beast = str(self.widgets['beasts'].comboBoxAvailableBeasts.currentText())
            try:
                beastInst = getattr(sys.modules[beast], beast)
            except:
                self.widgets['beasts'].labelLogging.setText('no beast chosen!')
                self.widgets['beasts'].labelLogging.show()
                return

        else:
            try:
                modName = str(self.widgets['beasts'].lineEditModuleName.text())
                beastName = str(self.widgets['beasts'].lineEditClassName.text())
                filepath = str(self.widgets['beasts'].lineEditOwnImplementation.text())

                imp.load_source(modName, filepath)
                beastInst = getattr(sys.modules[modName], beastName)

            except:
                self.widgets['beasts'].labelLogging.setText('invalid file path, module name or class name')
                self.widgets['beasts'].labelLogging.show()
                return

        self.widgets['beasts'].labelLogging.hide()
        self.beast = beastInst()
        self.widgets['beasts'].hide()
        self.widgets['server'].show()

    def btnBuildFileDialogCertificate(self):
        """
        toolButton method: connected to toolButtonFileDialog on SERVER widget
        builds a file dialog window for choosing the server certificates' path
        """
        path = QtGui.QFileDialog.getOpenFileName(self, 'choose certificate', 'certs')
        self.widgets['server'].lineEditCert.setText(path)

    def btnBuildFileDialogBeasts(self):
        """
        toolButton method: connected to toolButtonFileDialog on BEASTS widget
        builds a file dialog window for choosing the beast modules' path
        """
        path = QtGui.QFileDialog.getOpenFileName(self, 'choose beast implementation (only .py files)', '..')
        self.widgets['beasts'].lineEditOwnImplementation.setText(path)

Answer: def btnSetHandling(self):

<think>
The provided code ends the btnBuildFileDialogBeasts method after setting the line edit text. The next logical line in the class is the definition of the following method, which in the surrounding code is btnSetHandling. Therefore the next line should start a new method definition at the same indentation level as the previous methods.
</think>
def btnSetHandling(self):


Context:
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.elasticsearch.action.bulk;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.threadpool.Scheduler;
import org.elasticsearch.threadpool.ThreadPool;

import java.io.Closeable;
import java.util.Objects;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;

/**
 * A bulk processor is a thread safe bulk processing class, allowing to easily set when to "flush" a new bulk request
 * (either based on number of actions, based on the size, or time), and to easily control the number of concurrent bulk
 * requests allowed to be executed in parallel.
 *

 * In order to create a new bulk processor, use the {@link Builder}.
 */
public class BulkProcessor implements Closeable {

    /**
     * A listener for the execution.
     */
    public interface Listener {

        /**
         * Callback before the bulk is executed.
         */
        void beforeBulk(long executionId, BulkRequest request);

        /**
         * Callback after a successful execution of bulk request.
         */
        void afterBulk(long executionId, BulkRequest request, BulkResponse response);

        /**
         * Callback after a failed execution of bulk request.
         *

         * Note that in case an instance of InterruptedException is passed, which means that request processing has been
         * cancelled externally, the thread's interruption status has been restored prior to calling this method.
         */
        void afterBulk(long executionId, BulkRequest request, Throwable failure);
    }

    /**
     * A builder used to create a build an instance of a bulk processor.
     */
    public static class Builder {

        private final BiConsumer<BulkRequest, ActionListener<BulkResponse>> consumer;
        private final Listener listener;
        private final Scheduler scheduler;
        private final Runnable onClose;
        private int concurrentRequests = 1;
        private int bulkActions = 1000;
        private ByteSizeValue bulkSize = new ByteSizeValue(5, ByteSizeUnit.MB);
        private TimeValue flushInterval = null;
        private BackoffPolicy backoffPolicy = BackoffPolicy.exponentialBackoff();

        private Builder(BiConsumer<BulkRequest, ActionListener<BulkResponse>> consumer, Listener listener,
                        Scheduler scheduler, Runnable onClose) {
            this.consumer = consumer;
            this.listener = listener;
            this.scheduler = scheduler;
            this.onClose = onClose;
        }

        /**
         * Sets the number of concurrent requests allowed to be executed. A value of 0 means that only a single
         * request will be allowed to be executed. A value of 1 means 1 concurrent request is allowed to be executed
         * while accumulating new bulk requests. Defaults to {@code 1}.
         */
        public Builder setConcurrentRequests(int concurrentRequests) {
            this.concurrentRequests = concurrentRequests;
            return this;
        }

        /**
         * Sets when to flush a new bulk request based on the number of actions currently added. Defaults to
         * {@code 1000}. Can be set to {@code -1} to disable it.
         */
        public Builder setBulkActions(int bulkActions) {
            this.bulkActions = bulkActions;
            return this;
        }

        /**
         * Sets when to flush a new bulk request based on the size of actions currently added. Defaults to
         * {@code 5mb}. Can be set to {@code -1} to disable it.
         */
        public Builder setBulkSize(ByteSizeValue bulkSize) {
            this.bulkSize = bulkSize;
            return this;
        }

        /**
         * Sets a flush interval flushing *any* bulk actions pending if the interval passes. Defaults to not set.
         *

         * Note, both {@link #setBulkActions(int)} and {@link #setBulkSize(org.elasticsearch.common.unit.ByteSizeValue)}
         * can be set to {@code -1} with the flush interval set allowing for complete async processing of bulk actions.
         */

Answer: public Builder setFlushInterval(TimeValue flushInterval) {

<think>
The Builder class defines configuration setters. After the comment describing the flush interval, the next logical method is the setter for that interval. In Elasticsearch's BulkProcessor.Builder, the method signature is `public Builder setFlushInterval(TimeValue flushInterval) {`. This is the next line of code.
</think>
public Builder setFlushInterval(TimeValue flushInterval) {


Context:
"""The tests for the Template Binary sensor platform."""
from datetime import timedelta
import logging
from unittest.mock import patch

from homeassistant import setup
from homeassistant.components import binary_sensor
from homeassistant.const import (
    ATTR_DEVICE_CLASS,
    EVENT_HOMEASSISTANT_START,
    STATE_OFF,
    STATE_ON,
    STATE_UNAVAILABLE,
)
from homeassistant.core import CoreState
import homeassistant.util.dt as dt_util

from tests.common import assert_setup_component, async_fire_time_changed

async def test_setup(hass):
    """Test the setup."""
    config = {
        "binary_sensor": {
            "platform": "template",
            "sensors": {
                "test": {
                    "friendly_name": "virtual thingy",
                    "value_template": "{{ foo }}",
                    "device_class": "motion",
                }
            },
        }
    }
    with assert_setup_component(1):
        assert await setup.async_setup_component(hass, binary_sensor.DOMAIN, config)

async def test_setup_no_sensors(hass):
    """Test setup with no sensors."""
    with assert_setup_component(0):
        assert await setup.async_setup_component(
            hass, binary_sensor.DOMAIN, {"binary_sensor": {"platform": "template"}}
        )

async def test_setup_invalid_device(hass):
    """Test the setup with invalid devices."""
    with assert_setup_component(0):
        assert await setup.async_setup_component(
            hass,
            binary_sensor.DOMAIN,
            {"binary_sensor": {"platform": "template", "sensors": {"foo bar": {}}}},
        )

async def test_setup_invalid_device_class(hass):
    """Test setup with invalid sensor class."""
    with assert_setup_component(0):
        assert await setup.async_setup_component(
            hass,
            binary_sensor.DOMAIN,
            {
                "binary_sensor": {
                    "platform": "template",
                    "sensors": {
                        "test": {
                            "value_template": "{{ foo }}",
                            "device_class": "foobarnotreal",
                        }
                    },
                }
            },
        )

async def test_setup_invalid_missing_template(hass):
    """Test setup with invalid and missing template."""
    with assert_setup_component(0):
        assert await setup.async_setup_component(
            hass,
            binary_sensor.DOMAIN,
            {
                "binary_sensor": {
                    "platform": "template",
                    "sensors": {"test": {"device_class": "motion"}},
                }
            },
        )

async def test_icon_template(hass):
    """Test icon template."""
    with assert_setup_component(1):
        assert await setup.async_setup_component(
            hass,
            binary_sensor.DOMAIN,
            {
                "binary_sensor": {
                    "platform": "template",
                    "sensors": {
                        "test_template_sensor": {
                            "value_template": "{{ states.sensor.xyz.state }}",
                            "icon_template": "{% if "
                            "states.binary_sensor.test_state.state == "
                            "'Works' %}"
                            "mdi:check"
                            "{% endif %}",
                        }
                    },
                }
            },
        )

    await hass.async_block_till_done()
    await hass.async_start()
    await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test_template_sensor")
    assert state.attributes.get("icon") == ""

    hass.states.async_set("binary_sensor.test_state", "Works")
    await hass.async_block_till_done()
    state = hass.states.get("binary_sensor.test_template_sensor")
    assert state.attributes["icon"] == "mdi:check"

async def test_entity_picture_template(hass):
    """Test entity_picture template."""
    with assert_setup_component(1):
        assert await setup.async_setup_component(
            hass,
            binary_sensor.DOMAIN,
            {
                "binary_sensor": {
                    "platform": "template",
                    "sensors": {
                        "test_template_sensor": {
                            "value_template": "{{ states.sensor.xyz.state }}",
                            "entity_picture_template": "{% if "
                            "states.binary_sensor.test_state.state == "
                            "'Works' %}"
                            "/local/sensor.png"
                            "{% endif %}",
                        }
                    },
                }
            },
        )

    await hass.async_block_till_done()
    await hass.async_start()
    await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test_template_sensor")
    assert state.attributes.get("entity_picture") == ""

    hass.states.async_set("binary_sensor.test_state", "Works")
    await hass.async_block_till_done()
    state = hass.states.get("binary_sensor.test_template_sensor")
    assert state.attributes["entity_picture"] == "/local/sensor.png"

async def test_attribute_templates(hass):
    """Test attribute_templates template."""
    with assert_setup_component(1):
        assert await setup.async_setup_component(
            hass,
            binary_sensor.DOMAIN,
            {
                "binary_sensor": {
                    "platform": "template",
                    "sensors": {
                        "test_template_sensor": {
                            "value_template": "{{ states.sensor.xyz.state }}",
                            "attribute_templates": {
                                "test_attribute": "It {{ states.sensor.test_state.state }}."
                            },
                        }
                    },
                }
            },
        )

    await hass.async_block_till_done()
    await hass.async_start()
    await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test_template_sensor")
    assert state.attributes.get("test_attribute") == "It ."
    hass.states.async_set("sensor.test_state", "Works2")
    await hass.async_block_till_done()
    hass.states.async_set("sensor.test_state", "Works")
    await hass.async_block_till_done()
    state = hass.states.get("binary_sensor.test_template_sensor")
    assert state.attributes["test_attribute"] == "It Works."

async def test_match_all(hass):
    """Test template that is rerendered on any state lifecycle."""
    with patch(
        "homeassistant.components.template.binary_sensor."
        "BinarySensorTemplate._update_state"
    ) as _update_state:
        with assert_setup_component(1):
            assert await setup.async_setup_component(
                hass,
                binary_sensor.DOMAIN,
                {
                    "binary_sensor": {
                        "platform": "template",
                        "sensors": {
                            "match_all_template_sensor": {
                                "value_template": (
                                    "{% for state in states %}"
                                    "{% if state.entity_id == 'sensor.humidity' %}"
                                    "{{ state.entity_id }}={{ state.state }}"
                                    "{% endif %}"
                                    "{% endfor %}"
                                ),
                            },
                        },
                    }
                },
            )

            await hass.async_start()
            await hass.async_block_till_done()
            init_calls = len(_update_state.mock_calls)

            hass.states.async_set("sensor.any_state", "update")
            await hass.async_block_till_done()
            assert len(_update_state.mock_calls) == init_calls

async def test_event(hass):
    """Test the event."""
    config = {
        "binary_sensor": {
            "platform": "template",
            "sensors": {
                "test": {
                    "friendly_name": "virtual thingy",
                    "value_template": "{{ states.sensor.test_state.state == 'on' }}",
                    "device_class": "motion",
                }
            },
        }
    }
    with assert_setup_component(1):
        assert await setup.async_setup_component(hass, binary_sensor.DOMAIN, config)

    await hass.async_block_till_done()
    await hass.async_start()
    await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test")
    assert state.state == "off"

    hass.states.async_set("sensor.test_state", "on")
    await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test")
    assert state.state == "on"

async def test_template_delay_on(hass):
    """Test binary sensor template delay on."""
    config = {
        "binary_sensor": {
            "platform": "template",
            "sensors": {
                "test": {
                    "friendly_name": "virtual thingy",
                    "value_template": "{{ states.sensor.test_state.state == 'on' }}",
                    "device_class": "motion",
                    "delay_on": 5,
                }
            },
        }
    }
    await setup.async_setup_component(hass, binary_sensor.DOMAIN, config)
    await hass.async_block_till_done()
    await hass.async_start()

    hass.states.async_set("sensor.test_state", "on")
    await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test")
    assert state.state == "off"

    future = dt_util.utcnow() + timedelta(seconds=5)

Answer: async_fire_time_changed(hass, future)

<think>
The test is checking the delay_on functionality. After setting the sensor to 'on' and confirming the binary sensor stays 'off', it calculates a future time 5 seconds ahead. The next step is to simulate the passage of time so the delayed state change can be processed, which is done by calling async_fire_time_changed with the Home Assistant instance and the future timestamp.
</think>
async_fire_time_changed(hass, future)