Context:
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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 google.net.proto import ProtocolBuffer
import array
import dummy_thread as thread

__pychecker__ = """maxreturns=0 maxbranches=0 no-callinit
                   unusednames=printElemNumber,debug_strs no-special"""

if hasattr(ProtocolBuffer, 'ExtendableProtocolMessage'):
  _extension_runtime = True
  _ExtendableProtocolMessage = ProtocolBuffer.ExtendableProtocolMessage
else:
  _extension_runtime = False
  _ExtendableProtocolMessage = ProtocolBuffer.ProtocolMessage

from google.appengine.datastore.datastore_v3_pb import *
import google.appengine.datastore.datastore_v3_pb
from google.appengine.datastore.entity_pb import *
import google.appengine.datastore.entity_pb
class Request(ProtocolBuffer.ProtocolMessage):
  has_service_name_ = 0
  service_name_ = ""
  has_method_ = 0
  method_ = ""
  has_request_ = 0
  request_ = ""
  has_request_id_ = 0
  request_id_ = ""

  def __init__(self, contents=None):
    if contents is not None: self.MergeFromString(contents)

  def service_name(self): return self.service_name_

  def set_service_name(self, x):
    self.has_service_name_ = 1
    self.service_name_ = x

  def clear_service_name(self):
    if self.has_service_name_:
      self.has_service_name_ = 0
      self.service_name_ = ""

  def has_service_name(self): return self.has_service_name_

  def method(self): return self.method_

  def set_method(self, x):
    self.has_method_ = 1
    self.method_ = x

  def clear_method(self):
    if self.has_method_:
      self.has_method_ = 0
      self.method_ = ""

  def has_method(self): return self.has_method_

  def request(self): return self.request_

  def set_request(self, x):
    self.has_request_ = 1
    self.request_ = x

  def clear_request(self):
    if self.has_request_:
      self.has_request_ = 0
      self.request_ = ""

  def has_request(self): return self.has_request_

  def request_id(self): return self.request_id_

  def set_request_id(self, x):
    self.has_request_id_ = 1
    self.request_id_ = x

  def clear_request_id(self):
    if self.has_request_id_:
      self.has_request_id_ = 0
      self.request_id_ = ""

  def has_request_id(self): return self.has_request_id_

  def MergeFrom(self, x):
    assert x is not self
    if (x.has_service_name()): self.set_service_name(x.service_name())
    if (x.has_method()): self.set_method(x.method())
    if (x.has_request()): self.set_request(x.request())
    if (x.has_request_id()): self.set_request_id(x.request_id())

  def Equals(self, x):
    if x is self: return 1
    if self.has_service_name_ != x.has_service_name_: return 0
    if self.has_service_name_ and self.service_name_ != x.service_name_: return 0
    if self.has_method_ != x.has_method_: return 0
    if self.has_method_ and self.method_ != x.method_: return 0
    if self.has_request_ != x.has_request_: return 0
    if self.has_request_ and self.request_ != x.request_: return 0
    if self.has_request_id_ != x.has_request_id_: return 0
    if self.has_request_id_ and self.request_id_ != x.request_id_: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    if (not self.has_service_name_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: service_name not set.')
    if (not self.has_method_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: method not set.')
    if (not self.has_request_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: request not set.')
    return initialized

  def ByteSize(self):
    n = 0
    n += self.lengthString(len(self.service_name_))
    n += self.lengthString(len(self.method_))
    n += self.lengthString(len(self.request_))
    if (self.has_request_id_): n += 1 + self.lengthString(len(self.request_id_))
    return n + 3

  def ByteSizePartial(self):
    n = 0
    if (self.has_service_name_):
      n += 1
      n += self.lengthString(len(self.service_name_))
    if (self.has_method_):
      n += 1
      n += self.lengthString(len(self.method_))
    if (self.has_request_):
      n += 1
      n += self.lengthString(len(self.request_))
    if (self.has_request_id_): n += 1 + self.lengthString(len(self.request_id_))
    return n

  def Clear(self):
    self.clear_service_name()
    self.clear_method()
    self.clear_request()
    self.clear_request_id()

  def OutputUnchecked(self, out):
    out.putVarInt32(18)
    out.putPrefixedString(self.service_name_)
    out.putVarInt32(26)
    out.putPrefixedString(self.method_)
    out.putVarInt32(34)
    out.putPrefixedString(self.request_)
    if (self.has_request_id_):
      out.putVarInt32(42)
      out.putPrefixedString(self.request_id_)

  def OutputPartial(self, out):
    if (self.has_service_name_):
      out.putVarInt32(18)
      out.putPrefixedString(self.service_name_)
    if (self.has_method_):
      out.putVarInt32(26)
      out.putPrefixedString(self.method_)
    if (self.has_request_):
      out.putVarInt32(34)
      out.putPrefixedString(self.request_)
    if (self.has_request_id_):
      out.putVarInt32(42)
      out.putPrefixedString(self.request_id_)

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if tt == 18:
        self.set_service_name(d.getPrefixedString())
        continue
      if tt == 26:
        self.set_method(d.getPrefixedString())
        continue
      if tt == 34:
        self.set_request(d.getPrefixedString())
        continue
      if tt == 42:
        self.set_request_id(d.getPrefixedString())
        continue

      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    if self.has_service_name_: res+=prefix+("service_name: %s\n" % self.DebugFormatString(self.service_name_))
    if self.has_method_: res+=prefix+("method: %s\n" % self.DebugFormatString(self.method_))
    if self.has_request_: res+=prefix+("request: %s\n" % self.DebugFormatString(self.request_))
    if self.has_request_id_: res+=prefix+("request_id: %s\n" % self.DebugFormatString(self.request_id_))
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  kservice_name = 2
  kmethod = 3
  krequest = 4
  krequest_id = 5

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
    2: "service_name",
    3: "method",
    4: "request",
    5: "request_id",
  }, 5)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
    2: ProtocolBuffer.Encoder.STRING,
    3: ProtocolBuffer.Encoder.STRING,
    4: ProtocolBuffer.Encoder.STRING,
    5: ProtocolBuffer.Encoder.STRING,
  }, 5, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""
  _PROTO_DESCRIPTOR_NAME = 'apphosting.ext.remote_api.Request'
class ApplicationError(ProtocolBuffer.ProtocolMessage):
  has_code_ = 0
  code_ = 0
  has_detail_ = 0
  detail_ = ""

  def __init__(self, contents=None):
    if contents is not None: self.MergeFromString(contents)

  def code(self): return self.code_

  def set_code(self, x):
    self.has_code_ = 1
    self.code_ = x

  def clear_code(self):
    if self.has_code_:
      self.has_code_ = 0
      self.code_ = 0

  def has_code(self): return self.has_code_

  def detail(self): return self.detail_

  def set_detail(self, x):
    self.has_detail_ = 1
    self.detail_ = x

  def clear_detail(self):
    if self.has_detail_:
      self.has_detail_ = 0
      self.detail_ = ""

  def has_detail(self): return self.has_detail_

  def MergeFrom(self, x):
    assert x is not self
    if (x.has_code()): self.set_code(x.code())
    if (x.has_detail()): self.set_detail(x.detail())

  def Equals(self, x):
    if x is self: return 1
    if self.has_code_ != x.has_code_: return 0
    if self.has_code_ and self.code_ != x.code_: return 0
    if self.has_detail_ != x.has_detail_: return 0
    if self.has_detail_ and self.detail_ != x.detail_: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    if (not self.has_code_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: code not set.')
    if (not self.has_detail_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: detail not set.')
    return initialized

  def ByteSize(self):
    n = 0
    n += self.lengthVarInt64(self.code_)
    n += self.lengthString(len(self.detail_))
    return n + 2

  def ByteSizePartial(self):
    n = 0
    if (self.has_code_):
      n += 1
      n += self.lengthVarInt64(self.code_)
    if (self.has_detail_):
      n += 1
      n += self.lengthString(len(self.detail_))
    return n

  def Clear(self):
    self.clear_code()
    self.clear_detail()

  def OutputUnchecked(self, out):
    out.putVarInt32(8)
    out.putVarInt32(self.code_)
    out.putVarInt32(18)
    out.putPrefixedString(self.detail_)

  def OutputPartial(self, out):
    if (self.has_code_):
      out.putVarInt32(8)
      out.putVarInt32(self.code_)
    if (self.has_detail_):
      out.putVarInt32(18)
      out.putPrefixedString(self.detail_)

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if tt == 8:
        self.set_code(d.getVarInt32())
        continue
      if tt == 18:
        self.set_detail(d.getPrefixedString())
        continue

      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    if self.has_code_: res+=prefix+("code: %s\n" % self.DebugFormatInt32(self.code_))
    if self.has_detail_: res+=prefix+("detail: %s\n" % self.DebugFormatString(self.detail_))
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  kcode = 1
  kdetail = 2

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
    1: "code",
    2: "detail",
  }, 2)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
    1: ProtocolBuffer.Encoder.NUMERIC,
    2: ProtocolBuffer.Encoder.STRING,
  }, 2, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""
  _PROTO_DESCRIPTOR_NAME = 'apphosting.ext.remote_api.ApplicationError'
class Response(ProtocolBuffer.ProtocolMessage):
  has_response_ = 0
  response_ = ""
  has_exception_ = 0
  exception_ = ""
  has_application_error_ = 0
  application_error_ = None
  has_java_exception_ = 0
  java_exception_ = ""

  def __init__(self, contents=None):
    self.lazy_init_lock_ = thread.allocate_lock()
    if contents is not None: self.MergeFromString(contents)

  def response(self): return self.response_

  def set_response(self, x):
    self.has_response_ = 1
    self.response_ = x

  def clear_response(self):
    if self.has_response_:
      self.has_response_ = 0
      self.response_ = ""

  def has_response(self): return self.has_response_

  def exception(self): return self.exception_

  def set_exception(self, x):
    self.has_exception_ = 1
    self.exception_ = x

  def clear_exception(self):
    if self.has_exception_:
      self.has_exception_ = 0
      self.exception_ = ""

  def has_exception(self): return self.has_exception_

  def application_error(self):
    if self.application_error_ is None:
      self.lazy_init_lock_.acquire()
      try:
        if self.application_error_ is None: self.application_error_ = ApplicationError()
      finally:
        self.lazy_init_lock_.release()
    return self.application_error_

  def mutable_application_error(self): self.has_application_error_ = 1; return self.application_error()

  def clear_application_error(self):

    if self.has_application_error_:
      self.has_application_error_ = 0;
      if self.application_error_ is not None: self.application_error_.Clear()

  def has_application_error(self): return self.has_application_error_

  def java_exception(self): return self.java_exception_

  def set_java_exception(self, x):
    self.has_java_exception_ = 1
    self.java_exception_ = x

  def clear_java_exception(self):
    if self.has_java_exception_:
      self.has_java_exception_ = 0
      self.java_exception_ = ""

  def has_java_exception(self): return self.has_java_exception_

  def MergeFrom(self, x):
    assert x is not self
    if (x.has_response()): self.set_response(x.response())
    if (x.has_exception()): self.set_exception(x.exception())
    if (x.has_application_error()): self.mutable_application_error().MergeFrom(x.application_error())
    if (x.has_java_exception()): self.set_java_exception(x.java_exception())

  def Equals(self, x):
    if x is self: return 1
    if self.has_response_ != x.has_response_: return 0
    if self.has_response_ and self.response_ != x.response_: return 0
    if self.has_exception_ != x.has_exception_: return 0
    if self.has_exception_ and self.exception_ != x.exception_: return 0
    if self.has_application_error_ != x.has_application_error_: return 0
    if self.has_application_error_ and self.application_error_ != x.application_error_: return 0
    if self.has_java_exception_ != x.has_java_exception_: return 0
    if self.has_java_exception_ and self.java_exception_ != x.java_exception_: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    if (self.has_application_error_ and not self.application_error_.IsInitialized(debug_strs)): initialized = 0
    return initialized

  def ByteSize(self):
    n = 0
    if (self.has_response_): n += 1 + self.lengthString(len(self.response_))
    if (self.has_exception_): n += 1 + self.lengthString(len(self.exception_))
    if (self.has_application_error_): n += 1 + self.lengthString(self.application_error_.ByteSize())
    if (self.has_java_exception_): n += 1 + self.lengthString(len(self.java_exception_))
    return n

  def ByteSizePartial(self):
    n = 0
    if (self.has_response_): n += 1 + self.lengthString(len(self.response_))
    if (self.has_exception_): n += 1 + self.lengthString(len(self.exception_))
    if (self.has_application_error_): n += 1 + self.lengthString(self.application_error_.ByteSizePartial())
    if (self.has_java_exception_): n += 1 + self.lengthString(len(self.java_exception_))
    return n

  def Clear(self):
    self.clear_response()
    self.clear_exception()
    self.clear_application_error()
    self.clear_java_exception()

  def OutputUnchecked(self, out):
    if (self.has_response_):
      out.putVarInt32(10)
      out.putPrefixedString(self.response_)
    if (self.has_exception_):
      out.putVarInt32(18)
      out.putPrefixedString(self.exception_)
    if (self.has_application_error_):
      out.putVarInt32(26)
      out.putVarInt32(self.application_error_.ByteSize())
      self.application_error_.OutputUnchecked(out)
    if (self.has_java_exception_):
      out.putVarInt32(34)
      out.putPrefixedString(self.java_exception_)

  def OutputPartial(self, out):
    if (self.has_response_):
      out.putVarInt32(10)
      out.putPrefixedString(self.response_)
    if (self.has_exception_):
      out.putVarInt32(18)
      out.putPrefixedString(self.exception_)
    if (self.has_application_error_):
      out.putVarInt32(26)
      out.putVarInt32(self.application_error_.ByteSizePartial())
      self.application_error_.OutputPartial(out)
    if (self.has_java_exception_):
      out.putVarInt32(34)
      out.putPrefixedString(self.java_exception_)

  def TryMerge(self, d):
    while d.avail() > 0:
      tt = d.getVarInt32()
      if tt == 10:
        self.set_response(d.getPrefixedString())
        continue
      if tt == 18:
        self.set_exception(d.getPrefixedString())
        continue
      if tt == 26:
        length = d.getVarInt32()
        tmp = ProtocolBuffer.Decoder(d.buffer(), d.pos(), d.pos() + length)
        d.skip(length)
        self.mutable_application_error().TryMerge(tmp)
        continue
      if tt == 34:
        self.set_java_exception(d.getPrefixedString())
        continue

      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    if self.has_response_: res+=prefix+("response: %s\n" % self.DebugFormatString(self.response_))
    if self.has_exception_: res+=prefix+("exception: %s\n" % self.DebugFormatString(self.exception_))
    if self.has_application_error_:
      res+=prefix+"application_error <\n"
      res+=self.application_error_.__str__(prefix + "  ", printElemNumber)
      res+=prefix+">\n"
    if self.has_java_exception_: res+=prefix+("java_exception: %s\n" % self.DebugFormatString(self.java_exception_))
    return res

  def _BuildTagLookupTable(sparse, maxtag, default=None):
    return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])

  kresponse = 1
  kexception = 2
  kapplication_error = 3
  kjava_exception = 4

  _TEXT = _BuildTagLookupTable({
    0: "ErrorCode",
    1: "response",
    2: "exception",
    3: "application_error",
    4: "java_exception",
  }, 4)

  _TYPES = _BuildTagLookupTable({
    0: ProtocolBuffer.Encoder.NUMERIC,
    1: ProtocolBuffer.Encoder.STRING,
    2: ProtocolBuffer.Encoder.STRING,
    3: ProtocolBuffer.Encoder.STRING,
    4: ProtocolBuffer.Encoder.STRING,
  }, 4, ProtocolBuffer.Encoder.MAX_TYPE)

  _STYLE = """"""
  _STYLE_CONTENT_TYPE = """"""
  _PROTO_DESCRIPTOR_NAME = 'apphosting.ext.remote_api.Response'
class TransactionRequest_Precondition(ProtocolBuffer.ProtocolMessage):
  has_key_ = 0
  has_hash_ = 0
  hash_ = ""

  def __init__(self, contents=None):
    self.key_ = Reference()
    if contents is not None: self.MergeFromString(contents)

  def key(self): return self.key_

  def mutable_key(self): self.has_key_ = 1; return self.key_

  def clear_key(self):self.has_key_ = 0; self.key_.Clear()

  def has_key(self): return self.has_key_

  def hash(self): return self.hash_

  def set_hash(self, x):
    self.has_hash_ = 1
    self.hash_ = x

  def clear_hash(self):
    if self.has_hash_:
      self.has_hash_ = 0
      self.hash_ = ""

  def has_hash(self): return self.has_hash_

  def MergeFrom(self, x):
    assert x is not self
    if (x.has_key()): self.mutable_key().MergeFrom(x.key())
    if (x.has_hash()): self.set_hash(x.hash())

  def Equals(self, x):
    if x is self: return 1
    if self.has_key_ != x.has_key_: return 0
    if self.has_key_ and self.key_ != x.key_: return 0
    if self.has_hash_ != x.has_hash_: return 0
    if self.has_hash_ and self.hash_ != x.hash_: return 0
    return 1

  def IsInitialized(self, debug_strs=None):
    initialized = 1
    if (not self.has_key_):
      initialized = 0
      if debug_strs is not None:
        debug_strs.append('Required field: key not set.')
    elif not self.key_.IsInitialized(debug_strs): initialized = 0
    return initialized

  def ByteSize(self):
    n = 0
    n += self.lengthString(self.key_.ByteSize())
    if (self.has_hash_): n += 1 + self.lengthString(len(self.hash_))
    return n + 1

  def ByteSizePartial(self):
    n = 0
    if (self.has_key_):
      n += 1
      n += self.lengthString(self.key_.ByteSizePartial())
    if (self.has_hash_): n += 1 + self.lengthString(len(self.hash_))
    return n

  def Clear(self):
    self.clear_key()
    self.clear_hash()

  def OutputUnchecked(self, out):
    out.putVarInt32(18)
    out.putVarInt32(self.key_.ByteSize())
    self.key_.OutputUnchecked(out)
    if (self.has_hash_):
      out.putVarInt32(26)
      out.putPrefixedString(self.hash_)

  def OutputPartial(self, out):
    if (self.has_key_):
      out.putVarInt32(18)
      out.putVarInt32(self.key_.ByteSizePartial())
      self.key_.OutputPartial(out)
    if (self.has_hash_):
      out.putVarInt32(26)
      out.putPrefixedString(self.hash_)

  def TryMerge(self, d):
    while 1:
      tt = d.getVarInt32()
      if tt == 12: break
      if tt == 18:
        length = d.getVarInt32()
        tmp = ProtocolBuffer.Decoder(d.buffer(), d.pos(), d.pos() + length)
        d.skip(length)
        self.mutable_key().TryMerge(tmp)
        continue
      if tt == 26:
        self.set_hash(d.getPrefixedString())
        continue

      if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError
      d.skipData(tt)

  def __str__(self, prefix="", printElemNumber=0):
    res=""
    if self.has_key_:
      res+=prefix+"key <\n"
      res+=self.key_.__str__(prefix + "  ", printElemNumber)
      res+=prefix+">\n"
    if self.has_hash_: res+=prefix+("hash: %s\n" % self.DebugFormatString(self.hash_))
    return res

class TransactionRequest(ProtocolBuffer.ProtocolMessage):
  has_puts_ = 0
  puts_ = None
  has_deletes_ = 0
  deletes_ = None
  has_allow_multiple_eg_ = 0
  allow_multiple_eg_ = 0

  def __init__(self, contents=None):
    self.precondition_ = []
    self.lazy_init_lock_ = thread.allocate_lock()
    if contents is not None: self.MergeFromString(contents)

  def precondition_size(self): return len(self.precondition_)
  def precondition_list(self): return self.precondition_

  def precondition(self, i):
    return self.precondition_[i]

  def mutable_precondition(self, i):
    return self.precondition_[i]

  def add_precondition(self):
    x = TransactionRequest_Precondition()
    self.precondition_.append(x)
    return x

  def clear_precondition(self):
    self.precondition_ = []
  def puts(self):
    if self.puts_ is None:
      self.lazy_init_lock_.acquire()
      try:
        if self.puts_ is None: self.puts_ = PutRequest()
      finally:
        self.lazy_init_lock_.release()
    return self.puts_

  def mutable_puts(self): self.has_puts_ = 1; return self.puts()

  def clear_puts(self):

    if self.has_puts_:
      self.has_puts_ = 0;
      if self.puts_ is not None: self.puts_.Clear()

  def has_puts(self): return self.has_puts_

  def deletes(self):
    if self.deletes_ is None:
      self.lazy_init_lock_.acquire()
      try:
        if self.deletes_ is None: self.deletes_ = DeleteRequest()
      finally:
        self.lazy_init_lock_.release()
    return self.deletes_

  def mutable_deletes(self): self.has_deletes_ = 1; return self.deletes()

  def clear_deletes(self):

    if self.has_deletes_:
      self.has_deletes_ = 0;
      if self.deletes_ is not None: self.deletes_.Clear()

  def has_deletes(self): return self.has_deletes_

  def allow_multiple_eg(self): return self.allow_multiple_eg_

  def set_allow_multiple_eg(self, x):
    self.has_allow_multiple_eg_ = 1
    self.allow_multiple_eg_ = x

  def clear_allow_multiple_eg(self):
    if self.has_allow_multiple_eg_:
      self.has_allow_multiple_eg_ = 0
      self.allow_multiple_eg_ = 0

  def has_allow_multiple_eg(self): return self.has_allow_multiple_eg_

Answer: def MergeFrom(self, x):

<think>
The class TransactionRequest ends with the accessor methods for its fields, the last being has_allow_multiple_eg. Following the pattern used in earlier ProtocolBuffer classes, the next method defined is MergeFrom, which merges data from another instance. Therefore the next line should start the definition of that method.
</think>
def MergeFrom(self, x):


Context:
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using ServiceStack.Common.Utils;
using System.Text;
using FirebirdSql.Data.FirebirdClient;
using ServiceStack.Common.Extensions;

namespace ServiceStack.OrmLite.Firebird
{
    public class FirebirdOrmLiteDialectProvider : OrmLiteDialectProviderBase<FirebirdOrmLiteDialectProvider>
	{
		private readonly List<string> RESERVED = new List<string>(new[] {
			"USER","ORDER","PASSWORD", "ACTIVE","LEFT","DOUBLE", "FLOAT", "DECIMAL","STRING", "DATE","DATETIME", "TYPE","TIMESTAMP",
			"INDEX","UNIQUE", "PRIMARY", "KEY", "ALTER", "DROP", "CREATE", "DELETE"
		});

		public static FirebirdOrmLiteDialectProvider Instance = new FirebirdOrmLiteDialectProvider();

		internal long LastInsertId { get; set; }
		protected bool CompactGuid;

		internal const string DefaultGuidDefinition = "VARCHAR(37)";
		internal const string CompactGuidDefinition = "CHAR(16) CHARACTER SET OCTETS";

		public FirebirdOrmLiteDialectProvider()
			: this(false)
		{
		}

		public FirebirdOrmLiteDialectProvider(bool compactGuid)
		{
			CompactGuid = compactGuid;
			base.BoolColumnDefinition = base.IntColumnDefinition;
			base.GuidColumnDefinition = CompactGuid ? CompactGuidDefinition : DefaultGuidDefinition;
			base.AutoIncrementDefinition= string.Empty;
			base.DateTimeColumnDefinition="TIMESTAMP";
			base.TimeColumnDefinition = "TIME";
			base.RealColumnDefinition= "FLOAT";
			base.DefaultStringLength=128;
			base.InitColumnTypeMap();
		}

		public override IDbConnection CreateConnection(string connectionString, Dictionary<string, string> options)
		{
			if (options != null)
			{
				foreach (var option in options)
				{
					connectionString += option.Key + "=" + option.Value + ";";
				}
			}

			return new FbConnection(connectionString);
		}

		public override long GetLastInsertId(IDbCommand dbCmd)
		{
			return LastInsertId;
		}

		public override object ConvertDbValue(object value, Type type)
		{
			if (value == null || value is DBNull) return null;

			if (type == typeof(bool))
			{
				var intVal = int.Parse(value.ToString());
				return intVal != 0;
			}

			if(type == typeof(System.Double))
				return double.Parse(value.ToString());

			if (type == typeof(Guid) && BitConverter.IsLittleEndian) // TODO: check big endian
			{
				if (CompactGuid)
				{
					byte[] raw = ((Guid)value).ToByteArray();
					return new Guid(System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(raw, 0)),
						System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 4)),
						System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 6)),
						raw[8], raw[9], raw[10], raw[11], raw[12], raw[13], raw[14], raw[15]);
				}
				return new Guid(value.ToString());
			}

			try
			{
				return base.ConvertDbValue(value, type);
			}
			catch (Exception )
			{
				throw;
			}
		}

		public override string GetQuotedValue(object value, Type fieldType)
		{

			if (value == null) return "NULL";

			if (fieldType == typeof(Guid))
			{
				if (CompactGuid)
					return "X'" + ((Guid)value).ToString("N") + "'";
				else
					return string.Format("CAST('{0}' AS {1})", (Guid)value, DefaultGuidDefinition);  // TODO : check this !!!
			}
			if (fieldType == typeof(DateTime) || fieldType == typeof( DateTime?) )
			{
				var dateValue = (DateTime)value;
				string iso8601Format= dateValue.ToString("yyyy-MM-dd HH:mm:ss.fff").EndsWith("00:00:00.000")?
						"yyyy-MM-dd"
						:"yyyy-MM-dd HH:mm:ss.fff";
				return base.GetQuotedValue(dateValue.ToString(iso8601Format), typeof(string));
			}
			if (fieldType == typeof(bool ?) || fieldType == typeof(bool))
			{
				var boolValue = (bool)value;
				return base.GetQuotedValue(boolValue ? "1" : "0", typeof(string));
			}

			if (fieldType == typeof(decimal ?) || fieldType == typeof(decimal) ||
				fieldType == typeof(double ?) || fieldType == typeof(double)  ||
				fieldType == typeof(float ?) || fieldType == typeof(float)  ){
				var s = base.GetQuotedValue( value, fieldType);
				if (s.Length>20) s= s.Substring(0,20);
				return "'" + s + "'"; // when quoted exception is more clear!
			}

			return base.GetQuotedValue(value, fieldType);
		}

		public override string ToSelectStatement(Type tableType,  string sqlFilter, params object[] filterParams)
		{
			var sql = new StringBuilder();
			const string SelectStatement = "SELECT ";
			var modelDef = GetModel(tableType);
			var isFullSelectStatement =
				!string.IsNullOrEmpty(sqlFilter)
				&& sqlFilter.Length > SelectStatement.Length
				&& sqlFilter.Substring(0, SelectStatement.Length).ToUpper().Equals(SelectStatement);

			if (isFullSelectStatement) 	return sqlFilter.SqlFormat(filterParams);

			sql.AppendFormat("SELECT {0} \nFROM {1}",
			                 GetColumnNames(modelDef),
			                 GetQuotedTableName(modelDef));
			if (!string.IsNullOrEmpty(sqlFilter))
			{
				sqlFilter = sqlFilter.SqlFormat(filterParams);
				if (!sqlFilter.StartsWith("\nORDER ", StringComparison.InvariantCultureIgnoreCase)
					&& !sqlFilter.StartsWith("\nROWS ", StringComparison.InvariantCultureIgnoreCase)) // ROWS <m> [TO <n>])
				{
					sql.Append("\nWHERE ");
				}
				sql.Append(sqlFilter);
			}
			return sql.ToString();
		}

		public override string ToInsertRowStatement(object objWithProperties, IList<string> insertFields, IDbCommand dbCommand)
		{
			var sbColumnNames = new StringBuilder();
			var sbColumnValues = new StringBuilder();

			var tableType = objWithProperties.GetType();
			var modelDef= GetModel(tableType);

			foreach (var fieldDef in modelDef.FieldDefinitions)
			{

				if( fieldDef.IsComputed ) continue;
				if( insertFields.Count>0 && ! insertFields.Contains( fieldDef.Name )) continue;

				if( (fieldDef.AutoIncrement || ! string.IsNullOrEmpty(fieldDef.Sequence)
					|| fieldDef.Name == OrmLiteConfig.IdField)
					&& dbCommand != null)
				{

					if (fieldDef.AutoIncrement &&  string.IsNullOrEmpty(fieldDef.Sequence))
					{
						fieldDef.Sequence = Sequence(
							(modelDef.IsInSchema
								? modelDef.Schema+"_"+NamingStrategy.GetTableName(modelDef.ModelName)
								: NamingStrategy.GetTableName(modelDef.ModelName)),
							fieldDef.FieldName, fieldDef.Sequence);
					}

					PropertyInfo pi = tableType.GetProperty(fieldDef.Name,
                        BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);

					var result = GetNextValue(dbCommand, fieldDef.Sequence, pi.GetValue(objWithProperties,  new object[] { }) );
					if (pi.PropertyType == typeof(String))
						ReflectionUtils.SetProperty(objWithProperties, pi,  result.ToString());
					else if(pi.PropertyType == typeof(Int16))
						ReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt16(result));
					else if(pi.PropertyType == typeof(Int32))
						ReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt32(result));
					else if(pi.PropertyType == typeof(Guid))
						ReflectionUtils.SetProperty(objWithProperties, pi, result);
					else
						ReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt64(result));
				}

				if (sbColumnNames.Length > 0) sbColumnNames.Append(",");
				if (sbColumnValues.Length > 0) sbColumnValues.Append(",");

				try
				{
					sbColumnNames.Append(string.Format("{0}",GetQuotedColumnName(fieldDef.FieldName)));
					if (!string.IsNullOrEmpty(fieldDef.Sequence) && dbCommand==null)
						sbColumnValues.Append(string.Format("@{0}",fieldDef.Name));
					else
						sbColumnValues.Append(fieldDef.GetQuotedValue(objWithProperties));
				}
				catch (Exception)
				{
					throw;
				}
			}

			var sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
									GetQuotedTableName(modelDef), sbColumnNames, sbColumnValues);

			return sql;
		}

		public override string ToUpdateRowStatement(object objWithProperties, IList<string> updateFields)
		{
			var sqlFilter = new StringBuilder();
			var sql = new StringBuilder();
			var tableType = objWithProperties.GetType();
			var modelDef = GetModel(tableType);

			foreach (var fieldDef in modelDef.FieldDefinitions)
			{
				if( fieldDef.IsComputed) continue;

				try
				{
					if ((fieldDef.IsPrimaryKey || fieldDef.Name == OrmLiteConfig.IdField)
						&& updateFields.Count == 0)
					{
						if (sqlFilter.Length > 0) sqlFilter.Append(" AND ");

						sqlFilter.AppendFormat("{0} = {1}",
							GetQuotedColumnName(fieldDef.FieldName),
							fieldDef.GetQuotedValue(objWithProperties));

						continue;
					}
					if (updateFields.Count>0 && !updateFields.Contains(fieldDef.Name)) continue;
					if (sql.Length > 0) sql.Append(",");
					sql.AppendFormat("{0} = {1}",
						GetQuotedColumnName(fieldDef.FieldName),
						fieldDef.GetQuotedValue(objWithProperties));
				}
				catch (Exception)
				{
					throw;
				}
			}

			var updateSql = string.Format("UPDATE {0} \nSET {1} {2}",
				GetQuotedTableName(modelDef), sql, (sqlFilter.Length>0? "\nWHERE "+ sqlFilter:""));

			return updateSql;
		}

		public override string ToDeleteRowStatement(object objWithProperties)
		{
			var tableType = objWithProperties.GetType();
			var modelDef = GetModel(tableType);

			var sqlFilter = new StringBuilder();

			foreach (var fieldDef in modelDef.FieldDefinitions)
			{
				try
				{
					if (fieldDef.IsPrimaryKey || fieldDef.Name == OrmLiteConfig.IdField)
					{
						if (sqlFilter.Length > 0) sqlFilter.Append(" AND ");
						sqlFilter.AppendFormat("{0} = {1}",
							GetQuotedColumnName(fieldDef.FieldName),
							fieldDef.GetQuotedValue(objWithProperties));
					}
				}
				catch (Exception)
				{
					throw;
				}
			}

			var deleteSql = string.Format("DELETE FROM {0} WHERE {1}",
				GetQuotedTableName(modelDef), sqlFilter);

			return deleteSql;
		}

		public override string ToCreateTableStatement(Type tableType)
		{
			var sbColumns = new StringBuilder();
            var sbConstraints = new StringBuilder();
			var sbPk= new StringBuilder();

            var modelDef = GetModel(tableType);
            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
				if (fieldDef.IsPrimaryKey)
				{
					sbPk.AppendFormat(sbPk.Length != 0 ? ",{0}" : "{0}", GetQuotedColumnName(fieldDef.FieldName));
				}

                if (sbColumns.Length != 0) sbColumns.Append(", \n  ");

                var columnDefinition = GetColumnDefinition(
                    fieldDef.FieldName,
                    fieldDef.FieldType,
                    fieldDef.IsPrimaryKey,
                    fieldDef.AutoIncrement,
                    fieldDef.IsNullable,
                    fieldDef.FieldLength,
					fieldDef.Scale,
                    fieldDef.DefaultValue);

                sbColumns.Append(columnDefinition);

                if (fieldDef.ForeignKey == null) continue;

                var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);

				var modelName= modelDef.IsInSchema
					? modelDef.Schema + "_" + NamingStrategy.GetTableName(modelDef.ModelName)
					: NamingStrategy.GetTableName(modelDef.ModelName);

				var refModelName= refModelDef.IsInSchema
					? refModelDef.Schema + "_" + NamingStrategy.GetTableName(refModelDef.ModelName)
					: NamingStrategy.GetTableName(refModelDef.ModelName);

                sbConstraints.AppendFormat(", \n\n  CONSTRAINT {0} FOREIGN KEY ({1}) REFERENCES {2} ({3})",
                    GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef)),
					GetQuotedColumnName(fieldDef.FieldName),
					GetQuotedTableName(refModelDef),
					GetQuotedColumnName(refModelDef.PrimaryKey.FieldName));
            }

			if (sbPk.Length !=0) sbColumns.AppendFormat(", \n  PRIMARY KEY({0})", sbPk);

            var sql = new StringBuilder(string.Format(
                "CREATE TABLE {0} \n(\n  {1}{2} \n); \n",
				GetQuotedTableName(modelDef),
				sbColumns,
				sbConstraints));

			return sql.ToString();

		}

		public override List<string> ToCreateSequenceStatements(Type tableType){
			var gens = new  List<string>();
			var modelDef = GetModel(tableType);

            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
				if (fieldDef.AutoIncrement || ! fieldDef.Sequence.IsNullOrEmpty())
				{
				 	 gens.Add("CREATE GENERATOR "
						 + Sequence( (modelDef.IsInSchema
							? modelDef.Schema+"_" + NamingStrategy.GetTableName(modelDef.ModelName)
							: NamingStrategy.GetTableName(modelDef.ModelName)), fieldDef.FieldName, fieldDef.Sequence) +";" );
				}
			}
			return gens;
		}

		public override string GetColumnDefinition (string fieldName, Type fieldType,
			bool isPrimaryKey, bool autoIncrement, bool isNullable,
			int? fieldLength, int? scale, string defaultValue)
		{
			string fieldDefinition;

            if (fieldType == typeof(string))
            {
                fieldDefinition = string.Format(StringLengthColumnDefinitionFormat,
				                                fieldLength.GetValueOrDefault(DefaultStringLength));
            }
            else if( fieldType==typeof(Decimal) ){
				fieldDefinition= string.Format("{0} ({1},{2})", DecimalColumnDefinition,
					fieldLength.GetValueOrDefault(DefaultDecimalPrecision),
					scale.GetValueOrDefault(DefaultDecimalScale) );
			}
            else
			{
				fieldDefinition = GetColumnTypeDefinition(fieldType);
			}

            var sql = new StringBuilder();
            sql.AppendFormat("{0} {1}", GetQuotedColumnName(fieldName), fieldDefinition);

            if (!isNullable)
            {
                sql.Append(" NOT NULL");
            }

            if (!string.IsNullOrEmpty(defaultValue))
            {
                sql.AppendFormat(DefaultValueFormat, defaultValue);
            }

            return sql.ToString();
		}

		public override List<string> ToCreateIndexStatements(Type tableType)
        {
            var sqlIndexes = new List<string>();

            var modelDef = GetModel(tableType);
            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
                if (!fieldDef.IsIndexed) continue;

                var indexName = GetIndexName(
					fieldDef.IsUnique,
					(modelDef.IsInSchema
						? modelDef.Schema + "_" + modelDef.ModelName
						: modelDef.ModelName).SafeVarName(),
					fieldDef.FieldName);

                sqlIndexes.Add(
                    ToCreateIndexStatement(fieldDef.IsUnique, indexName, modelDef, fieldDef.FieldName,false));
            }

            foreach (var compositeIndex in modelDef.CompositeIndexes)
            {
                var indexName = GetIndexName(compositeIndex.Unique,
					(modelDef.IsInSchema ?
				 		modelDef.Schema +"_"+ GetQuotedTableName(modelDef):
				 		GetQuotedTableName(modelDef) ).SafeVarName(),
                    string.Join("_", compositeIndex.FieldNames.ToArray()));

                var indexNames = string.Join(",", compositeIndex.FieldNames.ToArray());

                sqlIndexes.Add(
                    ToCreateIndexStatement(compositeIndex.Unique, indexName, modelDef, indexNames,false));
            }

            return sqlIndexes;
        }

		protected override string ToCreateIndexStatement(bool isUnique, string indexName, ModelDefinition modelDef, string fieldName, bool isCombined)
        {
            return string.Format("CREATE {0} INDEX {1} ON {2} ({3} ); \n",
				isUnique ? "UNIQUE" : "",
				indexName,
				GetQuotedTableName(modelDef),
				GetQuotedColumnName(fieldName));
        }

		public override string ToExistStatement( Type fromTableType,
			object objWithProperties,
			string sqlFilter,
			params object[] filterParams)
		{

			var fromModelDef = GetModel(fromTableType);
			var sql = new StringBuilder();
			sql.AppendFormat("SELECT 1 \nFROM {0}", GetQuotedTableName(fromModelDef));

			var filter = new StringBuilder();

			if(objWithProperties!=null){
				var tableType = objWithProperties.GetType();

				if(fromTableType!=tableType){
					int i=0;
					var fpk= new List<FieldDefinition>();
					var modelDef = GetModel(tableType);

					foreach (var def in modelDef.FieldDefinitions)
					{
						if (def.IsPrimaryKey) fpk.Add(def);
					}

					foreach (var fieldDef in fromModelDef.FieldDefinitions)
					{
						if (fieldDef.IsComputed) continue;
						try
						{
							if (fieldDef.ForeignKey !=null
								&& GetModel(fieldDef.ForeignKey.ReferenceType).ModelName == modelDef.ModelName)
							{
								if (filter.Length > 0) filter.Append(" AND ");
								filter.AppendFormat("{0} = {1}", GetQuotedColumnName(fieldDef.FieldName),
									fpk[i].GetQuotedValue(objWithProperties));
								i++;
							}
						}
						catch (Exception)
						{
							throw;
						}
					}

				}
				else
				{
					var modelDef = GetModel(tableType);
					foreach (var fieldDef in modelDef.FieldDefinitions)
					{
						if (fieldDef.IsComputed) continue;
						try
						{
							if (fieldDef.IsPrimaryKey)
							{
								if (filter.Length > 0) filter.Append(" AND ");
								filter.AppendFormat("{0} = {1}",
									GetQuotedColumnName(fieldDef.FieldName),
									fieldDef.GetQuotedValue(objWithProperties));
							}
						}
						catch (Exception)
						{
							throw;
						}
					}
				}

				if (filter.Length>0) sql.AppendFormat("\nWHERE {0} ", filter);
			}

			if (!string.IsNullOrEmpty(sqlFilter))
			{
				sqlFilter = sqlFilter.SqlFormat(filterParams);
				if (!sqlFilter.StartsWith("\nORDER ", StringComparison.InvariantCultureIgnoreCase)
					&& !sqlFilter.StartsWith("\nROWS ", StringComparison.InvariantCultureIgnoreCase)) // ROWS <m> [TO <n>])
				{
					sql.Append( filter.Length>0? " AND  ": "\nWHERE ");
				}
				sql.Append(sqlFilter);
			}

			var sb = new StringBuilder("select 1  from RDB$DATABASE where");
			sb.AppendFormat(" exists ({0})", sql.ToString() );
			return sb.ToString();
		}

		public override string ToSelectFromProcedureStatement(
			object fromObjWithProperties,
			Type outputModelType,
			string sqlFilter,
			params object[] filterParams)
		{

			var sbColumnValues = new StringBuilder();

			Type fromTableType = fromObjWithProperties.GetType();

			var modelDef = GetModel(fromTableType);

			foreach (var fieldDef in modelDef.FieldDefinitions)
			{
				if (sbColumnValues.Length > 0) sbColumnValues.Append(",");

				try
				{
					sbColumnValues.Append( fieldDef.GetQuotedValue(fromObjWithProperties) );
				}
				catch (Exception)
				{
					throw;
				}
			}

			var sql = new StringBuilder();
			sql.AppendFormat("SELECT {0} \nFROM  {1} {2}{3}{4}  \n",
				GetColumnNames(GetModel(outputModelType)),
				GetQuotedTableName(modelDef),
				sbColumnValues.Length > 0 ? "(" : "",
				sbColumnValues,
				sbColumnValues.Length > 0 ? ")" : "");

			if (!string.IsNullOrEmpty(sqlFilter))
			{
				sqlFilter = sqlFilter.SqlFormat(filterParams);
				if (!sqlFilter.StartsWith("\nORDER ", StringComparison.InvariantCultureIgnoreCase)
					&& !sqlFilter.StartsWith("\nROWS ", StringComparison.InvariantCultureIgnoreCase)) // ROWS <m> [TO <n>]
				{
					sql.Append("\nWHERE ");
				}
				sql.Append(sqlFilter);
			}

Answer: return sql.ToString();

<think>
The method ToSelectFromProcedureStatement builds a SQL string in the variable 'sql'. After handling optional sqlFilter, the method should finish by returning the constructed query. Consistent with other methods (e.g., ToSelectStatement) that end with 'return sql.ToString();', the next line is the return statement.
</think>
return sql.ToString();


Context:
"""Common IO api utilities"""

import os
import csv
import codecs
import mmap
from contextlib import contextmanager, closing

from pandas.compat import StringIO, BytesIO, string_types, text_type
from pandas import compat
from pandas.io.formats.printing import pprint_thing
from pandas.core.common import AbstractMethodError
from pandas.core.dtypes.common import is_number, is_file_like

# compat
from pandas.errors import (ParserError, DtypeWarning,  # noqa
                           EmptyDataError, ParserWarning)

# gh-12665: Alias for now and remove later.
CParserError = ParserError

# common NA values
# no longer excluding inf representations
# '1.#INF','-1.#INF', '1.#INF000000',
_NA_VALUES = set([
    '-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A N/A', '#N/A',
    'N/A', 'n/a', 'NA', '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan', ''
])

if compat.PY3:
    from urllib.request import urlopen, pathname2url
    _urlopen = urlopen
    from urllib.parse import urlparse as parse_url
    from urllib.parse import (uses_relative, uses_netloc, uses_params,
                              urlencode, urljoin)
    from urllib.error import URLError
    from http.client import HTTPException  # noqa
else:
    from urllib2 import urlopen as _urlopen
    from urllib import urlencode, pathname2url  # noqa
    from urlparse import urlparse as parse_url
    from urlparse import uses_relative, uses_netloc, uses_params, urljoin
    from urllib2 import URLError  # noqa
    from httplib import HTTPException  # noqa
    from contextlib import contextmanager, closing  # noqa
    from functools import wraps  # noqa

    # @wraps(_urlopen)
    @contextmanager
    def urlopen(*args, **kwargs):
        with closing(_urlopen(*args, **kwargs)) as f:
            yield f

_VALID_URLS = set(uses_relative + uses_netloc + uses_params)
_VALID_URLS.discard('')

class BaseIterator(object):
    """Subclass this and provide a "__next__()" method to obtain an iterator.
    Useful only when the object being iterated is non-reusable (e.g. OK for a
    parser, not for an in-memory table, yes for its iterator)."""

    def __iter__(self):
        return self

    def __next__(self):
        raise AbstractMethodError(self)

if not compat.PY3:
    BaseIterator.next = lambda self: self.__next__()

def _is_url(url):
    """Check to see if a URL has a valid protocol.

    Parameters
    ----------
    url : str or unicode

    Returns
    -------
    isurl : bool
        If `url` has a valid protocol return True otherwise False.
    """
    try:
        return parse_url(url).scheme in _VALID_URLS
    except:
        return False

def _is_s3_url(url):
    """Check for an s3, s3n, or s3a url"""
    try:
        return parse_url(url).scheme in ['s3', 's3n', 's3a']
    except:
        return False

def _expand_user(filepath_or_buffer):
    """Return the argument with an initial component of ~ or ~user
       replaced by that user's home directory.

    Parameters
    ----------
    filepath_or_buffer : object to be converted if possible

    Returns
    -------
    expanded_filepath_or_buffer : an expanded filepath or the
                                  input if not expandable
    """
    if isinstance(filepath_or_buffer, string_types):
        return os.path.expanduser(filepath_or_buffer)
    return filepath_or_buffer

def _validate_header_arg(header):
    if isinstance(header, bool):
        raise TypeError("Passing a bool to header is invalid. "
                        "Use header=None for no header or "
                        "header=int or list-like of ints to specify "
                        "the row(s) making up the column names")

def _stringify_path(filepath_or_buffer):
    """Attempt to convert a path-like object to a string.

    Parameters
    ----------
    filepath_or_buffer : object to be converted

    Returns
    -------
    str_filepath_or_buffer : maybe a string version of the object

    Notes
    -----
    Objects supporting the fspath protocol (python 3.6+) are coerced
    according to its __fspath__ method.

    For backwards compatibility with older pythons, pathlib.Path and
    py.path objects are specially coerced.

    Any other object is passed through unchanged, which includes bytes,
    strings, buffers, or anything else that's not even path-like.
    """
    try:
        import pathlib
        _PATHLIB_INSTALLED = True
    except ImportError:
        _PATHLIB_INSTALLED = False

    try:
        from py.path import local as LocalPath
        _PY_PATH_INSTALLED = True
    except ImportError:
        _PY_PATH_INSTALLED = False

    if hasattr(filepath_or_buffer, '__fspath__'):
        return filepath_or_buffer.__fspath__()
    if _PATHLIB_INSTALLED and isinstance(filepath_or_buffer, pathlib.Path):
        return text_type(filepath_or_buffer)
    if _PY_PATH_INSTALLED and isinstance(filepath_or_buffer, LocalPath):
        return filepath_or_buffer.strpath
    return filepath_or_buffer

def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
                           compression=None):
    """
    If the filepath_or_buffer is a url, translate and return the buffer.
    Otherwise passthrough.

    Parameters
    ----------
    filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),
                         or buffer
    encoding : the encoding to use to decode py3 bytes, default is 'utf-8'

    Returns
    -------
    a filepath_or_buffer, the encoding, the compression
    """
    filepath_or_buffer = _stringify_path(filepath_or_buffer)

    if _is_url(filepath_or_buffer):
        req = _urlopen(filepath_or_buffer)
        content_encoding = req.headers.get('Content-Encoding', None)
        if content_encoding == 'gzip':
            # Override compression based on Content-Encoding header
            compression = 'gzip'
        reader = BytesIO(req.read())
        return reader, encoding, compression

    if _is_s3_url(filepath_or_buffer):
        from pandas.io import s3
        return s3.get_filepath_or_buffer(filepath_or_buffer,
                                         encoding=encoding,
                                         compression=compression)

    if isinstance(filepath_or_buffer, (compat.string_types,
                                       compat.binary_type,
                                       mmap.mmap)):
        return _expand_user(filepath_or_buffer), None, compression

    if not is_file_like(filepath_or_buffer):
        msg = "Invalid file path or buffer object type: {_type}"
        raise ValueError(msg.format(_type=type(filepath_or_buffer)))

    return filepath_or_buffer, None, compression

def file_path_to_url(path):
    """
    converts an absolute native path to a FILE URL.

    Parameters
    ----------
    path : a path in native format

    Returns
    -------
    a valid FILE URL
    """
    return urljoin('file:', pathname2url(path))

_compression_to_extension = {
    'gzip': '.gz',
    'bz2': '.bz2',
    'zip': '.zip',
    'xz': '.xz',
}

def _infer_compression(filepath_or_buffer, compression):
    """
    Get the compression method for filepath_or_buffer. If compression='infer',
    the inferred compression method is returned. Otherwise, the input
    compression method is returned unchanged, unless it's invalid, in which
    case an error is raised.

    Parameters
    ----------
    filepath_or_buf :
        a path (str) or buffer
    compression : str or None
        the compression method including None for no compression and 'infer'

    Returns
    -------
    string or None :
        compression method

    Raises
    ------
    ValueError on invalid compression specified
    """

    # No compression has been explicitly specified
    if compression is None:
        return None

    # Infer compression
    if compression == 'infer':
        # Convert all path types (e.g. pathlib.Path) to strings
        filepath_or_buffer = _stringify_path(filepath_or_buffer)
        if not isinstance(filepath_or_buffer, compat.string_types):
            # Cannot infer compression of a buffer, assume no compression
            return None

        # Infer compression from the filename/URL extension
        for compression, extension in _compression_to_extension.items():
            if filepath_or_buffer.endswith(extension):
                return compression
        return None

    # Compression has been specified. Check that it's valid
    if compression in _compression_to_extension:
        return compression

    msg = 'Unrecognized compression type: {}'.format(compression)
    valid = ['infer', None] + sorted(_compression_to_extension)
    msg += '\nValid compression types are {}'.format(valid)
    raise ValueError(msg)

def _get_handle(path_or_buf, mode, encoding=None, compression=None,
                memory_map=False, is_text=True):
    """
    Get file handle for given path/buffer and mode.

    Parameters
    ----------
    path_or_buf :
        a path (str) or buffer
    mode : str
        mode to open path_or_buf with
    encoding : str or None
    compression : str or None
        Supported compression protocols are gzip, bz2, zip, and xz
    memory_map : boolean, default False
        See parsers._parser_params for more information.
    is_text : boolean, default True
        whether file/buffer is in text format (csv, json, etc.), or in binary
        mode (pickle, etc.)
    Returns
    -------
    f : file-like
        A file-like object
    handles : list of file-like objects
        A list of file-like object that were openned in this function.
    """
    try:
        from s3fs import S3File
        need_text_wrapping = (BytesIO, S3File)
    except ImportError:
        need_text_wrapping = (BytesIO,)

    handles = list()
    f = path_or_buf

    # Convert pathlib.Path/py.path.local or string
    path_or_buf = _stringify_path(path_or_buf)
    is_path = isinstance(path_or_buf, compat.string_types)

    if compression:

        if compat.PY2 and not is_path and encoding:
            msg = 'compression with encoding is not yet supported in Python 2'
            raise ValueError(msg)

        # GZ Compression
        if compression == 'gzip':
            import gzip
            if is_path:
                f = gzip.open(path_or_buf, mode)
            else:
                f = gzip.GzipFile(fileobj=path_or_buf)

        # BZ Compression
        elif compression == 'bz2':
            import bz2
            if is_path:
                f = bz2.BZ2File(path_or_buf, mode)
            elif compat.PY2:
                # Python 2's bz2 module can't take file objects, so have to
                # run through decompress manually
                f = StringIO(bz2.decompress(path_or_buf.read()))
                path_or_buf.close()
            else:
                f = bz2.BZ2File(path_or_buf)

        # ZIP Compression
        elif compression == 'zip':
            import zipfile
            zip_file = zipfile.ZipFile(path_or_buf)
            zip_names = zip_file.namelist()
            if len(zip_names) == 1:
                f = zip_file.open(zip_names.pop())
            elif len(zip_names) == 0:
                raise ValueError('Zero files found in ZIP file {}'
                                 .format(path_or_buf))
            else:
                raise ValueError('Multiple files found in ZIP file.'
                                 ' Only one file per ZIP: {}'
                                 .format(zip_names))

        # XZ Compression
        elif compression == 'xz':
            lzma = compat.import_lzma()
            f = lzma.LZMAFile(path_or_buf, mode)

        # Unrecognized Compression
        else:
            msg = 'Unrecognized compression type: {}'.format(compression)
            raise ValueError(msg)

        handles.append(f)

    elif is_path:
        if compat.PY2:
            # Python 2
            f = open(path_or_buf, mode)
        elif encoding:
            # Python 3 and encoding
            f = open(path_or_buf, mode, encoding=encoding)
        elif is_text:
            # Python 3 and no explicit encoding
            f = open(path_or_buf, mode, errors='replace')
        else:
            # Python 3 and binary mode
            f = open(path_or_buf, mode)
        handles.append(f)

    # in Python 3, convert BytesIO or fileobjects passed with an encoding
    if compat.PY3 and is_text and\
            (compression or isinstance(f, need_text_wrapping)):
        from io import TextIOWrapper
        f = TextIOWrapper(f, encoding=encoding)
        handles.append(f)

    if memory_map and hasattr(f, 'fileno'):
        try:
            g = MMapWrapper(f)
            f.close()
            f = g
        except Exception:
            # we catch any errors that may have occurred
            # because that is consistent with the lower-level
            # functionality of the C engine (pd.read_csv), so
            # leave the file handler as is then
            pass

    return f, handles

class MMapWrapper(BaseIterator):
    """
    Wrapper for the Python's mmap class so that it can be properly read in
    by Python's csv.reader class.

    Parameters
    ----------
    f : file object
        File object to be mapped onto memory. Must support the 'fileno'
        method or have an equivalent attribute

    """

Answer: def __init__(self, f):

<think>
The class MMapWrapper is being defined. After the docstring, the next logical line is the initializer method that takes the file object to wrap. In pandas' implementation, the first method defined inside the class is __init__(self, f). Therefore the next line should be the definition of that method.
</think>
def __init__(self, f):


Context:
/*
Copyright 2010 Google Inc

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.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

namespace Google.Apis.Util
{
    ///
    /// Provides the base class for a generic read-only dictionary.
    ///
    /// <typeparam name="TKey">
    /// The type of keys in the dictionary.
    /// </typeparam>
    /// <typeparam name="TValue">
    /// The type of values in the dictionary.
    /// </typeparam>
    /// <remarks>
    /// <para>
    /// An instance of the ReadOnlyDictionary generic class is
    /// always read-only. A dictionary that is read-only is simply a
    /// dictionary with a wrapper that prevents modifying the
    /// dictionary; therefore, if changes are made to the underlying
    /// dictionary, the read-only dictionary reflects those changes.
    /// See <see cref="Dictionary{TKey,TValue}"/> for a modifiable version of
    /// this class.
    /// </para>
    /// <para>
    /// Notes to Implementers This base class is provided to
    /// make it easier for implementers to create a generic read-only
    /// custom dictionary. Implementers are encouraged to extend this
    /// base class instead of creating their own.
    /// </para>
    /// </remarks>
    [DebuggerDisplay("Count = {Count}")]
    [DebuggerTypeProxy(typeof(ReadOnlyDictionaryDebugView<,>))]
#if !SILVERLIGHT
    [Serializable]
#endif
    public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
    {
        private readonly IDictionary<TKey, TValue> source;

        ///
        /// Initializes a new instance of the
        /// <see cref="T:ReadOnlyDictionary`2" /> class that wraps
        /// the supplied <paramref name="dictionaryToWrap"/>.
        ///
        /// <param name="dictionaryToWrap">The <see cref="T:IDictionary`2" />
        /// that will be wrapped.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// Thrown when the dictionary is null.
        /// </exception>
        public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionaryToWrap)
        {
            if (dictionaryToWrap == null)
            {
                throw new ArgumentNullException("dictionaryToWrap");
            }

            source = dictionaryToWrap;
        }

        #region IDictionary Members

        /// Gets a value indicating whether the
        /// dictionary has a fixed size. This property will
        /// always return true.
        bool IDictionary.IsFixedSize
        {
            get { return true; }
        }

        /// Gets a value indicating whether the
        /// dictionary is read-only.This property will
        /// always return true.
        bool IDictionary.IsReadOnly
        {
            get { return true; }
        }

        /// Gets an <see cref="ICollection"/> object
        /// containing the keys of the dictionary object.
        ICollection IDictionary.Keys
        {
            get { return ((IDictionary) source).Keys; }
        }

        ///
        /// Gets an ICollection object containing the values in the DictionaryBase object.
        ///
        ICollection IDictionary.Values
        {
            get { return ((IDictionary) source).Values; }
        }

        ///
        /// Gets a value indicating whether access to the dictionary
        /// is synchronized (thread safe).
        ///
        bool ICollection.IsSynchronized
        {
            get { return ((ICollection) source).IsSynchronized; }
        }

        ///
        /// Gets an object that can be used to synchronize access to dictionary.
        ///
        object ICollection.SyncRoot
        {
            get { return ((ICollection) source).SyncRoot; }
        }

        ///
        /// Gets or sets the element with the specified key.
        ///
        /// <param name="key">The key of the element to get or set.</param>
        /// <returns>The element with the specified key. </returns>
        /// <exception cref="NotSupportedException">
        /// Thrown when a value is set.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown when the key is a null reference (Nothing in Visual Basic).
        /// </exception>
        object IDictionary.this[object key]
        {
            get { return ((IDictionary) source)[key]; }
            set { ThrowNotSupportedException(); }
        }

        ///
        /// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
        ///
        /// <param name="key">
        /// The System.Object to use as the key of the element to add.
        /// </param>
        /// <param name="value">
        /// The System.Object to use as the value of the element to add.
        /// </param>
        void IDictionary.Add(object key, object value)
        {
            ThrowNotSupportedException();
        }

        ///
        /// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
        ///
        void IDictionary.Clear()
        {
            ThrowNotSupportedException();
        }

        ///
        /// Determines whether the IDictionary object contains an element
        /// with the specified key.
        ///
        /// <param name="key">
        /// The key to locate in the IDictionary object.
        /// </param>
        /// <returns>
        /// true if the IDictionary contains an element with the key;
        /// otherwise, false.
        /// </returns>
        bool IDictionary.Contains(object key)
        {
            return ((IDictionary) source).Contains(key);
        }

        ///
        /// Returns an <see cref="IDictionaryEnumerator"/> for the
        /// <see cref="IDictionary"/>.
        ///
        /// <returns>
        /// An IDictionaryEnumerator for the IDictionary.
        /// </returns>
        IDictionaryEnumerator IDictionary.GetEnumerator()
        {
            return ((IDictionary) source).GetEnumerator();
        }

        ///
        /// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
        ///
        /// <param name="key">
        /// Gets an <see cref="ICollection"/> object containing the keys of the
        /// <see cref="IDictionary"/> object.
        /// </param>
        void IDictionary.Remove(object key)
        {
            ThrowNotSupportedException();
        }

        ///
        /// For a description of this member, see <see cref="ICollection.CopyTo"/>.
        ///
        /// <param name="array">
        /// The one-dimensional Array that is the destination of the elements copied from
        /// ICollection. The Array must have zero-based indexing.
        /// </param>
        /// <param name="index">
        /// The zero-based index in Array at which copying begins.
        /// </param>
        void ICollection.CopyTo(Array array, int index)
        {
            ((ICollection) source).CopyTo(array, index);
        }

        #endregion

        #region IDictionary<TKey,TValue> Members

        ///
        /// Gets the number of key/value pairs contained in the
        /// <see cref="T:ReadOnlyDictionary`2"></see>.
        ///
        /// <value>The number of key/value pairs.</value>
        /// <returns>The number of key/value pairs contained in the
        /// <see cref="T:ReadOnlyDictionary`2"></see>.</returns>
        public int Count
        {
            get { return source.Count; }
        }

        /// Gets a collection containing the keys in the
        /// <see cref="T:ReadOnlyDictionary{TKey,TValue}"></see>.
        /// <value>A <see cref="Dictionary{TKey,TValue}.KeyCollection"/>
        /// containing the keys.</value>
        /// <returns>A
        /// <see cref="Dictionary{TKey,TValue}.KeyCollection"/>
        /// containing the keys in the
        /// <see cref="Dictionary{TKey,TValue}"></see>.
        /// </returns>
        public ICollection<TKey> Keys
        {
            get { return source.Keys; }
        }

        ///
        /// Gets a collection containing the values of the
        /// <see cref="T:ReadOnlyDictionary`2"/>.
        ///
        /// <value>The collection of values.</value>
        public ICollection<TValue> Values
        {
            get { return source.Values; }
        }

        /// Gets a value indicating whether the dictionary is read-only.
        /// This value will always be true.
        bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
        {
            get { return true; }
        }

        ///
        /// Gets or sets the value associated with the specified key.
        ///
        /// <returns>
        /// The value associated with the specified key. If the specified key
        /// is not found, a get operation throws a
        /// <see cref="T:System.Collections.Generic.KeyNotFoundException" />,
        /// and a set operation creates a new element with the specified key.
        /// </returns>
        /// <param name="key">The key of the value to get or set.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// Thrown when the key is null.
        /// </exception>
        /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
        /// The property is retrieved and key does not exist in the collection.
        /// </exception>
        public TValue this[TKey key]
        {
            get { return source[key]; }
            set { ThrowNotSupportedException(); }
        }

        /// This method is not supported by the
        /// <see cref="T:ReadOnlyDictionary`2"/>.
        /// <param name="key">
        /// The object to use as the key of the element to add.</param>
        /// <param name="value">
        /// The object to use as the value of the element to add.</param>
        void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
        {
            ThrowNotSupportedException();
        }

        /// Determines whether the <see cref="T:ReadOnlyDictionary`2" />
        /// contains the specified key.
        /// <returns>
        /// True if the <see cref="T:ReadOnlyDictionary`2" /> contains
        /// an element with the specified key; otherwise, false.
        /// </returns>
        /// <param name="key">The key to locate in the
        /// <see cref="T:ReadOnlyDictionary`2"></see>.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// Thrown when the key is null.
        /// </exception>
        public bool ContainsKey(TKey key)
        {
            return source.ContainsKey(key);
        }

        ///
        /// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
        ///
        /// <param name="key">The key of the element to remove.</param>
        /// <returns>
        /// True if the element is successfully removed; otherwise, false.
        /// </returns>
        bool IDictionary<TKey, TValue>.Remove(TKey key)
        {
            ThrowNotSupportedException();
            return false;
        }

        ///
        /// Gets the value associated with the specified key.
        ///
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value
        /// associated with the specified key, if the key is found;
        /// otherwise, the default value for the type of the value parameter.
        /// This parameter is passed uninitialized.</param>
        /// <returns>
        /// true if the <see cref="T:ReadOnlyDictionary`2" /> contains
        /// an element with the specified key; otherwise, false.
        /// </returns>

Answer: public bool TryGetValue(TKey key, out TValue value)

<think>
The code is inside the IDictionary<TKey,TValue> region of a read‑only dictionary implementation. After the XML comment describing a method that returns a bool indicating whether a key exists and outputs its value, the next member is the TryGetValue method signature. The appropriate line is the public method declaration matching IDictionary<TKey,TValue>.TryGetValue.
</think>
public bool TryGetValue(TKey key, out TValue value)


Context:
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

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

import os

from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.build_graph.files import Files
from pants.cache.cache_setup import CacheSetup
from pants.option.arg_splitter import GLOBAL_SCOPE
from pants.subsystem.subsystem import Subsystem
from pants.subsystem.subsystem_client_mixin import SubsystemDependency
from pants.task.task import Task
from pants.util.dirutil import safe_rmtree
from pants_test.tasks.task_test_base import TaskTestBase

class DummyTask(Task):
  """A task that appends the content of a Files's sources into its results_dir."""

  _implementation_version = 0
  _force_fail = False

  @property
  def incremental(self):
    return self._incremental

  @property
  def cache_target_dirs(self):
    return True

  @classmethod
  def implementation_version_str(cls):
    # NB: Intentionally ignoring `super` and returning a simplified version.
    return str(cls._implementation_version)

  # Enforces a single VT and returns a tuple of (vt, was_valid).
  def execute(self):
    with self.invalidated(self.context.targets()) as invalidation:
      assert len(invalidation.all_vts) == 1
      vt = invalidation.all_vts[0]
      was_valid = vt.valid
      if not was_valid:
        if vt.is_incremental:
          assert os.path.isdir(vt.previous_results_dir)
        for source in vt.target.sources_relative_to_buildroot():
          with open(os.path.join(get_buildroot(), source), 'r') as infile:
            outfile_name = os.path.join(vt.results_dir, source)
            with open(outfile_name, 'a') as outfile:
              outfile.write(infile.read())
        if self._force_fail:
          raise TaskError('Task forced to fail before updating vt state.')
        vt.update()
      return vt, was_valid

class FakeTask(Task):
  _impls = []

  @classmethod
  def implementation_version(cls):
    return super(FakeTask, cls).implementation_version() + cls._impls

  @classmethod
  def supports_passthru_args(cls):
    return True

  options_scope = 'fake-task'

  _deps = ()

  @classmethod
  def subsystem_dependencies(cls):
    return super(FakeTask, cls).subsystem_dependencies() + cls._deps

  def execute(self): pass

class OtherFakeTask(FakeTask):
  _other_impls = []

  @classmethod
  def supports_passthru_args(cls):
    return False

  @classmethod
  def implementation_version(cls):
    return super(OtherFakeTask, cls).implementation_version() + cls._other_impls

  options_scope = 'other-fake-task'

class FakeSubsystem(Subsystem):
  options_scope = 'fake-subsystem'

  @classmethod
  def register_options(cls, register):
    super(FakeSubsystem, cls).register_options(register)
    register('--fake-option', type=bool)

class AnotherFakeTask(Task):
  options_scope = 'another-fake-task'

  @classmethod
  def supports_passthru_args(cls):
    return True

  @classmethod
  def subsystem_dependencies(cls):
    return super(AnotherFakeTask, cls).subsystem_dependencies() + (FakeSubsystem.scoped(cls),)

  def execute(self): pass

class YetAnotherFakeTask(AnotherFakeTask):
  options_scope = 'yet-another-fake-task'

  @classmethod
  def supports_passthru_args(cls):
    return False

class TaskTest(TaskTestBase):

  _filename = 'f'
  _file_contents = 'results_string\n'
  _cachedir = 'local_artifact_cache'

  @classmethod
  def task_type(cls):
    return DummyTask

  def assertContent(self, vt, content):
    with open(os.path.join(vt.current_results_dir, self._filename), 'r') as f:
      self.assertEquals(f.read(), content)

  def _toggle_cache(self, enable_artifact_cache):
    cache_dir = self.create_dir(self._cachedir)
    self.set_options_for_scope(
      CacheSetup.options_scope,
      write_to=[cache_dir],
      read_from=[cache_dir],
      write=enable_artifact_cache,
      read=enable_artifact_cache,
    )

  def _fixture(self, incremental, options=None):
    target = self.make_target(':t', target_type=Files, sources=[self._filename])
    context = self.context(options=options, target_roots=[target])
    task = self.create_task(context)
    task._incremental = incremental
    return task, target

  def _run_fixture(self, content=None, incremental=False, artifact_cache=False, options=None):
    content = content or self._file_contents
    self._toggle_cache(artifact_cache)

    task, target = self._fixture(incremental=incremental, options=options)
    self._create_clean_file(target, content)
    vtA, was_valid = task.execute()
    return task, vtA, was_valid

  def _create_clean_file(self, target, content):
    self.create_file(self._filename, content)
    target.mark_invalidation_hash_dirty()

  def _cache_ignore_options(self, globally=False):
    return {
      'cache' + ('' if globally else '.' + self.options_scope): {
        'ignore': True
      }
    }

  def _synthesize_subtype(self, name='A', scope=None, cls=FakeTask, **kwargs):
    """Generate a synthesized subtype of `cls`."""
    if scope is None:
      scope = cls.options_scope
    subclass_name = b'test_{0}_{1}_{2}'.format(cls.__name__, scope, name)
    kwargs['options_scope'] = scope
    return type(subclass_name, (cls,), kwargs)

  def _instantiate_synthesized_type(self, task_type, **kwargs):
    """Generate a new instance of the synthesized type `task_type`."""
    ctx = super(TaskTestBase, self).context(for_task_types=[task_type], **kwargs)
    return task_type(ctx, self.test_workdir)

  def _task_type_to_fp(self, task_type, **kwargs):
    """Instantiate the `task_type` and return its fingerprint."""
    task_object = self._instantiate_synthesized_type(task_type, **kwargs)
    return task_object.fingerprint

  def _synth_fp(self, scope=None, cls=FakeTask, options_fingerprintable=None, **kwargs):
    """Synthesize a subtype of `cls`, instantiate it, and take its
    fingerprint. `options_fingerprintable` describes the registered options in
    their respective scopes which can contribute to the task fingerprint."""
    task_type = self._synthesize_subtype(scope=scope, cls=cls, **kwargs)
    return self._task_type_to_fp(
      task_type, options_fingerprintable=options_fingerprintable)

  def test_revert_after_failure(self):
    # Regression test to catch the following scenario:
    #
    # 1) In state A: Task suceeds and writes some output.  Key is recorded by the invalidator.
    # 2) In state B: Task fails, but writes some output.  Key is not recorded.
    # 3) After reverting back to state A: The current key is the same as the one recorded at the
    #    end of step 1), so it looks like no work needs to be done, but actually the task
    #    must re-run, to overwrite the output written in step 2.

    good_content = "good_content"
    bad_content = "bad_content"
    task, target = self._fixture(incremental=False)

    # Clean run succeeds.
    self._create_clean_file(target, good_content)
    vt, was_valid = task.execute()
    self.assertFalse(was_valid)
    self.assertContent(vt, good_content)

    # Change causes the task to fail.
    self._create_clean_file(target, bad_content)
    task._force_fail = True
    self.assertRaises(TaskError, task.execute)
    task._force_fail = False

    # Reverting to the previous content should invalidate, so the task
    # can reset any state created by the failed run.
    self._create_clean_file(target, good_content)
    vt, was_valid = task.execute()
    self.assertFalse(was_valid)
    self.assertContent(vt, good_content)

  def test_incremental(self):
    """Run three times with two unique fingerprints."""

    one = '1\n'
    two = '2\n'
    three = '3\n'
    task, target = self._fixture(incremental=True)

    # Clean - this is the first run so the VT is invalid.
    self._create_clean_file(target, one)
    vtA, was_A_valid = task.execute()
    self.assertFalse(was_A_valid)
    self.assertContent(vtA, one)

    # Changed the source file, so it copies the results from vtA.
    self._create_clean_file(target, two)
    vtB, was_B_valid = task.execute()
    self.assertFalse(was_B_valid)
    self.assertEqual(vtB.previous_cache_key, vtA.cache_key)
    self.assertContent(vtB, one + two)
    self.assertTrue(vtB.has_previous_results_dir)

    # Another changed source means a new cache_key. The previous_results_dir is copied.
    self._create_clean_file(target, three)
    vtC, was_C_valid = task.execute()
    self.assertFalse(was_C_valid)
    self.assertTrue(vtC.has_previous_results_dir)
    self.assertEqual(vtC.previous_results_dir, vtB.current_results_dir)
    self.assertContent(vtC, one + two + three)

    # Again create a clean file but this time reuse an old cache key - in this case vtB.
    self._create_clean_file(target, two)

    # This VT will be invalid, since there is no cache hit and it doesn't match the immediately
    # previous run. It will wipe the invalid vtB.current_results_dir and followup by copying in the
    # most recent results_dir, from vtC.
    vtD, was_D_valid = task.execute()
    self.assertFalse(was_D_valid)
    self.assertTrue(vtD.has_previous_results_dir)
    self.assertEqual(vtD.previous_results_dir, vtC.current_results_dir)
    self.assertContent(vtD, one + two + three + two)

    # And that the results_dir was stable throughout.
    self.assertEqual(vtA.results_dir, vtB.results_dir)
    self.assertEqual(vtB.results_dir, vtD.results_dir)

  def test_non_incremental(self):
    """Non-incremental should be completely unassociated."""

    one = '1\n'
    two = '2\n'
    task, target = self._fixture(incremental=False)

    # Run twice.
    self._create_clean_file(target, one)
    vtA, _ = task.execute()
    self.assertContent(vtA, one)
    self._create_clean_file(target, two)
    vtB, _ = task.execute()

    # Confirm two unassociated current directories with a stable results_dir.
    self.assertContent(vtA, one)
    self.assertContent(vtB, two)
    self.assertNotEqual(vtA.current_results_dir, vtB.current_results_dir)
    self.assertEqual(vtA.results_dir, vtB.results_dir)

  def test_implementation_version(self):
    """When the implementation version changes, previous artifacts are not available."""

    one = '1\n'
    two = '2\n'
    task, target = self._fixture(incremental=True)

    # Run twice, with a different implementation version the second time.
    DummyTask._implementation_version = 0
    self._create_clean_file(target, one)
    vtA, _ = task.execute()
    self.assertContent(vtA, one)
    DummyTask._implementation_version = 1
    self._create_clean_file(target, two)
    vtB, _ = task.execute()

    # No incrementalism.
    self.assertFalse(vtA.is_incremental)
    self.assertFalse(vtB.is_incremental)

    # Confirm two unassociated current directories, and unassociated stable directories.
    self.assertContent(vtA, one)
    self.assertContent(vtB, two)
    self.assertNotEqual(vtA.current_results_dir, vtB.current_results_dir)
    self.assertNotEqual(vtA.results_dir, vtB.results_dir)

  def test_execute_cleans_invalid_result_dirs(self):
    # Regression test to protect task.execute() from returning invalid dirs.
    task, vt, _ = self._run_fixture()
    self.assertNotEqual(os.listdir(vt.results_dir), [])
    self.assertTrue(os.path.islink(vt.results_dir))

    # Mimic the failure case, where an invalid task is run twice, due to failed download or
    # something.
    vt.force_invalidate()

    # But if this VT is invalid for a second run, the next invalidation deletes and recreates.
    self.assertTrue(os.path.islink(vt.results_dir))
    self.assertTrue(os.path.isdir(vt.current_results_dir))

  def test_cache_hit_short_circuits_incremental_copy(self):
    # Tasks should only copy over previous results if there is no cache hit, otherwise the copy is
    # wasted.
    first_contents = 'staid country photo'
    second_contents = 'shocking tabloid secret'

    self.assertFalse(self.buildroot_files(self._cachedir))
    # Initial run will have been invalid no cache hit, and with no previous_results_dir.
    task, vtA, was_A_valid = self._run_fixture(content=first_contents, incremental=True,
                                               artifact_cache=True)

    self.assertTrue(self.buildroot_files(self._cachedir))
    self.assertTrue(task.incremental)
    self.assertFalse(was_A_valid)

    # Invalidate and then execute with the same cache key.
    # Should be valid due to the artifact cache hit. No previous_results_dir will have been copied.
    vtA.force_invalidate()
    vtB, was_B_valid = task.execute()
    self.assertEqual(vtA.cache_key.hash, vtB.cache_key.hash)
    self.assertTrue(was_B_valid)
    self.assertFalse(vtB.has_previous_results_dir)

    # Change the cache_key and disable the cache_reads.
    # This results in an invalid vt, with no cache hit. It will then copy the vtB.previous_results
    # into vtC.results_dir.
    self._toggle_cache(False)
    self._create_clean_file(vtB.target, second_contents)

    vtC, was_C_valid = task.execute()
    self.assertNotEqual(vtB.cache_key.hash, vtC.cache_key.hash)
    self.assertEqual(vtC.previous_cache_key, vtB.cache_key)
    self.assertFalse(was_C_valid)

    self.assertTrue(vtC.has_previous_results_dir)
    self.assertEqual(vtB.current_results_dir, vtC.previous_results_dir)

    # Verify the content. The task was invalid twice - the initial run and the run with the changed
    # source file. Only vtC (previous sucessful runs + cache miss) resulted in copying the
    # previous_results.
    self.assertContent(vtC, first_contents + second_contents)

  # live_dirs() is in cache_manager, but like all of these tests, only makes sense to test as a
  # sequence of task runs.
  def test_live_dirs(self):
    task, vtA, _ = self._run_fixture(incremental=True)

    vtA_live = list(vtA.live_dirs())
    self.assertIn(vtA.results_dir, vtA_live)
    self.assertIn(vtA.current_results_dir, vtA_live)
    self.assertEqual(len(vtA_live), 2)

    self._create_clean_file(vtA.target, 'bar')
    vtB, _ = task.execute()
    vtB_live = list(vtB.live_dirs())

    # This time it contains the previous_results_dir.
    self.assertIn(vtB.results_dir, vtB_live)
    self.assertIn(vtB.current_results_dir, vtB_live)
    self.assertIn(vtA.current_results_dir, vtB_live)
    self.assertEqual(len(vtB_live), 3)

    # Delete vtB results_dir. live_dirs() should only return existing dirs, even if it knows the
    # previous_cache_key.
    safe_rmtree(vtB.current_results_dir)

    self._create_clean_file(vtB.target, 'baz')
    vtC, _ = task.execute()
    vtC_live = list(vtC.live_dirs())
    self.assertNotIn(vtB.current_results_dir, vtC_live)
    self.assertEqual(len(vtC_live), 2)

  def test_ignore_global(self):
    _, vtA, was_valid = self._run_fixture()
    self.assertFalse(was_valid)
    self.assertTrue(vtA.cacheable)

    self.reset_build_graph()
    _, vtA, was_valid = self._run_fixture()
    self.assertTrue(was_valid)
    self.assertTrue(vtA.cacheable)

    self.reset_build_graph()
    _, vtA, was_valid = self._run_fixture(options=self._cache_ignore_options(globally=True))
    self.assertFalse(was_valid)
    self.assertFalse(vtA.cacheable)

  def test_ignore(self):
    _, vtA, was_valid = self._run_fixture()
    self.assertFalse(was_valid)
    self.assertTrue(vtA.cacheable)

Answer: self.reset_build_graph()

<think>
The test_ignore method mirrors test_ignore_global, which after asserting cacheable resets the build graph before running with ignore options. The next logical line is resetting the graph.
</think>
self.reset_build_graph()