text:
import sys
import traceback
from pysnmp.smi.indices import OidOrderedDict
from pysnmp.smi import exval, error
from pysnmp.proto import rfc1902
from pysnmp import cache, debug
from pyasn1.error import PyAsn1Error

Integer, ObjectIdentifier = mibBuilder.importSymbols(
    "ASN1", "Integer", "ObjectIdentifier"
)

(ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint,
 ValueRangeConstraint, ValueSizeConstraint) = mibBuilder.importSymbols(
     "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion",
     "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint"
 )

# syntax of objects

OctetString = rfc1902.OctetString
Bits = rfc1902.Bits
Integer32 = rfc1902.Integer32
IpAddress = rfc1902.IpAddress
Counter32 = rfc1902.Counter32
Gauge32 = rfc1902.Gauge32
Unsigned32 = rfc1902.Unsigned32
TimeTicks = rfc1902.TimeTicks
Opaque = rfc1902.Opaque
Counter64 = rfc1902.Counter64

class ExtUTCTime(OctetString):
    subtypeSpec = OctetString.subtypeSpec+ConstraintsUnion(ValueSizeConstraint(11, 11), ValueSizeConstraint(13, 13))

# MIB tree foundation class

class MibNode:
    label = ''
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.name)

    def getName(self):
        return self.name

    def getLabel(self):
        return self.label

    def setLabel(self, label):
        self.label = label
        return self

    def clone(self, name=None):
        myClone = self.__class__(self.name)
        if name is not None:
            myClone.name = name
        if self.label is not None:
            myClone.label = self.label
        return myClone

# definitions for information modules

class ModuleIdentity(MibNode):
    def getLastUpdated(self):
        return getattr(self, 'lastUpdated', '')

    def setLastUpdated(self, v):
        self.lastUpdated = v
        return self

    def getOrganization(self):
        return getattr(self, 'organization', '')

    def setOrganization(self, v):
        self.organization = v
        return self

    def getContactInfo(self):
        return getattr(self, 'contactInfo', '')

    def setContactInfo(self, v):
        self.contactInfo = v
        return self

    def getDescription(self):
        return getattr(self, 'description', '')

    def setDescription(self, v):
        self.description = v
        return self

    def getRevisions(self):
        return getattr(self, 'revisions', ())

    def setRevisions(self, args):
        self.revisions = args
        return self

    def asn1Print(self):
        return '\
MODULE-IDENTITY\n\
  LAST-UPDATED %s\n\
  ORGANIZATION \"%s\"\n\
  CONTACT-INFO \"%s\"\n\
  DESCRIPTION \"%s\"\n\
  %s\
' % (self.getLastUpdated(),
     self.getOrganization(),
     self.getContactInfo(),
     self.getDescription(),
     ''.join(["REVISION \"%s\"\n" % x for x in self.getRevisions()]))

class ObjectIdentity(MibNode):
    def getStatus(self):
        return getattr(self, 'status', 'current')

    def setStatus(self, v):
        self.status = v
        return self

    def getDescription(self):
        return getattr(self, 'description', '')

    def setDescription(self, v):
        self.description = v
        return self

    def getReference(self):
        return getattr(self, 'reference', '')

    def setReference(self, v):
        self.reference = v
        return self

    def asn1Print(self):
        return '\
OBJECT-IDENTITY\n\
  STATUS %s\n\
  DESCRIPTION \"%s\"\n\
  REFERENCE \"%s\"\
' % (self.getStatus(),
     self.getDescription(),
     self.getReference())

# definition for objects

class NotificationType(MibNode):
    def getObjects(self):
        return getattr(self, 'objects', ())

    def setObjects(self, *args):
        self.objects = args
        return self

    def getStatus(self):
        return getattr(self, 'status', 'current')

    def setStatus(self, v):
        self.status = v
        return self

    def getDescription(self):
        return getattr(self, 'description', '')

    def setDescription(self, v):
        self.description = v
        return self

    def getRevisions(self):
        return getattr(self, 'revisions', ())

    def setRevisions(self, args):
        self.revisions = args
        return self

    def asn1Print(self):
        return '\
NOTIFICATION-TYPE\n\
  OBJECTS { %s }\n\
  STATUS %s\n\
  DESCRIPTION \"%s\"\n\
  %s\
' % (', '.join([x for x in self.getObjects()]),
     self.getStatus(),
     self.getDescription(),
     ''.join(["REVISION \"%s\"\n" % x for x in self.getRevisions()]))

class MibIdentifier(MibNode):
    def asn1Print(self):
        return 'OBJECT IDENTIFIER'

class ObjectType(MibNode):
    maxAccess = None
    def __init__(self, name, syntax=None):
        MibNode.__init__(self, name)
        self.syntax = syntax

    # XXX
    def __eq__(self, other):
        return self.syntax == other

    def __ne__(self, other):
        return self.syntax != other

    def __lt__(self, other):
        return self.syntax < other

    def __le__(self, other):
        return self.syntax <= other

    def __gt__(self, other):
        return self.syntax > other

    def __ge__(self, other):
        return self.syntax >= other

    def __repr__(self):
        return '%s(%r, %r)' % (
            self.__class__.__name__, self.name, self.syntax
        )

    def getSyntax(self):
        return self.syntax

    def setSyntax(self, v):
        self.syntax = v
        return self

    def getUnits(self):
        return getattr(self, 'units', '')

    def setUnits(self, v):
        self.units = v
        return self

    def getMaxAccess(self):
        return getattr(self, 'maxAccess', 'not-accessible')

    def setMaxAccess(self, v):
        self.maxAccess = v
        return self

    def getStatus(self):
        return getattr(self, 'status', 'current')

    def setStatus(self, v):
        self.status = v
        return self

    def getDescription(self):
        return getattr(self, 'description', '')

    def setDescription(self, v):
        self.description = v
        return self

    def getReference(self):
        return getattr(self, 'reference', '')

    def setReference(self, v):
        self.reference = v
        return self

    def asn1Print(self):
        return '\
OBJECT-TYPE\n\
  SYNTAX %s\n\
  UNITS \"%s\"\n\
  MAX-ACCESS %s\n\
  STATUS %s\n\
  DESCRIPTION \"%s\"\n\
  REFERENCE \"%s\"\
' % (self.getSyntax().__class__.__name__,
     self.getUnits(),
     self.getMaxAccess(),
     self.getStatus(),
     self.getDescription(),
     self.getReference())

class MibTree(ObjectType):
    branchVersionId = 0    # cnanges on tree structure change
    maxAccess = 'not-accessible'
    def __init__(self, name, syntax=None):
        ObjectType.__init__(self, name, syntax)
        self._vars = OidOrderedDict()

    # Subtrees registration

    def registerSubtrees(self, *subTrees):
        self.branchVersionId += 1
        for subTree in subTrees:
            if subTree.name in self._vars:
                raise error.SmiError(
                    'MIB subtree %s already registered at %s' %  (subTree.name, self)
                    )
            self._vars[subTree.name] = subTree

    def unregisterSubtrees(self, *names):
        self.branchVersionId += 1
        for name in names:
            # This may fail if you fill a table by exporting MibScalarInstances
            # but later drop them through SNMP.
            if name not in self._vars:
                raise  error.SmiError(
                    'MIB subtree %s not registered at %s' %  (name, self)
                    )
            del self._vars[name]

    #
    # Tree traversal
    #
    # Missing branches are indicated by the NoSuchObjectError exception.
    # Although subtrees may indicate their missing branches by the
    # NoSuchInstanceError exception.
    #

    def getBranch(self, name, idx):
        """Return a branch of this tree where the 'name' OID may reside"""
        for keyLen in self._vars.getKeysLens():
            subName = name[:keyLen]
            if subName in self._vars:
                return self._vars[subName]

        raise error.NoSuchObjectError(name=name, idx=idx)

    def getNextBranch(self, name, idx=None):
        # Start from the beginning
        if self._vars:
            first = list(self._vars.keys())[0]
        if self._vars and name < first:
            return self._vars[first]
        else:
            try:
                return self._vars[self._vars.nextKey(name)]
            except KeyError:
                raise error.NoSuchObjectError(idx=idx, name=name)

    def getNode(self, name, idx=None):
        """Return tree node found by name"""
        if name == self.name:
            return self
        else:
            return self.getBranch(name, idx).getNode(name, idx)

    def getNextNode(self, name, idx=None):
        """Return tree node next to name"""
        try:
            nextNode = self.getBranch(name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            return self.getNextBranch(name, idx)
        else:
            try:
                return nextNode.getNextNode(name, idx)
            except (error.NoSuchInstanceError, error.NoSuchObjectError):
                try:
                    return self._vars[self._vars.nextKey(nextNode.name)]
                except KeyError:
                    raise error.NoSuchObjectError(idx=idx, name=name)

    # MIB instrumentation

    # Read operation

    def readTest(self, name, val, idx, acInfo):
        (acFun, acCtx) = acInfo
        if name == self.name:
            if acFun:
                if self.maxAccess not in ('readonly',
                                          'readwrite', 'readcreate') or \
                       acFun(name, self.syntax, idx, 'read', acCtx):
                    raise error.NoAccessError(idx=idx, name=name)
        else:
            try:
                node = self.getBranch(name, idx)
            except (error.NoSuchInstanceError, error.NoSuchObjectError):
                return # missing object is not an error here
            else:
                node.readTest(name, val, idx, acInfo)

    def readGet(self, name, val, idx, acInfo):
        try:
            node = self.getBranch(name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            return name, exval.noSuchObject
        else:
            return node.readGet(name, val, idx, acInfo)

    # Read next operation is subtree-specific

    depthFirst, breadthFirst = 0, 1

    def readTestNext(self, name, val, idx, acInfo, oName=None):
        if oName is None:
            oName = name
            topOfTheMib = True
        else:
            topOfTheMib = False
        nextName = name
        direction = self.depthFirst
        while 1:  # XXX linear search here
            if direction == self.depthFirst:
                direction = self.breadthFirst
                try:
                    node = self.getBranch(nextName, idx)
                except (error.NoSuchInstanceError, error.NoSuchObjectError):
                    continue
            else:
                try:
                    node = self.getNextBranch(nextName, idx)
                except (error.NoSuchInstanceError, error.NoSuchObjectError):
                    if topOfTheMib:
                        return
                    raise
                direction = self.depthFirst
                nextName = node.name
            try:
                return node.readTestNext(nextName, val, idx, acInfo, oName)
            except (error.NoAccessError, error.NoSuchInstanceError, error.NoSuchObjectError):
                pass

    def readGetNext(self, name, val, idx, acInfo, oName=None):
        if oName is None:
            oName = name
            topOfTheMib = True
        else:
            topOfTheMib = False
        nextName = name
        direction = self.depthFirst
        while True:  # XXX linear search ahead!
            if direction == self.depthFirst:
                direction = self.breadthFirst
                try:
                    node = self.getBranch(nextName, idx)
                except (error.NoSuchInstanceError, error.NoSuchObjectError):
                    continue
            else:
                try:
                    node = self.getNextBranch(nextName, idx)
                except (error.NoSuchInstanceError, error.NoSuchObjectError):
                    if topOfTheMib:
                        return name, exval.endOfMib
                    raise
                direction = self.depthFirst
                nextName = node.name
            try:
                return node.readGetNext(nextName, val, idx, acInfo, oName)
            except (error.NoAccessError, error.NoSuchInstanceError, error.NoSuchObjectError):
                pass

    # Write operation

    def writeTest(self, name, val, idx, acInfo):
        acFun, acCtx = acInfo
        if name == self.name:
            # Make sure variable is writable
            if acFun:
                if self.maxAccess not in ('readwrite', 'readcreate') or \
                       acFun(name, self.syntax, idx, 'write', acCtx):
                    raise error.NotWritableError(idx=idx, name=name)
        else:
            node = self.getBranch(name, idx)
            node.writeTest(name, val, idx, acInfo)

    def writeCommit(self, name, val, idx, acInfo):
        self.getBranch(name, idx).writeCommit(name, val, idx, acInfo)

    def writeCleanup(self, name, val, idx, acInfo):
        self.branchVersionId += 1
        self.getBranch(name, idx).writeCleanup(name, val, idx, acInfo)

    def writeUndo(self, name, val, idx, acInfo):
        self.getBranch(name, idx).writeUndo(name, val, idx, acInfo)

class MibScalar(MibTree):
    """Scalar MIB variable. Implements access control checking."""
    maxAccess = 'readonly'

    #
    # Subtree traversal
    #
    # Missing branches are indicated by the NoSuchInstanceError exception.
    #

    def getBranch(self, name, idx):
        try:
            return MibTree.getBranch(self, name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def getNextBranch(self, name, idx=None):
        try:
            return MibTree.getNextBranch(self, name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def getNode(self, name, idx=None):
        try:
            return MibTree.getNode(self, name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def getNextNode(self, name, idx=None):
        try:
            return MibTree.getNextNode(self, name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            raise error.NoSuchInstanceError(idx=idx, name=name)

    # MIB instrumentation methods

    # Read operation

    def readTest(self, name, val, idx, acInfo):
        (acFun, acCtx) = acInfo
        if name == self.name:
            raise error.NoAccessError(idx=idx, name=name)
        if acFun:
            if self.maxAccess not in ('readonly', 'readwrite',
                                      'readcreate') or \
                    acFun(name, self.syntax, idx, 'read', acCtx):
                raise error.NoAccessError(idx=idx, name=name)
        MibTree.readTest(self, name, val, idx, acInfo)

    def readGet(self, name, val, idx, acInfo):
        try:
            node = self.getBranch(name, idx)
        except error.NoSuchInstanceError:
            return name, exval.noSuchInstance
        else:
            return node.readGet(name, val, idx, acInfo)

    def readTestNext(self, name, val, idx, acInfo, oName=None):
        (acFun, acCtx) = acInfo
        if acFun:
            if self.maxAccess not in ('readonly', 'readwrite',
                                      'readcreate') or \
                    acFun(name, self.syntax, idx, 'read', acCtx):
                raise error.NoAccessError(idx=idx, name=name)
        MibTree.readTestNext(self, name, val, idx, acInfo, oName)

    def readGetNext(self, name, val, idx, acInfo, oName=None):
        (acFun, acCtx) = acInfo
        # have to dublicate AC here as *Next code above treats
        # noAccess as a noSuchObject at the Test stage, goes on
        # to Reading
        if acFun:
            if self.maxAccess not in ('readonly', 'readwrite',
                                      'readcreate') or \
                    acFun(name, self.syntax, idx, 'read', acCtx):
                raise error.NoAccessError(idx=idx, name=name)
        return MibTree.readGetNext(self, name, val, idx, acInfo, oName)

    # Two-phase commit implementation

    def writeTest(self, name, val, idx, acInfo):
        acFun, acCtx = acInfo
        if name == self.name:
            raise error.NoAccessError(idx=idx, name=name)
        if acFun:
            if self.maxAccess not in ('readwrite', 'readcreate') or \
                   acFun(name, self.syntax, idx, 'write', acCtx):
                raise error.NotWritableError(idx=idx, name=name)
        MibTree.writeTest(self, name, val, idx, acInfo)

class MibScalarInstance(MibTree):
    """Scalar MIB variable instance. Implements read/write operations."""
    def __init__(self, typeName, instId, syntax):
        MibTree.__init__(self, typeName + instId, syntax)
        self.typeName = typeName
        self.instId = instId
        self.__oldSyntax = None

    #
    # Managed object value access methods
    #

    def getValue(self, name, idx):
        debug.logger & debug.flagIns and debug.logger('getValue: returning %r for %s' % (self.syntax, self.name))
        return self.syntax.clone()

    def setValue(self, value, name, idx):
        try:
            if hasattr(self.syntax, 'setValue'):
                return self.syntax.setValue(value)
            else:
                return self.syntax.clone(value)
        except PyAsn1Error:
            exc_t, exc_v, exc_tb = sys.exc_info()
            debug.logger & debug.flagIns and debug.logger('setValue: %s=%r failed with traceback %s' % (self.name, value, traceback.format_exception(exc_t, exc_v, exc_tb)))
            if isinstance(exc_v, error.TableRowManagement):
                raise exc_v
            else:
                raise error.WrongValueError(idx=idx, name=name, msg=exc_v)

    #
    # Subtree traversal
    #
    # Missing branches are indicated by the NoSuchInstanceError exception.
    #

    def getBranch(self, name, idx):
        try:
            return MibTree.getBranch(self, name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def getNextBranch(self, name, idx=None):
        try:
            return MibTree.getNextBranch(self, name, idx)
        except (error.NoSuchInstanceError, error.NoSuchObjectError):
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def getNode(self, name, idx=None):
        # Recursion terminator
        if name == self.name:
            return self
        raise error.NoSuchInstanceError(idx=idx, name=name)

    def getNextNode(self, name, idx=None):
        raise error.NoSuchInstanceError(idx=idx, name=name)

    # MIB instrumentation methods

    # Read operation

    def readTest(self, name, val, idx, acInfo):
        if name != self.name:
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def readGet(self, name, val, idx, acInfo):
        # Return current variable (name, value)
        if name == self.name:
            debug.logger & debug.flagIns and debug.logger('readGet: %s=%r' % (self.name, self.syntax))
            return self.name, self.getValue(name, idx)
        else:
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def readTestNext(self, name, val, idx, acInfo, oName=None):
        if name != self.name or name <= oName:
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def readGetNext(self, name, val, idx, acInfo, oName=None):
        if name == self.name and name > oName:
            debug.logger & debug.flagIns and debug.logger('readGetNext: %s=%r' % (self.name, self.syntax))
            return self.readGet(name, val, idx, acInfo)
        else:
            raise error.NoSuchInstanceError(idx=idx, name=name)

    # Write operation: two-phase commit

    def writeTest(self, name, val, idx, acInfo):
        # Make sure write's allowed
        if name == self.name:
            try:
                self.__newSyntax = self.setValue(val, name, idx)
            except error.MibOperationError:
                # SMI exceptions may carry additional content
                why = sys.exc_info()[1]
                if 'syntax' in why:
                    self.__newSyntax = why['syntax']
                    raise why
                else:
                    raise error.WrongValueError(idx=idx, name=name, msg=sys.exc_info()[1])
        else:
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def writeCommit(self, name, val, idx, acInfo):
        # Backup original value
        if self.__oldSyntax is None:
            self.__oldSyntax = self.syntax
        # Commit new value
        self.syntax = self.__newSyntax

    def writeCleanup(self, name, val, idx, acInfo):
        self.branchVersionId += 1
        debug.logger & debug.flagIns and debug.logger('writeCleanup: %s=%r' % (name, val))
        # Drop previous value
        self.__newSyntax = self.__oldSyntax = None

    def writeUndo(self, name, val, idx, acInfo):
        # Revive previous value
        self.syntax = self.__oldSyntax
        self.__newSyntax = self.__oldSyntax = None

    # Table column instance specifics

    # Create operation

    def createTest(self, name, val, idx, acInfo):
        if name == self.name:
            try:
                self.__newSyntax = self.setValue(val, name, idx)
            except error.MibOperationError:
                # SMI exceptions may carry additional content
                why = sys.exc_info()[1]
                if 'syntax' in why:
                    self.__newSyntax = why['syntax']
                else:
                    raise error.WrongValueError(idx=idx, name=name, msg=sys.exc_info()[1])
        else:
            raise error.NoSuchInstanceError(idx=idx, name=name)

    def createCommit(self, name, val, idx, acInfo):
        if val is not None:
            self.writeCommit(name, val, idx, acInfo)

    def createCleanup(self, name, val, idx, acInfo):
        self.branchVersionId += 1
        debug.logger & debug.flagIns and debug.logger('createCleanup: %s=%r' % (name, val))
        if val is not None:
            self.writeCleanup(name, val, idx, acInfo)

    def createUndo(self, name, val, idx, acInfo):
        if val is not None:
            self.writeUndo(name, val, idx, acInfo)

    # Destroy operation

    def destroyTest(self, name, val, idx, acInfo):
        if name == self.name:
            try:
                self.__newSyntax = self.setValue(val, name, idx)
            except error.MibOperationError:
                # SMI exceptions may carry additional content
                why = sys.exc_info()[1]
                if 'syntax' in why:
                    self.__newSyntax = why['syntax']
        else:
            raise error.NoSuchInstanceError(idx=idx, name=name)
    def destroyCommit(self, name, val, idx, acInfo):
        pass

    def destroyCleanup(self, name, val, idx, acInfo):
        self.branchVersionId += 1

    def destroyUndo(self, name, val, idx, acInfo):
        pass

# Conceptual table classes

class MibTableColumn(MibScalar):
    """MIB table column. Manages a set of column instance variables"""
    protoInstance = MibScalarInstance
    def __init__(self, name, syntax):
        MibScalar.__init__(self, name, syntax)
        self.__createdInstances = {}
        self.__destroyedInstances = {}
        self.__rowOpWanted = {}

    #
    # Subtree traversal
    #
    # Missing leaves are indicated by the NoSuchInstanceError exception.
    #

    def getBranch(self, name, idx):
        if name in self._vars:
            return self._vars[name]
        raise error.NoSuchInstanceError(name=name, idx=idx)

    def setProtoInstance(self, protoInstance):
        self.protoInstance = protoInstance

    # Column creation (this should probably be converted into some state
    # machine for clarity). Also, it might be a good idea to inidicate
    # defaulted cols creation in a clearer way than just a val == None.

    def createTest(self, name, val, idx, acInfo):
        (acFun, acCtx) = acInfo
        # Make sure creation allowed, create a new column instance but
        # do not replace the old one
        if name == self.name:
            raise error.NoAccessError(idx=idx, name=name)
        if acFun:
            if val is not None and self.maxAccess != 'readcreate' or \
                   acFun(name, self.syntax, idx, 'write', acCtx):
                debug.logger & debug.flagACL and debug.logger('createTest: %s=%r %s at %s' % (name, val, self.maxAccess, self.name))
                raise error.NoCreationError(idx=idx, name=name)
        # Create instances if either it does not yet exist (row creation)
        # or a value is passed (multiple OIDs in SET PDU)
        if val is None and name in self.__createdInstances:
            return
        self.__createdInstances[name] = self.protoInstance(
            self.name, name[len(self.name):], self.syntax.clone()
        )
        self.__createdInstances[name].createTest(name, val, idx, acInfo)

    def createCommit(self, name, val, idx, acInfo):
        # Commit new instance value
        if name in self._vars: # XXX
            if name in self.__createdInstances:
                self._vars[name].createCommit(name, val, idx, acInfo)
            return
        self.__createdInstances[name].createCommit(name, val, idx, acInfo)
        # ...commit new column instance
        self._vars[name], self.__createdInstances[name] = \
                          self.__createdInstances[name], self._vars.get(name)

    def createCleanup(self, name, val, idx, acInfo):
        # Drop previous column instance
        self.branchVersionId += 1
        if name in self.__createdInstances:
            if self.__createdInstances[name] is not None:
                self.__createdInstances[name].createCleanup(name, val, idx,
                                                            acInfo)
            del self.__createdInstances[name]
        elif name in self._vars:
            self._vars[name].createCleanup(name, val, idx, acInfo)

    def createUndo(self, name, val, idx, acInfo):
        # Set back previous column instance, drop the new one
        if name in self.__createdInstances:
            self._vars[name] = self.__createdInstances[name]
            del self.__createdInstances[name]
            # Remove new instance on rollback
            if self._vars[name] is None:
                del self._vars[name]
            else:
                # Catch half-created instances (hackerish)
                try:
                    self._vars[name] == 0
                except PyAsn1Error:
                    del self._vars[name]
                else:
                    self._vars[name].createUndo(name, val, idx, acInfo)

    # Column destruction

    def destroyTest(self, name, val, idx, acInfo):
        (acFun, acCtx) = acInfo
        # Make sure destruction is allowed
        if name == self.name:
            raise error.NoAccessError(idx=idx, name=name)
        if name not in self._vars:
            return
        if acFun:
            if val is not None and self.maxAccess != 'readcreate' or \
                   acFun(name, self.syntax, idx, 'write', acCtx):
                raise error.NoAccessError(idx=idx, name=name)
        self._vars[name].destroyTest(name, val, idx, acInfo)

    def destroyCommit(self, name, val, idx, acInfo):
        # Make a copy of column instance and take it off the tree
        if name in self._vars:
            self._vars[name].destroyCommit(name, val, idx, acInfo)
            self.__destroyedInstances[name] = self._vars[name]
            del self._vars[name]

    def destroyCleanup(self, name, val, idx, acInfo):
        # Drop instance copy
        self.branchVersionId += 1
        if name in self.__destroyedInstances:
            self.__destroyedInstances[name].destroyCleanup(name, val,
                                                           idx, acInfo)
            debug.logger & debug.flagIns and debug.logger('destroyCleanup: %s=%r' % (name, val))
            del self.__destroyedInstances[name]

    def destroyUndo(self, name, val, idx, acInfo):
        # Set back column instance
        if name in self.__destroyedInstances:
            self._vars[name] = self.__destroyedInstances[name]
            self._vars[name].destroyUndo(name, val, idx, acInfo)
            del self.__destroyedInstances[name]

    # Set/modify column

    def writeTest(self, name, val, idx, acInfo):
        # Besides common checks, request row creation on no-instance
        try:
            # First try the instance
            MibScalar.writeTest(self, name, val, idx, acInfo)
        # ...otherwise proceed with creating new column
        except (error.NoSuchInstanceError, error.RowCreationWanted):
            excValue = sys.exc_info()[1]
            if isinstance(excValue, error.RowCreationWanted):
                self.__rowOpWanted[name] = excValue
            else:
                self.__rowOpWanted[name] = error.RowCreationWanted()
            self.createTest(name, val, idx, acInfo)
        except error.RowDestructionWanted:
            self.__rowOpWanted[name] = error.RowDestructionWanted()
            self.destroyTest(name, val, idx, acInfo)
        if name in self.__rowOpWanted:
            debug.logger & debug.flagIns and debug.logger('%s flagged by %s=%r, exception %s' % (self.__rowOpWanted[name], name, val, sys.exc_info()[1]))
            raise self.__rowOpWanted[name]

    def __delegateWrite(self, subAction, name, val, idx, acInfo):
        if name not in self.__rowOpWanted:
            getattr(MibScalar, 'write'+subAction)(self, name, val, idx, acInfo)
            return
        if isinstance(self.__rowOpWanted[name], error.RowCreationWanted):
            getattr(self, 'create'+subAction)(name, val, idx, acInfo)
        if isinstance(self.__rowOpWanted[name], error.RowDestructionWanted):
            getattr(self, 'destroy'+subAction)(name, val, idx, acInfo)

    def writeCommit(self, name, val, idx, acInfo):
        self.__delegateWrite('Commit', name, val, idx, acInfo)
        if name in self.__rowOpWanted:
            raise self.__rowOpWanted[name]

    def writeCleanup(self, name, val, idx, acInfo):
        self.branchVersionId += 1
        self.__delegateWrite('Cleanup', name, val, idx, acInfo)
        if name in self.__rowOpWanted:
            e = self.__rowOpWanted[name]
            del self.__rowOpWanted[name]
            debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%r' % (e, name, val))
            raise e

    def writeUndo(self, name, val, idx, acInfo):
        if name in self.__rowOpWanted:
            self.__rowOpWanted[name] = error.RowDestructionWanted()
        self.__delegateWrite('Undo', name, val, idx, acInfo)
        if name in self.__rowOpWanted:
            e = self.__rowOpWanted[name]
            del self.__rowOpWanted[name]
            debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%r' % (e, name, val))
            raise e

class MibTableRow(MibTree):
    """MIB table row (SMI 'Entry'). Manages a set of table columns.
       Implements row creation/destruction.
    """
    def __init__(self, name):
        MibTree.__init__(self, name)
        self.__idToIdxCache = cache.Cache()
        self.__idxToIdCache = cache.Cache()
        self.indexNames = ()
        self.augmentingRows = {}

    # Table indices resolution. Handle almost all possible rfc1902 types
    # explicitly rather than by means of isSuperTypeOf() method because
    # some subtypes may be implicitly tagged what renders base tag
    # unavailable.

    __intBaseTag = Integer.tagSet.getBaseTag()
    __strBaseTag = OctetString.tagSet.getBaseTag()
    __oidBaseTag = ObjectIdentifier.tagSet.getBaseTag()
    __ipaddrTagSet = IpAddress.tagSet
    __bitsBaseTag = Bits.tagSet.getBaseTag()

    def setFromName(self, obj, value, impliedFlag=None):
        if not value:
            raise error.SmiError('Short OID for index %r' % (obj,))
        value = tuple(value)  # possible ObjectIdentifiers
        baseTag = obj.getTagSet().getBaseTag()
        if baseTag == self.__intBaseTag:
            return obj.clone(value[0]), value[1:]
        elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()):
            return obj.clone('.'.join([str(x) for x in value[:4]])), value[4:]
        elif baseTag == self.__strBaseTag:
            # rfc1902, 7.7
            if impliedFlag:
                return obj.clone(value), ()
            elif obj.isFixedLength():
                l = obj.getFixedLength()
                return obj.clone(value[:l]), value[l:]
            else:
                return obj.clone(value[1:value[0]+1]), value[value[0]+1:]
        elif baseTag == self.__oidBaseTag:
            if impliedFlag:
                return obj.clone(value), ()
            else:
                return obj.clone(value[1:value[0]+1]), value[value[0]+1:]
        # rfc2578, 7.1
        elif baseTag == self.__bitsBaseTag:
            return obj.clone(value[1:value[0]+1]), value[value[0]+1:]
        else:
            raise error.SmiError('Unknown value type for index %r' % (obj,))

    def getAsName(self, obj, impliedFlag=None):
        baseTag = obj.getTagSet().getBaseTag()
        if baseTag == self.__intBaseTag:
            return (int(obj),)
        elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()):
            return obj.asNumbers()
        elif baseTag == self.__strBaseTag:
            if impliedFlag or obj.isFixedLength():
                initial = ()
            else:
                initial = (len(obj),)
            return initial + obj.asNumbers()
        elif baseTag == self.__oidBaseTag:
            if impliedFlag:
                return tuple(obj)
            else:
                return (len(self.name),) + tuple(obj)
        # rfc2578, 7.1
        elif baseTag == self.__bitsBaseTag:
            return (len(obj),) +  obj.asNumbers()
        else:
            raise error.SmiError('Unknown value type for index %r' % (obj,))

    # Fate sharing mechanics

    def announceManagementEvent(self, action, name, val, idx, acInfo):
        # Convert OID suffix into index vals
        instId = name[len(self.name)+1:]
        baseIndices = []
        for impliedFlag, modName, symName in self.indexNames:
            mibObj, = mibBuilder.importSymbols(modName, symName)
            syntax, instId = self.setFromName(mibObj.syntax, instId,
                                              impliedFlag)

            if self.name == mibObj.name[:-1]:
                baseIndices.append((mibObj.name, syntax))

        if instId:
            raise error.SmiError('Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId))

        if not baseIndices:
            return

        for modName, mibSym in self.augmentingRows.keys():
            mibObj, = mibBuilder.importSymbols(modName, mibSym)
            debug.logger & debug.flagIns and debug.logger('announceManagementEvent %s to %s' % (action, mibObj))
            mibObj.receiveManagementEvent(
                action, baseIndices, val, idx, acInfo
            )

    def receiveManagementEvent(self, action, baseIndices, val, idx, acInfo):
        # The default implementation supports one-to-one rows dependency
        newSuffix = ()
        # Resolve indices intersection
        for impliedFlag, modName, symName in self.indexNames:
            mibObj, = mibBuilder.importSymbols(modName, symName)
            for name, syntax in baseIndices:
                if name == mibObj.name:
                    newSuffix = newSuffix + self.getAsName(syntax, impliedFlag)

        if newSuffix:
            debug.logger & debug.flagIns and debug.logger('receiveManagementEvent %s for suffix %s' % (action, newSuffix))
            self.__manageColumns(action, (), newSuffix, val, idx, acInfo)

    def registerAugmentions(self, *names):
        for modName, symName in names:
            if (modName, symName) in self.augmentingRows:
                raise error.SmiError(
                    'Row %s already augmented by %s::%s' % \
                    (self.name, modName, symName)
                )
            self.augmentingRows[(modName, symName)] = 1
        return self

    def setIndexNames(self, *names):
        for name in names:
            self.indexNames = self.indexNames + (name,)
        return self

    def getIndexNames(self):
        return self.indexNames

    def __manageColumns(self, action, excludeName, nameSuffix,
                        val, idx, acInfo):
        # Build a map of index names and values for automatic initialization
        indexVals = {}
        instId = nameSuffix
        for impliedFlag, modName, symName in self.indexNames:
            mibObj, = mibBuilder.importSymbols(modName, symName)
            syntax, instId = self.setFromName(mibObj.syntax, instId,
                                              impliedFlag)
            indexVals[mibObj.name] = syntax

        for name, var in self._vars.items():
            if name == excludeName:
                continue

            if name in indexVals:
                getattr(var, action)(name + nameSuffix, indexVals[name], idx,
                                     (None, None))
            else:
                getattr(var, action)(name + nameSuffix, val, idx, acInfo)

            debug.logger & debug.flagIns and debug.logger('__manageColumns: action %s name %s suffix %s %svalue %r' % (action, name, nameSuffix, name in indexVals and "index " or "", indexVals.get(name, val)))

    def __delegate(self, subAction, name, val, idx, acInfo):
        # Relay operation request to column, expect row operation request.
        rowIsActive = False
        try:
            getattr(self.getBranch(name, idx), 'write'+subAction)(
                name, val, idx, acInfo
            )

        except error.RowCreationWanted:
            self.__manageColumns(
                'create'+subAction, name[:len(self.name)+1],
                name[len(self.name)+1:], None, idx, acInfo
            )

            self.announceManagementEvent(
                'create'+subAction, name, None, idx, acInfo
            )

            # watch for RowStatus == 'stActive'
            rowIsActive = sys.exc_info()[1].get('syntax', 0) == 1

        except error.RowDestructionWanted:
            self.__manageColumns(
                'destroy'+subAction, name[:len(self.name)+1],
                name[len(self.name)+1:], None, idx, acInfo
            )

            self.announceManagementEvent(
                'destroy'+subAction, name, None, idx, acInfo
            )

        return rowIsActive

    def writeTest(self, name, val, idx, acInfo):
        self.__delegate('Test', name, val, idx, acInfo)

    def writeCommit(self, name, val, idx, acInfo):
        rowIsActive = self.__delegate('Commit', name, val, idx, acInfo)
        if rowIsActive:
            for mibNode in self._vars.values():
                colNode = mibNode.getNode(mibNode.name + name[len(self.name)+1:])
                if not colNode.syntax.hasValue():
                    raise error.InconsistentValueError(msg='Row consistency check failed for %r' % colNode)

    def writeCleanup(self, name, val, idx, acInfo):
        self.branchVersionId += 1
        self.__delegate('Cleanup', name, val, idx, acInfo)

    def writeUndo(self, name, val, idx, acInfo):
        self.__delegate('Undo', name, val, idx, acInfo)

    # Table row management

    # Table row access by instance name

    def getInstName(self, colId, instId):
        return self.name + (colId,) + instId

    # Table index management

    def getIndicesFromInstId(self, instId):
        """Return index values for instance identification"""
        if instId in self.__idToIdxCache:
            return self.__idToIdxCache[instId]
        indices = []
        for impliedFlag, modName, symName in self.indexNames:
            mibObj, = mibBuilder.importSymbols(modName, symName)
            syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag)
            indices.append(syntax) # to avoid cyclic refs
        if instId:
            raise error.SmiError(
                'Excessive instance identifier sub-OIDs left at %s: %s' %
                (self, instId)
            )
        indices = tuple(indices)
        self.__idToIdxCache[instId] = indices
        return indices

    def getInstIdFromIndices(self, *indices):
        """Return column instance identification from indices"""
        if indices in self.__idxToIdCache:
            return self.__idxToIdCache[indices]
        idx = 0
        idxLen = len(indices)
        instId = ()
        for impliedFlag, modName, symName in self.indexNames:
            mibObj, = mibBuilder.importSymbols(modName, symName)
            if idx < idxLen:
                instId = instId + self.getAsName(
                    mibObj.syntax.clone(indices[idx]), impliedFlag
                )
            else:
                break
            idx = idx + 1
        self.__idxToIdCache[indices] = instId
        return instId

    # Table access by index

    def getInstNameByIndex(self, colId, *indices):
        """Build column instance name from components"""
        return self.name + (colId,) + self.getInstIdFromIndices(*indices)

    def getInstNamesByIndex(self, *indices):
        """Build column instance names from indices"""
        instNames = []
        for columnName in self._vars.keys():
            instNames.append(
                self.getInstNameByIndex(*(columnName[-1],) + indices)
            )

        return tuple(instNames)

class MibTable(MibTree):
    """MIB table. Manages a set of TableRow's"""
    def __init__(self, name):
        MibTree.__init__(self, name)

zeroDotZero = ObjectIdentity((0, 0))

# OID tree
itu_t = MibTree((0,)).setLabel('itu-t')
iso = MibTree((1,))
joint_iso_itu_t = MibTree((2,)).setLabel('joint-iso-itu-t')
org = MibIdentifier(iso.name + (3,))
dod = MibIdentifier(org.name + (6,))
internet = MibIdentifier(dod.name + (1,))
directory = MibIdentifier(internet.name + (1,))
mgmt = MibIdentifier(internet.name + (2,))
mib_2 = MibIdentifier(mgmt.name + (1,)).setLabel('mib-2')
transmission = MibIdentifier(mib_2.name + (10,))
experimental = MibIdentifier(internet.name + (3,))
private = MibIdentifier(internet.name + (4,))
enterprises = MibIdentifier(private.name + (1,))
security = MibIdentifier(internet.name + (5,))
snmpV2 = MibIdentifier(internet.name + (6,))

snmpDomains = MibIdentifier(snmpV2.name + (1,))
snmpProxys = MibIdentifier(snmpV2.name +(2,))
snmpModules = MibIdentifier(snmpV2.name +(3,))

mibBuilder.exportSymbols(
    'SNMPv2-SMI', MibNode=MibNode,
    Integer32=Integer32, Bits=Bits, IpAddress=IpAddress,
    Counter32=Counter32, Gauge32=Gauge32, Unsigned32=Unsigned32,
    TimeTicks=TimeTicks, Opaque=Opaque, Counter64=Counter64,
    ExtUTCTime=ExtUTCTime,
    ModuleIdentity=ModuleIdentity, ObjectIdentity=ObjectIdentity,
    NotificationType=NotificationType, MibScalar=MibScalar,
    MibScalarInstance=MibScalarInstance,
    MibIdentifier=MibIdentifier, MibTree=MibTree,
    MibTableColumn=MibTableColumn, MibTableRow=MibTableRow,
    MibTable=MibTable, zeroDotZero=zeroDotZero,
    itu_t=itu_t, iso=iso, joint_iso_itu_t=joint_iso_itu_t, org=org, dod=dod,
    internet=internet, directory=directory, mgmt=mgmt, mib_2=mib_2,
    transmission=transmission, experimental=experimental, private=private,
    enterprises=enterprises, security=security, snmpV2=snmpV2,
    snmpDomains=snmpDomains, snmpProxys=snmpProxys, snmpModules=snmpModules
)

# XXX
# getAsName/setFromName goes out of MibRow?
# revisit getNextNode() -- needs optimization


text:
using System.Buffers;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.SqlServer.Server;

namespace System.Data.SqlClient
{
    internal enum CallbackType
    {
        Read = 0,
        Write = 1
    }

    internal enum EncryptionOptions
    {
        OFF,
        ON,
        NOT_SUP,
        REQ,
        LOGIN
    }

    internal enum PreLoginHandshakeStatus
    {
        Successful,
        InstanceFailure
    }

    internal enum PreLoginOptions
    {
        VERSION,
        ENCRYPT,
        INSTANCE,
        THREADID,
        MARS,
        TRACEID,
        FEDAUTHREQUIRED,
        NUMOPT,
        LASTOPT = 255
    }

    internal enum RunBehavior
    {
        UntilDone = 1, // 0001 binary
        ReturnImmediately = 2, // 0010 binary
        Clean = 5, // 0101 binary - Clean AND UntilDone
        Attention = 13  // 1101 binary - Clean AND UntilDone AND Attention
    }

    internal enum TdsParserState
    {
        Closed,
        OpenNotLoggedIn,
        OpenLoggedIn,
        Broken,
    }

    /// <summary>
    /// Struct encapsulating the data to be sent to the server as part of Federated Authentication Feature Extension.
    /// </summary>
    internal struct FederatedAuthenticationFeatureExtensionData
    {
        internal TdsEnums.FedAuthLibrary libraryType;
        internal bool fedAuthRequiredPreLoginResponse;
        internal byte[] accessToken;
    }

    internal sealed class SqlCollation
    {
        // First 20 bits of info field represent the lcid, bits 21-25 are compare options
        private const uint IgnoreCase = 1 << 20; // bit 21 - IgnoreCase
        private const uint IgnoreNonSpace = 1 << 21; // bit 22 - IgnoreNonSpace / IgnoreAccent
        private const uint IgnoreWidth = 1 << 22; // bit 23 - IgnoreWidth
        private const uint IgnoreKanaType = 1 << 23; // bit 24 - IgnoreKanaType
        private const uint BinarySort = 1 << 24; // bit 25 - BinarySort

        internal const uint MaskLcid = 0xfffff;
        private const int LcidVersionBitOffset = 28;
        private const uint MaskLcidVersion = unchecked((uint)(0xf << LcidVersionBitOffset));
        private const uint MaskCompareOpt = IgnoreCase | IgnoreNonSpace | IgnoreWidth | IgnoreKanaType | BinarySort;

        internal uint info;
        internal byte sortId;

        private static int FirstSupportedCollationVersion(int lcid) =>
            // NOTE: switch-case works ~3 times faster in this case than search with Dictionary
            lcid switch
            {
                1044 => 2, // Norwegian_100_BIN
                1047 => 2, // Romansh_100_BIN
                1056 => 2, // Urdu_100_BIN
                1065 => 2, // Persian_100_BIN
                1068 => 2, // Azeri_Latin_100_BIN
                1070 => 2, // Upper_Sorbian_100_BIN
                1071 => 1, // Macedonian_FYROM_90_BIN
                1081 => 1, // Indic_General_90_BIN
                1082 => 2, // Maltese_100_BIN
                1083 => 2, // Sami_Norway_100_BIN
                1087 => 1, // Kazakh_90_BIN
                1090 => 2, // Turkmen_100_BIN
                1091 => 1, // Uzbek_Latin_90_BIN
                1092 => 1, // Tatar_90_BIN
                1093 => 2, // Bengali_100_BIN
                1101 => 2, // Assamese_100_BIN
                1105 => 2, // Tibetan_100_BIN
                1106 => 2, // Welsh_100_BIN
                1107 => 2, // Khmer_100_BIN
                1108 => 2, // Lao_100_BIN
                1114 => 1, // Syriac_90_BIN
                1121 => 2, // Nepali_100_BIN
                1122 => 2, // Frisian_100_BIN
                1123 => 2, // Pashto_100_BIN
                1125 => 1, // Divehi_90_BIN
                1133 => 2, // Bashkir_100_BIN
                1146 => 2, // Mapudungan_100_BIN
                1148 => 2, // Mohawk_100_BIN
                1150 => 2, // Breton_100_BIN
                1152 => 2, // Uighur_100_BIN
                1153 => 2, // Maori_100_BIN
                1155 => 2, // Corsican_100_BIN
                1157 => 2, // Yakut_100_BIN
                1164 => 2, // Dari_100_BIN
                2074 => 2, // Serbian_Latin_100_BIN
                2092 => 2, // Azeri_Cyrillic_100_BIN
                2107 => 2, // Sami_Sweden_Finland_100_BIN
                2143 => 2, // Tamazight_100_BIN
                3076 => 1, // Chinese_Hong_Kong_Stroke_90_BIN
                3098 => 2, // Serbian_Cyrillic_100_BIN
                5124 => 2, // Chinese_Traditional_Pinyin_100_BIN
                5146 => 2, // Bosnian_Latin_100_BIN
                8218 => 2, // Bosnian_Cyrillic_100_BIN

                _ => 0,   // other LCIDs have collation with version 0
            };

        internal int LCID
        {
            // First 20 bits of info field represent the lcid
            get
            {
                return unchecked((int)(info & MaskLcid));
            }
            set
            {
                int lcid = value & (int)MaskLcid;
                Debug.Assert(lcid == value, "invalid set_LCID value");

                // Some new Katmai LCIDs do not have collation with version = 0
                // since user has no way to specify collation version, we set the first (minimal) supported version for these collations
                int versionBits = FirstSupportedCollationVersion(lcid) << LcidVersionBitOffset;
                Debug.Assert((versionBits & MaskLcidVersion) == versionBits, "invalid version returned by FirstSupportedCollationVersion");

                // combine the current compare options with the new locale ID and its first supported version
                info = (info & MaskCompareOpt) | unchecked((uint)lcid) | unchecked((uint)versionBits);
            }
        }

        internal SqlCompareOptions SqlCompareOptions
        {
            get
            {
                SqlCompareOptions options = SqlCompareOptions.None;
                if (0 != (info & IgnoreCase))
                    options |= SqlCompareOptions.IgnoreCase;
                if (0 != (info & IgnoreNonSpace))
                    options |= SqlCompareOptions.IgnoreNonSpace;
                if (0 != (info & IgnoreWidth))
                    options |= SqlCompareOptions.IgnoreWidth;
                if (0 != (info & IgnoreKanaType))
                    options |= SqlCompareOptions.IgnoreKanaType;
                if (0 != (info & BinarySort))
                    options |= SqlCompareOptions.BinarySort;
                return options;
            }
            set
            {
                Debug.Assert((value & SqlTypeWorkarounds.SqlStringValidSqlCompareOptionMask) == value, "invalid set_SqlCompareOptions value");
                uint tmp = 0;
                if (0 != (value & SqlCompareOptions.IgnoreCase))
                    tmp |= IgnoreCase;
                if (0 != (value & SqlCompareOptions.IgnoreNonSpace))
                    tmp |= IgnoreNonSpace;
                if (0 != (value & SqlCompareOptions.IgnoreWidth))
                    tmp |= IgnoreWidth;
                if (0 != (value & SqlCompareOptions.IgnoreKanaType))
                    tmp |= IgnoreKanaType;
                if (0 != (value & SqlCompareOptions.BinarySort))
                    tmp |= BinarySort;
                info = (info & MaskLcid) | tmp;
            }
        }

        internal static bool AreSame(SqlCollation a, SqlCollation b)
        {
            if (a == null || b == null)
            {
                return a == b;
            }
            else
            {
                return a.info == b.info && a.sortId == b.sortId;
            }
        }
    }

    internal class RoutingInfo
    {
        internal byte Protocol { get; private set; }
        internal ushort Port { get; private set; }
        internal string ServerName { get; private set; }

        internal RoutingInfo(byte protocol, ushort port, string servername)
        {
            Protocol = protocol;
            Port = port;
            ServerName = servername;
        }
    }

    internal sealed class SqlEnvChange
    {
        internal byte type;
        internal byte oldLength;
        internal int newLength; // 7206 TDS changes makes this length an int
        internal int length;
        internal string newValue;
        internal string oldValue;
        /// <summary>
        /// contains binary data, before using this field check newBinRented to see if you can take the field array or whether you should allocate and copy
        /// </summary>
        internal byte[] newBinValue;
        /// <summary>
        /// contains binary data, before using this field check newBinRented to see if you can take the field array or whether you should allocate and copy
        /// </summary>
        internal byte[] oldBinValue;
        internal long newLongValue;
        internal long oldLongValue;
        internal SqlCollation newCollation;
        internal SqlCollation oldCollation;
        internal RoutingInfo newRoutingInfo;
        internal bool newBinRented;
        internal bool oldBinRented;

        internal SqlEnvChange Next;

        internal void Clear()
        {
            type = 0;
            oldLength = 0;
            newLength = 0;
            length = 0;
            newValue = null;
            oldValue = null;
            if (newBinValue != null)
            {
                Array.Clear(newBinValue, 0, newBinValue.Length);
                if (newBinRented)
                {
                    ArrayPool<byte>.Shared.Return(newBinValue);
                }

                newBinValue = null;
            }
            if (oldBinValue != null)
            {
                Array.Clear(oldBinValue, 0, oldBinValue.Length);
                if (oldBinRented)
                {
                    ArrayPool<byte>.Shared.Return(oldBinValue);
                }
                oldBinValue = null;
            }
            newBinRented = false;
            oldBinRented = false;
            newLongValue = 0;
            oldLongValue = 0;
            newCollation = null;
            oldCollation = null;
            newRoutingInfo = null;
            Next = null;
        }
    }

    internal sealed class SqlLogin
    {
        internal int timeout;                                                       // login timeout
        internal bool userInstance = false;                                   // user instance
        internal string hostName = "";                                      // client machine name
        internal string userName = "";                                      // user id
        internal string password = "";                                      // password
        internal string applicationName = "";                                      // application name
        internal string serverName = "";                                      // server name
        internal string language = "";                                      // initial language
        internal string database = "";                                      // initial database
        internal string attachDBFilename = "";                                      // DB filename to be attached
        internal bool useReplication = false;                                   // user login for replication
        internal string newPassword = "";                                   // new password for reset password
        internal bool useSSPI = false;                                   // use integrated security
        internal int packetSize = SqlConnectionString.DEFAULT.Packet_Size; // packet size
        internal bool readOnlyIntent = false;                                   // read-only intent
        internal SqlCredential credential;                                      // user id and password in SecureString
        internal SecureString newSecurePassword;
    }

    internal sealed class SqlLoginAck
    {
        internal byte majorVersion;
        internal byte minorVersion;
        internal short buildNum;
        internal uint tdsVersion;
    }

    internal sealed class _SqlMetaData : SqlMetaDataPriv
    {
        [Flags]
        private enum _SqlMetadataFlags : int
        {
            None = 0,

            Updatable = 1 << 0,
            UpdateableUnknown = 1 << 1,
            IsDifferentName = 1 << 2,
            IsKey = 1 << 3,
            IsHidden = 1 << 4,
            IsExpression = 1 << 5,
            IsIdentity = 1 << 6,
            IsColumnSet = 1 << 7,

            IsUpdatableMask = (Updatable | UpdateableUnknown) // two bit field (0 is read only, 1 is updatable, 2 is updatability unknown)
        }

        internal string column;
        internal string baseColumn;
        internal MultiPartTableName multiPartTableName;
        internal readonly int ordinal;
        internal byte tableNum;
        internal byte op;        // for altrow-columns only
        internal ushort operand; // for altrow-columns only
        private _SqlMetadataFlags flags;

        internal _SqlMetaData(int ordinal) : base()
        {
            this.ordinal = ordinal;
        }

        internal string serverName
        {
            get
            {
                return multiPartTableName.ServerName;
            }
        }
        internal string catalogName
        {
            get
            {
                return multiPartTableName.CatalogName;
            }
        }
        internal string schemaName
        {
            get
            {
                return multiPartTableName.SchemaName;
            }
        }
        internal string tableName
        {
            get
            {
                return multiPartTableName.TableName;
            }
        }

        public byte Updatability
        {
            get => (byte)(flags & _SqlMetadataFlags.IsUpdatableMask);
            set => flags = (_SqlMetadataFlags)((value & 0x3) | ((int)flags & ~0x03));
        }

        public bool IsReadOnly
        {
            get => (flags & _SqlMetadataFlags.IsUpdatableMask) == 0;
        }

        public bool IsDifferentName
        {
            get => flags.HasFlag(_SqlMetadataFlags.IsDifferentName);
            set => Set(_SqlMetadataFlags.IsDifferentName, value);
        }

        public bool IsKey
        {
            get => flags.HasFlag(_SqlMetadataFlags.IsKey);
            set => Set(_SqlMetadataFlags.IsKey, value);
        }

        public bool IsHidden
        {
            get => flags.HasFlag(_SqlMetadataFlags.IsHidden);
            set => Set(_SqlMetadataFlags.IsHidden, value);
        }

        public bool IsExpression
        {
            get => flags.HasFlag(_SqlMetadataFlags.IsExpression);
            set => Set(_SqlMetadataFlags.IsExpression, value);
        }

        public bool IsIdentity
        {
            get => flags.HasFlag(_SqlMetadataFlags.IsIdentity);
            set => Set(_SqlMetadataFlags.IsIdentity, value);
        }

        public bool IsColumnSet
        {
            get => flags.HasFlag(_SqlMetadataFlags.IsColumnSet);
            set => Set(_SqlMetadataFlags.IsColumnSet, value);
        }

        private void Set(_SqlMetadataFlags flag, bool value)
        {
            flags = value ? flags | flag : flags & ~flag;
        }

        internal bool IsNewKatmaiDateTimeType
        {
            get
            {
                return SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type;
            }
        }

        internal bool IsLargeUdt
        {
            get
            {
                return type == SqlDbType.Udt && length == int.MaxValue;
            }
        }

        public object Clone()
        {
            _SqlMetaData result = new _SqlMetaData(ordinal);
            result.CopyFrom(this);
            result.column = column;
            result.baseColumn = baseColumn;
            result.multiPartTableName = multiPartTableName;
            result.tableNum = tableNum;
            result.flags = flags;
            result.op = op;
            result.operand = operand;
            return result;
        }
    }

    internal sealed class _SqlMetaDataSet
    {
        internal ushort id;             // for altrow-columns only
        internal int[] indexMap;
        internal int visibleColumns;
        internal DataTable schemaTable;
        private readonly _SqlMetaData[] _metaDataArray;
        internal ReadOnlyCollection<DbColumn> dbColumnSchema;

        internal _SqlMetaDataSet(int count)
        {
            _metaDataArray = new _SqlMetaData[count];
            for (int i = 0; i < _metaDataArray.Length; ++i)
            {
                _metaDataArray[i] = new _SqlMetaData(i);
            }
        }

        private _SqlMetaDataSet(_SqlMetaDataSet original)
        {
            this.id = original.id;
            // although indexMap is not immutable, in practice it is initialized once and then passed around
            this.indexMap = original.indexMap;
            this.visibleColumns = original.visibleColumns;
            this.dbColumnSchema = original.dbColumnSchema;
            if (original._metaDataArray == null)
            {
                _metaDataArray = null;
            }
            else
            {
                _metaDataArray = new _SqlMetaData[original._metaDataArray.Length];
                for (int idx = 0; idx < _metaDataArray.Length; idx++)
                {
                    _metaDataArray[idx] = (_SqlMetaData)original._metaDataArray[idx].Clone();
                }
            }
        }

        internal int Length
        {
            get
            {
                return _metaDataArray.Length;
            }
        }

        internal _SqlMetaData this[int index]
        {
            get
            {
                return _metaDataArray[index];
            }
            set
            {
                Debug.Assert(null == value, "used only by SqlBulkCopy");
                _metaDataArray[index] = value;
            }
        }

        public object Clone()
        {
            return new _SqlMetaDataSet(this);
        }
    }

    internal sealed class _SqlMetaDataSetCollection
    {
        private readonly List<_SqlMetaDataSet> _altMetaDataSetArray;
        internal _SqlMetaDataSet metaDataSet;

        internal _SqlMetaDataSetCollection()
        {
            _altMetaDataSetArray = new List<_SqlMetaDataSet>();
        }

        internal void SetAltMetaData(_SqlMetaDataSet altMetaDataSet)
        {
            // If altmetadata with same id is found, override it rather than adding a new one
            int newId = altMetaDataSet.id;
            for (int i = 0; i < _altMetaDataSetArray.Count; i++)
            {
                if (_altMetaDataSetArray[i].id == newId)
                {
                    // override the existing metadata with the same id
                    _altMetaDataSetArray[i] = altMetaDataSet;
                    return;
                }
            }

            // if we did not find metadata to override, add as new
            _altMetaDataSetArray.Add(altMetaDataSet);
        }

        internal _SqlMetaDataSet GetAltMetaData(int id)
        {
            foreach (_SqlMetaDataSet altMetaDataSet in _altMetaDataSetArray)
            {
                if (altMetaDataSet.id == id)
                {
                    return altMetaDataSet;
                }
            }
            Debug.Fail("Can't match up altMetaDataSet with given id");
            return null;
        }

        public object Clone()
        {
            _SqlMetaDataSetCollection result = new _SqlMetaDataSetCollection();
            result.metaDataSet = metaDataSet == null ? null : (_SqlMetaDataSet)metaDataSet.Clone();
            foreach (_SqlMetaDataSet set in _altMetaDataSetArray)
            {
                result._altMetaDataSetArray.Add((_SqlMetaDataSet)set.Clone());
            }
            return result;
        }
    }

    internal class SqlMetaDataPriv
    {
        [Flags]
        private enum SqlMetaDataPrivFlags : byte
        {
            None = 0,
            IsNullable = 1 << 1,
            IsMultiValued = 1 << 2
        }

        internal SqlDbType type;    // SqlDbType enum value
        internal byte tdsType; // underlying tds type
        internal byte precision = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
        internal byte scale = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
        private SqlMetaDataPrivFlags flags;
        internal int length;
        internal SqlCollation collation;
        internal int codePage;
        internal Encoding encoding;
        internal MetaType metaType; // cached metaType
        public SqlMetaDataUdt udt;
        public SqlMetaDataXmlSchemaCollection xmlSchemaCollection;

        internal SqlMetaDataPriv()
        {
        }

        public bool IsNullable
        {
            get => flags.HasFlag(SqlMetaDataPrivFlags.IsNullable);
            set => Set(SqlMetaDataPrivFlags.IsNullable, value);
        }

        public bool IsMultiValued
        {
            get => flags.HasFlag(SqlMetaDataPrivFlags.IsMultiValued);
            set => Set(SqlMetaDataPrivFlags.IsMultiValued, value);
        }

        private void Set(SqlMetaDataPrivFlags flag, bool value)
        {
            flags = value ? flags | flag : flags & ~flag;
        }

        internal virtual void CopyFrom(SqlMetaDataPriv original)
        {
            this.type = original.type;
            this.tdsType = original.tdsType;
            this.precision = original.precision;
            this.scale = original.scale;
            this.length = original.length;
            this.collation = original.collation;
            this.codePage = original.codePage;
            this.encoding = original.encoding;
            this.metaType = original.metaType;
            this.flags = original.flags;

            if (original.udt != null)
            {
                udt = new SqlMetaDataUdt();
                udt.CopyFrom(original.udt);
            }

            if (original.xmlSchemaCollection != null)
            {
                xmlSchemaCollection = new SqlMetaDataXmlSchemaCollection();
                xmlSchemaCollection.CopyFrom(original.xmlSchemaCollection);
            }
        }
    }

    internal sealed class SqlMetaDataXmlSchemaCollection
    {
        internal string Database;
        internal string OwningSchema;
        internal string Name;

        public void CopyFrom(SqlMetaDataXmlSchemaCollection original)
        {
            if (original != null)
            {
                Database = original.Database;
                OwningSchema = original.OwningSchema;
                Name = original.Name;
            }
        }
    }

    internal sealed class SqlMetaDataUdt
    {
        internal Type Type;
        internal string DatabaseName;
        internal string SchemaName;
        internal string TypeName;
        internal string AssemblyQualifiedName;

        public void CopyFrom(SqlMetaDataUdt original)
        {
            if (original != null)
            {
                Type = original.Type;
                DatabaseName = original.DatabaseName;
                SchemaName = original.SchemaName;
                TypeName = original.TypeName;
                AssemblyQualifiedName = original.AssemblyQualifiedName;
            }
        }
    }

    internal sealed class _SqlRPC
    {
        internal string rpcName;
        internal ushort ProcID;       // Used instead of name
        internal ushort options;

        internal SqlParameter[] systemParams;
        internal byte[] systemParamOptions;
        internal int systemParamCount;

        internal SqlParameterCollection userParams;
        internal long[] userParamMap;
        internal int userParamCount;

        internal int? recordsAffected;
        internal int cumulativeRecordsAffected;

        internal int errorsIndexStart;
        internal int errorsIndexEnd;
        internal SqlErrorCollection errors;

        internal int warningsIndexStart;
        internal int warningsIndexEnd;
        internal SqlErrorCollection warnings;

        internal SqlParameter GetParameterByIndex(int index, out byte options)
        {
            options = 0;
            SqlParameter retval = null;
            if (index < systemParamCount)
            {
                retval = systemParams[index];
                options = systemParamOptions[index];
            }
            else
            {
                long data = userParamMap[index - systemParamCount];
                int paramIndex = (int)(data & int.MaxValue);
                options = (byte)((data >> 32) & 0xFF);
                retval = userParams[paramIndex];
            }
            return retval;
        }
    }

    internal sealed class SqlReturnValue : SqlMetaDataPriv
    {
        internal string parameter;
        internal readonly SqlBuffer value;

        internal SqlReturnValue() : base()
        {
            value = new SqlBuffer();
        }
    }

    internal struct MultiPartTableName
    {
        private string _multipartName;
        private string _serverName;
        private string _catalogName;
        private string _schemaName;
        private string _tableName;

        internal MultiPartTableName(string[] parts)
        {
            _multipartName = null;
            _serverName = parts[0];
            _catalogName = parts[1];
            _schemaName = parts[2];
            _tableName = parts[3];
        }

        internal MultiPartTableName(string multipartName)
        {
            _multipartName = multipartName;
            _serverName = null;
            _catalogName = null;
            _schemaName = null;
            _tableName = null;
        }

        internal string ServerName
        {
            get
            {
                ParseMultipartName();
                return _serverName;
            }
            set { _serverName = value; }
        }
        internal string CatalogName
        {
            get
            {
                ParseMultipartName();
                return _catalogName;
            }
            set { _catalogName = value; }
        }
        internal string SchemaName
        {
            get
            {
                ParseMultipartName();
                return _schemaName;
            }
            set { _schemaName = value; }
        }
        internal string TableName
        {
            get
            {
                ParseMultipartName();
                return _tableName;
            }
            set { _tableName = value; }
        }

        private void ParseMultipartName()
        {
            if (null != _multipartName)
            {
                string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", SR.SQL_TDSParserTableName, false);
                _serverName = parts[0];
                _catalogName = parts[1];
                _schemaName = parts[2];
                _tableName = parts[3];
                _multipartName = null;
            }
        }

        internal static readonly MultiPartTableName Null = new MultiPartTableName(new string[] { null, null, null, null });
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

click to show more practice.
More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

*/

import java.util.*;

public class MinimumSizeSubarraySum {
	public static int minSubArrayLen(int s, int[] nums) {
        if(nums.length <= 0 || s<=0) return 0;
        int L = nums.length;
        int sum = 0;
        int right = 0, left = 0;
        int res = Integer.MAX_VALUE;
        while(right < L){
            sum += nums[right++];
            while(sum >=s){   // condition: sum >= s not =
                res = Math.min(res, right-left);
                sum -= nums[left++];
            }
        }
        return res == Integer.MAX_VALUE? 0: res;
    }

	public static void main(String[] args) {
		int[] nums1 = new int[] {2,3, 1, 2, 4, 3};
        System.out.println("Array: ");
		for(int i=0; i < nums1.length; i++){
			System.out.print(nums1[i] + " ");
		}
        System.out.println();
		System.out.println("Enter target: ");
		Scanner reader = new Scanner(System.in);
		int s = reader.nextInt();
		int res = minSubArrayLen(s, nums1);
        System.out.println("results: " + res);
		return;
	}
}


text:
import base64
import uuid

from google.appengine.ext import db

from mcfw.rpc import returns, arguments
from rogerthat.bizz.channel import firebase
from rogerthat.rpc import users
from rogerthat.settings import get_server_settings

@returns(tuple)
@arguments()
def create_channel_token():
    user = users.get_current_user()
    session = users.get_current_session()
    user_channel_id = get_uid(user.email())
    session_channel_id = get_uid(session.key())

    token = firebase.create_custom_token(user_channel_id, {'sid': session_channel_id})
    return token, user_channel_id, session_channel_id

@returns(str)
@arguments(key=(unicode, db.Key))
def get_uid(key):
    if not isinstance(key, unicode):
        key = unicode(key)

    base64_key = base64.b64encode(key)
    uid = uuid.uuid5(uuid.NAMESPACE_URL, base64_key)
    return str(uid)

def append_firebase_params(params):
    """A utility function to append firebase required parameters to a dict.

    Args:
        params (dict)
    """
    from rogerthat.models import ServiceIdentity
    session = users.get_current_session()
    if session:
        server_settings = get_server_settings()
        token, user_channel_id, session_channel_id = create_channel_token()

        params['firebase_api_key'] = server_settings.firebaseApiKey
        params['firebase_auth_domain'] = server_settings.firebaseAuthDomain
        params['firebase_database_url'] = server_settings.firebaseDatabaseUrl
        params['firebase_token'] = token
        params['user_channel_id'] = user_channel_id
        params['session_channel_id'] = session_channel_id
        params['service_identity'] = session.service_identity or ServiceIdentity.DEFAULT

def send_message(user_or_session_id, data):
    channel_id = get_uid(user_or_session_id)
    firebase.send_firebase_message(channel_id, data)


text:
package br.com.juliocnsouza.ocpjp._2resource_bundle;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * ResourceBundleTest.java -> Job:
 * <p>
 * @since 03/02/2015
 * @version 1.0
 * @author Julio Cesar Nunes de Souza (julio.souza@mobilitasistemas.com.br)
 */
public class JavaResourceBundleTest {

    public static void main( String[] args ) {
        Locale localeEn_CA = new Locale( "en" , "CA" );

        ResourceBundle rb = ResourceBundle.getBundle(
                "br.com.juliocnsouza.ocpjp._2resource_bundle.Labels" , localeEn_CA );
        System.out.println( rb.getObject( "hello" ) );

    }

}


text:
package com.ghgande.j2mod.modbus;

import com.ghgande.j2mod.modbus.msg.ReadCoilsResponse;
import com.ghgande.j2mod.modbus.msg.ReadInputDiscretesResponse;
import com.ghgande.j2mod.modbus.msg.ReadInputRegistersResponse;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse;
import com.ghgande.j2mod.modbus.utils.AbstractTestModbusUDPMaster;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * This class tests the TCP master read features of the library
 */
@SuppressWarnings("ConstantConditions")
public class TestModbusUDPRead extends AbstractTestModbusUDPMaster {

    @Test
    public void testReadCoils() {
        ReadCoilsResponse res = (ReadCoilsResponse)readRequest(Modbus.READ_COILS, 0, 1);
        assertEquals("Incorrect status for coil 0", true, res.getCoilStatus(0));
        assertEquals("Incorrect status for coil 1", false, res.getCoilStatus(1));
    }

    @Test
    public void testReadInvalidCoil() {
        assertNull("Failed check for missing coil 3", readRequest(Modbus.READ_COILS, 3, 1));
    }

    @Test
    public void testReadDiscretes() {
        ReadInputDiscretesResponse res = (ReadInputDiscretesResponse)readRequest(Modbus.READ_INPUT_DISCRETES, 0, 2);
        assertEquals("Incorrect status for discrete 1", false, res.getDiscreteStatus(0));
        assertEquals("Incorrect status for discrete 2", true, res.getDiscreteStatus(1));
    }

    @Test
    public void testReadInvalidDiscretes() {
        assertNull("Failed check for missing discrete 3", readRequest(Modbus.READ_INPUT_DISCRETES, 9, 1));
    }

    @Test
    public void testReadInputRegisters() {
        ReadInputRegistersResponse res = (ReadInputRegistersResponse)readRequest(Modbus.READ_INPUT_REGISTERS, 0, 1);
        assertEquals("Incorrect value for input register 1", 45, res.getRegisterValue(0));
    }

    @Test
    public void testReadInvalidInputRegisters() {
        assertNull("Failed check for missing input register 6", readRequest(Modbus.READ_INPUT_REGISTERS, 6, 1));
    }

    @Test
    public void testReadHoldingRegisters() {
        ReadMultipleRegistersResponse res = (ReadMultipleRegistersResponse)readRequest(Modbus.READ_HOLDING_REGISTERS, 0, 1);
        assertEquals("Incorrect value for holding register 1", 251, res.getRegisterValue(0));
    }

    @Test
    public void testReadInvalidHoldingRegisters() {
        assertNull("Failed check for missing holding register 5", readRequest(Modbus.READ_HOLDING_REGISTERS, 5, 1));
    }

    @Test
    public void testReadMultipleInputRegisters() {
        ReadInputRegistersResponse res = (ReadInputRegistersResponse)readRequest(Modbus.READ_INPUT_REGISTERS, 0, 5);
        assertEquals("Failed to read multiple input register 1 length 5", 45, res.getRegisterValue(0));
        assertEquals("Failed to read multiple input register 2 length 5", 9999, res.getRegisterValue(1));
        assertEquals("Failed to read multiple input register 3 length 5", 8888, res.getRegisterValue(2));
        assertEquals("Failed to read multiple input register 4 length 5", 7777, res.getRegisterValue(3));
        assertEquals("Failed to read multiple input register 5 length 5", 6666, res.getRegisterValue(4));
    }

    @Test
    public void testReadMultipleHoldingRegisters() {
        ReadMultipleRegistersResponse res = (ReadMultipleRegistersResponse)readRequest(Modbus.READ_HOLDING_REGISTERS, 0, 5);
        assertEquals("Failed to read multiple holding register 1 length 5", 251, res.getRegisterValue(0));
        assertEquals("Failed to read multiple holding register 2 length 5", 1111, res.getRegisterValue(1));
        assertEquals("Failed to read multiple holding register 3 length 5", 2222, res.getRegisterValue(2));
        assertEquals("Failed to read multiple holding register 4 length 5", 3333, res.getRegisterValue(3));
        assertEquals("Failed to read multiple holding register 5 length 5", 4444, res.getRegisterValue(4));
    }

    @Test
    public void testBadUnitIdRequest() {
        try {
            master.readCoils(UNIT_ID + 10, 0, 1).getBit(0);
            fail("Failed check for invalid Unit ID");
        }
        catch (Exception e) {
            // expected
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Twilight.Internal
{
    internal static class ThrowHelper
    {
        internal static void CheckLat(double lat)
        {
            if (lat < -85.0)
                throw new ArgumentOutOfRangeException(nameof(lat));

            if (lat > 85.0)
                throw new ArgumentOutOfRangeException(nameof(lat));
        }

        internal static void CheckLng(double lng)
        {
            if (lng < -180.0)
                throw new ArgumentOutOfRangeException(nameof(lng));

            if (lng > 180.0)
                throw new ArgumentOutOfRangeException(nameof(lng));
        }
    }
}


text:
namespace sv {

Volume::Volume(const glm::uvec3 &offset, const glm::uvec3 &dims)
	: offset(offset), dims(dims), bounds(glm::vec3(offset), glm::vec3(offset + dims))
{}
Volume::~Volume() {}
const glm::uvec3& Volume::get_offset() const {
	return offset;
}
const glm::uvec3& Volume::get_dims() const {
	return dims;
}
const BBox& Volume::get_bounds() const {
	return bounds;
}

VolumeDType parse_volume_dtype(const std::string &s) {
	if (s == "uint8") {
		return VolumeDType::UINT8;
	} else if (s == "uint16") {
		return VolumeDType::UINT16;
	} else if (s == "int32") {
		return VolumeDType::INT32;
	} else if (s == "float") {
		return VolumeDType::FLOAT;
	} else if (s == "double") {
		return VolumeDType::DOUBLE;
	} else {
		throw std::runtime_error("Invalid VolumeDType: '" + s + "'");
	}
}
std::istream& operator>>(std::istream &is, VolumeDType &dtype) {
	std::string s;
	is >> s;
	std::transform(s.begin(), s.end(), s.begin(), ::tolower);
	dtype = parse_volume_dtype(s);
	return is;
}
static size_t dtype_size(const VolumeDType &dtype) {
	switch (dtype) {
		case VolumeDType::UINT8: return 1;
		case VolumeDType::UINT16: return 2;
		case VolumeDType::INT32: return 4;
		case VolumeDType::FLOAT: return 4;
		case VolumeDType::DOUBLE: return 8;
	}
	throw std::runtime_error("Invalid VolumeDType");
}
std::shared_ptr<Volume> load_raw_volume(const std::string &fname, const glm::uvec3 &dims,
		const VolumeDType dtype, const glm::uvec3 &offset, const glm::uvec3 &subregion_dims)
{
	std::ifstream fin{fname.c_str(), std::ios::binary};
	const glm::uvec3 load_dims = subregion_dims == glm::uvec3(0) ? dims : subregion_dims;
	const size_t dsize = dtype_size(dtype);
	std::vector<uint8_t> vol_data(load_dims.x * load_dims.y * load_dims.z * dsize, 0);

	// Go through and read scanlines of the volume until we read the subregion we're loading
	for (size_t z = 0; z < load_dims.z; ++z) {
		for (size_t y = 0; y < load_dims.y; ++y) {
			const size_t vz = z + offset.z;
			const size_t vy = y + offset.y;
			fin.seekg(((vz * dims.y + vy) * dims.x + offset.x) * dsize);
			const size_t i = (z * load_dims.y + y) * load_dims.x * dsize;
			fin.read(reinterpret_cast<char*>(&vol_data[i]), load_dims.x * dsize);
		}
	}

	switch (dtype) {
		case VolumeDType::UINT8:
			return std::make_shared<VolumeData<uint8_t>>(offset, load_dims,
					static_cast<const void*>(vol_data.data()));
		case VolumeDType::UINT16:
			return std::make_shared<VolumeData<uint16_t>>(offset, load_dims,
					static_cast<const void*>(vol_data.data()));
		case VolumeDType::INT32:
			return std::make_shared<VolumeData<int>>(offset, load_dims,
					static_cast<const void*>(vol_data.data()));
		case VolumeDType::FLOAT:
			return std::make_shared<VolumeData<float>>(offset, load_dims,
					static_cast<const void*>(vol_data.data()));
		case VolumeDType::DOUBLE:
			return std::make_shared<VolumeData<double>>(offset, load_dims,
					static_cast<const void*>(vol_data.data()));
	}
	throw std::runtime_error("Invalid VolumeDType");
}

}


text:
module Cryptoexchange::Exchanges
  module Bitopro
    class Market < Cryptoexchange::Models::Market
      NAME = 'bitopro'
      API_URL = 'https://api.bitopro.com/v2'

      def self.trade_page_url(args={})
        base = args[:base].downcase
        target = args[:target].downcase
        "https://www.bitopro.com/trading/#{base}_#{target}"
      end
    end
  end
end


text:
<?php

class PPI_Request_Cookie extends PPI_Request_Abstract {
	/**
	 * Constructor
	 *
	 * Stores the given cookies or tries to fetch
	 * cookies if the given array is empty or not
	 * given
	 *
	 * @param array $cookies
	 */
	function __construct(array $cookies = null) {
		if($cookies !== null) {
			$this->_array       = $cookies;
			$this->_isCollected = false;
		} else {
			$this->_array = $_COOKIE;
		}
	}

	/**
	 * Set an offset
	 *
	 * Required by ArrayAccess interface
	 *
	 * Note: PPI_Request should be smart enough to set an array
	 *
	 * @param string $offset
	 * @param string $value
	 *
	 * @return void
	 */
	function offsetSet($offset, $value) {
		if ($value === null) {
			return $this->offsetUnset($offset);
		}

		// Handle cookie parameters - TODO
		list($name, $content, $expire, $path, $domain, $secure, $httponly) = $value;

		$this->_array[$offset] = $content;

		if ($this->_isCollected) {
			setcookie($name, $content, $expire, $path, $domain, $secure, $httponly);
		}
	}

	/**
	 * Unset an offset
	 *
	 * Required by ArrayAccess interface
	 *
	 * @param string $offset
	 *
	 * @return void
	 */
	function offsetUnset($offset) {
		$this->_array[$offset] = null;

		if ($this->_isCollected) {
			setcookie($offset, null, time() - 3600);
		}
	}

}