text:
import abc
import struct
import six
import sys
import array
import binascii

from . import packet_base
from . import packet_utils
from ryu.lib import addrconv
from ryu.lib import stringify

ICMPV6_DST_UNREACH = 1       # dest unreachable, codes:
ICMPV6_PACKET_TOO_BIG = 2       # packet too big
ICMPV6_TIME_EXCEEDED = 3       # time exceeded, code:
ICMPV6_PARAM_PROB = 4       # ip6 header bad

ICMPV6_ECHO_REQUEST = 128     # echo service
ICMPV6_ECHO_REPLY = 129     # echo reply
MLD_LISTENER_QUERY = 130     # multicast listener query
MLD_LISTENER_REPOR = 131     # multicast listener report
MLD_LISTENER_DONE = 132     # multicast listener done
MLDV2_LISTENER_REPORT = 143     # multicast listern report (v2)

# RFC2292 decls
ICMPV6_MEMBERSHIP_QUERY = 130     # group membership query
ICMPV6_MEMBERSHIP_REPORT = 131     # group membership report
ICMPV6_MEMBERSHIP_REDUCTION = 132     # group membership termination

ND_ROUTER_SOLICIT = 133     # router solicitation
ND_ROUTER_ADVERT = 134     # router advertisment
ND_NEIGHBOR_SOLICIT = 135     # neighbor solicitation
ND_NEIGHBOR_ADVERT = 136     # neighbor advertisment
ND_REDIREC = 137     # redirect

ICMPV6_ROUTER_RENUMBERING = 138     # router renumbering

ICMPV6_WRUREQUEST = 139     # who are you request
ICMPV6_WRUREPLY = 140     # who are you reply
ICMPV6_FQDN_QUERY = 139     # FQDN query
ICMPV6_FQDN_REPLY = 140     # FQDN reply
ICMPV6_NI_QUERY = 139     # node information request
ICMPV6_NI_REPLY = 140     # node information reply

ICMPV6_MAXTYPE = 201

# ND_OPTIONS from RFC 4861
ND_OPTION_SLA = 1  # Source Link-Layer Address
ND_OPTION_TLA = 2  # Target Link-Layer Address
ND_OPTION_PI = 3   # Prefix Information
ND_OPTION_RH = 4   # Redirected Header
ND_OPTION_MTU = 5  # MTU

MODE_IS_INCLUDE = 1
MODE_IS_EXCLUDE = 2
CHANGE_TO_INCLUDE_MODE = 3
CHANGE_TO_EXCLUDE_MODE = 4
ALLOW_NEW_SOURCES = 5
BLOCK_OLD_SOURCES = 6

class icmpv6(packet_base.PacketBase):
    """ICMPv6 (RFC 2463) header encoder/decoder class.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    type\_         Type
    code           Code
    csum           CheckSum
                   (0 means automatically-calculate when encoding)
    data           Payload.

                   ryu.lib.packet.icmpv6.echo object, \
                   ryu.lib.packet.icmpv6.nd_neighbor object, \
                   ryu.lib.packet.icmpv6.nd_router_solicit object, \
                   ryu.lib.packet.icmpv6.nd_router_advert object, \
                   ryu.lib.packet.icmpv6.mld object, \
                   or a bytearray.
    ============== ====================
    """
    _PACK_STR = '!BBH'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _ICMPV6_TYPES = {}

    @staticmethod
    def register_icmpv6_type(*args):
        def _register_icmpv6_type(cls):
            for type_ in args:
                icmpv6._ICMPV6_TYPES[type_] = cls
            return cls
        return _register_icmpv6_type

    def __init__(self, type_=0, code=0, csum=0, data=None):
        super(icmpv6, self).__init__()
        self.type_ = type_
        self.code = code
        self.csum = csum
        self.data = data

    @classmethod
    def parser(cls, buf):
        (type_, code, csum) = struct.unpack_from(cls._PACK_STR, buf)
        msg = cls(type_, code, csum)
        offset = cls._MIN_LEN
        if len(buf) > offset:
            cls_ = cls._ICMPV6_TYPES.get(type_, None)
            if cls_:
                msg.data = cls_.parser(buf, offset)
            else:
                msg.data = buf[offset:]

        return msg, None, None

    def serialize(self, payload, prev):
        hdr = bytearray(struct.pack(icmpv6._PACK_STR, self.type_,
                                    self.code, self.csum))

        if self.data is not None:
            if self.type_ in icmpv6._ICMPV6_TYPES:
                hdr += self.data.serialize()
            else:
                hdr += self.data
        if self.csum == 0:
            self.csum = packet_utils.checksum_ip(prev, len(hdr), hdr + payload)
            struct.pack_into('!H', hdr, 2, self.csum)

        return hdr

    def __len__(self):
        length = self._MIN_LEN
        if self.data is not None:
            length += len(self.data)
        return length

@icmpv6.register_icmpv6_type(ND_NEIGHBOR_SOLICIT, ND_NEIGHBOR_ADVERT)
class nd_neighbor(stringify.StringifyMixin):
    """ICMPv6 sub encoder/decoder class for Neighbor Solicitation and
    Neighbor Advertisement messages. (RFC 4861)

    This is used with ryu.lib.packet.icmpv6.icmpv6.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    res            R,S,O Flags for Neighbor Advertisement. \
                   The 3 MSBs of "Reserved" field for Neighbor Solicitation.
    dst            Target Address
    option         a derived object of ryu.lib.packet.icmpv6.nd_option \
                   or a bytearray. None if no options.
    ============== ====================
    """

    _PACK_STR = '!I16s'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _ND_OPTION_TYPES = {}
    _TYPE = {
        'ascii': [
            'dst'
        ]
    }

    @staticmethod
    def register_nd_option_type(*args):
        def _register_nd_option_type(cls):
            nd_neighbor._ND_OPTION_TYPES[cls.option_type()] = cls
            return cls
        return _register_nd_option_type(args[0])

    def __init__(self, res=0, dst='::', option=None):
        self.res = res
        self.dst = dst
        self.option = option

    @classmethod
    def parser(cls, buf, offset):
        (res, dst) = struct.unpack_from(cls._PACK_STR, buf, offset)
        offset += cls._MIN_LEN
        option = None
        if len(buf) > offset:
            (type_, ) = struct.unpack_from('!B', buf, offset)
            cls_ = cls._ND_OPTION_TYPES.get(type_)
            if cls_ is not None:
                option = cls_.parser(buf, offset)
            else:
                option = buf[offset:]
        msg = cls(res >> 29, addrconv.ipv6.bin_to_text(dst), option)
        return msg

    def serialize(self):
        res = self.res << 29
        hdr = bytearray(struct.pack(
            nd_neighbor._PACK_STR, res,
            addrconv.ipv6.text_to_bin(self.dst)))
        if self.option is not None:
            if isinstance(self.option, nd_option):
                hdr.extend(self.option.serialize())
            else:
                hdr.extend(self.option)
        return six.binary_type(hdr)

    def __len__(self):
        length = self._MIN_LEN
        if self.option is not None:
            length += len(self.option)
        return length

@icmpv6.register_icmpv6_type(ND_ROUTER_SOLICIT)
class nd_router_solicit(stringify.StringifyMixin):
    """ICMPv6 sub encoder/decoder class for Router Solicitation messages.
    (RFC 4861)

    This is used with ryu.lib.packet.icmpv6.icmpv6.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    res            This field is unused.  It MUST be initialized to zero.
    option         a derived object of ryu.lib.packet.icmpv6.nd_option \
                   or a bytearray. None if no options.
    ============== ====================
    """

    _PACK_STR = '!I'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _ND_OPTION_TYPES = {}

    @staticmethod
    def register_nd_option_type(*args):
        def _register_nd_option_type(cls):
            nd_router_solicit._ND_OPTION_TYPES[cls.option_type()] = cls
            return cls
        return _register_nd_option_type(args[0])

    def __init__(self, res=0, option=None):
        self.res = res
        self.option = option

    @classmethod
    def parser(cls, buf, offset):
        (res, ) = struct.unpack_from(cls._PACK_STR, buf, offset)
        offset += cls._MIN_LEN
        option = None
        if len(buf) > offset:
            (type_, ) = struct.unpack_from('!B', buf, offset)
            cls_ = cls._ND_OPTION_TYPES.get(type_)
            if cls_ is not None:
                option = cls_.parser(buf, offset)
            else:
                option = buf[offset:]
        msg = cls(res, option)
        return msg

    def serialize(self):
        hdr = bytearray(struct.pack(
            nd_router_solicit._PACK_STR, self.res))
        if self.option is not None:
            if isinstance(self.option, nd_option):
                hdr.extend(self.option.serialize())
            else:
                hdr.extend(self.option)
        return six.binary_type(hdr)

    def __len__(self):
        length = self._MIN_LEN
        if self.option is not None:
            length += len(self.option)
        return length

@icmpv6.register_icmpv6_type(ND_ROUTER_ADVERT)
class nd_router_advert(stringify.StringifyMixin):
    """ICMPv6 sub encoder/decoder class for Router Advertisement messages.
    (RFC 4861)

    This is used with ryu.lib.packet.icmpv6.icmpv6.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    ch_l           Cur Hop Limit.
    res            M,O Flags for Router Advertisement.
    rou_l          Router Lifetime.
    rea_t          Reachable Time.
    ret_t          Retrans Timer.
    options        List of a derived object of \
                   ryu.lib.packet.icmpv6.nd_option or a bytearray. \
                   None if no options.
    ============== ====================
    """

    _PACK_STR = '!BBHII'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _ND_OPTION_TYPES = {}

    @staticmethod
    def register_nd_option_type(*args):
        def _register_nd_option_type(cls):
            nd_router_advert._ND_OPTION_TYPES[cls.option_type()] = cls
            return cls
        return _register_nd_option_type(args[0])

    def __init__(self, ch_l=0, res=0, rou_l=0, rea_t=0, ret_t=0, options=None):
        self.ch_l = ch_l
        self.res = res
        self.rou_l = rou_l
        self.rea_t = rea_t
        self.ret_t = ret_t
        options = options or []
        assert isinstance(options, list)
        self.options = options

    @classmethod
    def parser(cls, buf, offset):
        (ch_l, res, rou_l, rea_t, ret_t
         ) = struct.unpack_from(cls._PACK_STR, buf, offset)
        offset += cls._MIN_LEN
        options = []
        while len(buf) > offset:
            (type_, length) = struct.unpack_from('!BB', buf, offset)
            cls_ = cls._ND_OPTION_TYPES.get(type_)
            if cls_ is not None:
                option = cls_.parser(buf, offset)
            else:
                option = buf[offset:offset + (length * 8 - 2)]
            options.append(option)
            offset += len(option)
        msg = cls(ch_l, res >> 6, rou_l, rea_t, ret_t, options)
        return msg

    def serialize(self):
        res = self.res << 6
        hdr = bytearray(struct.pack(
            nd_router_advert._PACK_STR, self.ch_l, res, self.rou_l,
            self.rea_t, self.ret_t))
        for option in self.options:
            if isinstance(option, nd_option):
                hdr.extend(option.serialize())
            else:
                hdr.extend(option)
        return six.binary_type(hdr)

    def __len__(self):
        length = self._MIN_LEN
        for option in self.options:
            length += len(option)
        return length

@six.add_metaclass(abc.ABCMeta)
class nd_option(stringify.StringifyMixin):
    @classmethod
    @abc.abstractmethod
    def option_type(cls):
        pass

    @abc.abstractmethod
    def __init__(self, _type, length):
        self._type = _type
        self.length = length

    @classmethod
    @abc.abstractmethod
    def parser(cls, buf):
        pass

    @abc.abstractmethod
    def serialize(self):
        pass

    def __len__(self):
        return self._MIN_LEN

class nd_option_la(nd_option):

    _PACK_STR = '!BB6s'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _TYPE = {
        'ascii': [
            'hw_src'
        ]
    }

    @abc.abstractmethod
    def __init__(self, length, hw_src, data):
        super(nd_option_la, self).__init__(self.option_type(), length)
        self.hw_src = hw_src
        self.data = data

    @classmethod
    def parser(cls, buf, offset):
        (_, length, hw_src) = struct.unpack_from(cls._PACK_STR, buf, offset)
        msg = cls(length, addrconv.mac.bin_to_text(hw_src))
        offset += cls._MIN_LEN
        if len(buf) > offset:
            msg.data = buf[offset:]

        return msg

    def serialize(self):
        buf = bytearray(struct.pack(
            self._PACK_STR, self.option_type(), self.length,
            addrconv.mac.text_to_bin(self.hw_src)))
        if self.data is not None:
            buf.extend(self.data)
        mod = len(buf) % 8
        if mod:
            buf.extend(bytearray(8 - mod))
        if 0 == self.length:
            self.length = len(buf) // 8
            struct.pack_into('!B', buf, 1, self.length)
        return six.binary_type(buf)

    def __len__(self):
        length = self._MIN_LEN
        if self.data is not None:
            length += len(self.data)
        return length

@nd_neighbor.register_nd_option_type
@nd_router_solicit.register_nd_option_type
@nd_router_advert.register_nd_option_type
class nd_option_sla(nd_option_la):
    """ICMPv6 sub encoder/decoder class for Neighbor discovery
    Source Link-Layer Address Option. (RFC 4861)

    This is used with ryu.lib.packet.icmpv6.nd_neighbor,
    ryu.lib.packet.icmpv6.nd_router_solicit or
    ryu.lib.packet.icmpv6.nd_router_advert.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    length         length of the option. \
                   (0 means automatically-calculate when encoding)
    hw_src         Link-Layer Address. \
                   NOTE: If the address is longer than 6 octets this contains \
                   the first 6 octets in the address. \
                   This implementation assumes the address has at least \
                   6 octets.
    data           A bytearray which contains the rest of Link-Layer Address \
                   and padding.  When encoding a packet, it's user's \
                   responsibility to provide necessary padding for 8-octets \
                   alignment required by the protocol.
    ============== ====================
    """

    @classmethod
    def option_type(cls):
        return ND_OPTION_SLA

    def __init__(self, length=0, hw_src='00:00:00:00:00:00', data=None):
        super(nd_option_sla, self).__init__(length, hw_src, data)

@nd_neighbor.register_nd_option_type
class nd_option_tla(nd_option_la):
    """ICMPv6 sub encoder/decoder class for Neighbor discovery
    Target Link-Layer Address Option. (RFC 4861)

    This is used with ryu.lib.packet.icmpv6.nd_neighbor.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    length         length of the option. \
                   (0 means automatically-calculate when encoding)
    hw_src         Link-Layer Address. \
                   NOTE: If the address is longer than 6 octets this contains \
                   the first 6 octets in the address. \
                   This implementation assumes the address has at least \
                   6 octets.
    data           A bytearray which contains the rest of Link-Layer Address \
                   and padding.  When encoding a packet, it's user's \
                   responsibility to provide necessary padding for 8-octets \
                   alignment required by the protocol.
    ============== ====================
    """

    @classmethod
    def option_type(cls):
        return ND_OPTION_TLA

    def __init__(self, length=0, hw_src='00:00:00:00:00:00', data=None):
        super(nd_option_tla, self).__init__(length, hw_src, data)

@nd_router_advert.register_nd_option_type
class nd_option_pi(nd_option):
    """ICMPv6 sub encoder/decoder class for Neighbor discovery
    Prefix Information Option. (RFC 4861)

    This is used with ryu.lib.packet.icmpv6.nd_router_advert.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    .. tabularcolumns:: |l|p{35em}|

    ============== ====================
    Attribute      Description
    ============== ====================
    length         length of the option. \
                   (0 means automatically-calculate when encoding)
    pl             Prefix Length.
    res1           L,A,R\* Flags for Prefix Information.
    val_l          Valid Lifetime.
    pre_l          Preferred Lifetime.
    res2           This field is unused. It MUST be initialized to zero.
    prefix         An IP address or a prefix of an IP address.
    ============== ====================

    \*R flag is defined in (RFC 3775)
    """

    _PACK_STR = '!BBBBIII16s'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _TYPE = {
        'ascii': [
            'prefix'
        ]
    }

    @classmethod
    def option_type(cls):
        return ND_OPTION_PI

    def __init__(self, length=0, pl=0, res1=0, val_l=0, pre_l=0, res2=0,
                 prefix='::'):
        super(nd_option_pi, self).__init__(self.option_type(), length)
        self.pl = pl
        self.res1 = res1
        self.val_l = val_l
        self.pre_l = pre_l
        self.res2 = res2
        self.prefix = prefix

    @classmethod
    def parser(cls, buf, offset):
        (_, length, pl, res1, val_l, pre_l, res2, prefix
         ) = struct.unpack_from(cls._PACK_STR, buf, offset)
        msg = cls(length, pl, res1 >> 5, val_l, pre_l, res2,
                  addrconv.ipv6.bin_to_text(prefix))

        return msg

    def serialize(self):
        res1 = self.res1 << 5
        hdr = bytearray(struct.pack(
            self._PACK_STR, self.option_type(), self.length, self.pl,
            res1, self.val_l, self.pre_l, self.res2,
            addrconv.ipv6.text_to_bin(self.prefix)))
        if 0 == self.length:
            self.length = len(hdr) // 8
            struct.pack_into('!B', hdr, 1, self.length)
        return six.binary_type(hdr)

@icmpv6.register_icmpv6_type(ICMPV6_ECHO_REPLY, ICMPV6_ECHO_REQUEST)
class echo(stringify.StringifyMixin):
    """ICMPv6 sub encoder/decoder class for Echo Request and Echo Reply
    messages.

    This is used with ryu.lib.packet.icmpv6.icmpv6 for
    ICMPv6 Echo Request and Echo Reply messages.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    ============== ====================
    Attribute      Description
    ============== ====================
    id             Identifier
    seq            Sequence Number
    data           Data
    ============== ====================
    """

    _PACK_STR = '!HH'
    _MIN_LEN = struct.calcsize(_PACK_STR)

    def __init__(self, id_=0, seq=0, data=None):
        self.id = id_
        self.seq = seq
        self.data = data

    @classmethod
    def parser(cls, buf, offset):
        (id_, seq) = struct.unpack_from(cls._PACK_STR, buf, offset)
        msg = cls(id_, seq)
        offset += cls._MIN_LEN

        if len(buf) > offset:
            msg.data = buf[offset:]

        return msg

    def serialize(self):
        hdr = bytearray(struct.pack(echo._PACK_STR, self.id,
                                    self.seq))
        if self.data is not None:
            hdr += bytearray(self.data)

        return hdr

    def __len__(self):
        length = self._MIN_LEN
        if self.data is not None:
            length += len(self.data)
        return length

@icmpv6.register_icmpv6_type(
    MLD_LISTENER_QUERY, MLD_LISTENER_REPOR, MLD_LISTENER_DONE)
class mld(stringify.StringifyMixin):
    """ICMPv6 sub encoder/decoder class for MLD Lister Query,
    MLD Listener Report, and MLD Listener Done messages. (RFC 2710)

    http://www.ietf.org/rfc/rfc2710.txt

    This is used with ryu.lib.packet.icmpv6.icmpv6.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    ============== =========================================
    Attribute      Description
    ============== =========================================
    maxresp        max response time in millisecond. it is
                   meaningful only in Query Message.
    address        a group address value.
    ============== =========================================
    """

    _PACK_STR = '!H2x16s'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _TYPE = {
        'ascii': [
            'address'
        ]
    }

    def __init__(self, maxresp=0, address='::'):
        self.maxresp = maxresp
        self.address = address

    @classmethod
    def parser(cls, buf, offset):
        if cls._MIN_LEN < len(buf[offset:]):
            msg = mldv2_query.parser(buf[offset:])
        else:
            (maxresp, address) = struct.unpack_from(
                cls._PACK_STR, buf, offset)
            msg = cls(maxresp, addrconv.ipv6.bin_to_text(address))

        return msg

    def serialize(self):
        buf = struct.pack(mld._PACK_STR, self.maxresp,
                          addrconv.ipv6.text_to_bin(self.address))
        return buf

    def __len__(self):
        return self._MIN_LEN

class mldv2_query(mld):
    """
    ICMPv6 sub encoder/decoder class for MLD v2 Lister Query messages.
    (RFC 3810)

    http://www.ietf.org/rfc/rfc3810.txt

    This is used with ryu.lib.packet.icmpv6.icmpv6.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    ============== =========================================
    Attribute      Description
    ============== =========================================
    maxresp        max response time in millisecond. it is
                   meaningful only in Query Message.
    address        a group address value.
    s_flg          when set to 1, routers suppress the timer
                   process.
    qrv            robustness variable for a querier.
    qqic           an interval time for a querier in unit of
                   seconds.
    num            a number of the multicast servers.
    srcs           a list of IPv6 addresses of the multicast
                   servers.
    ============== =========================================
    """

    _PACK_STR = '!H2x16sBBH'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _TYPE = {
        'ascii': [
            'address'
        ],
        'asciilist': [
            'srcs'
        ]
    }

    def __init__(self, maxresp=0, address='::', s_flg=0, qrv=2,
                 qqic=0, num=0, srcs=None):
        super(mldv2_query, self).__init__(maxresp, address)
        self.s_flg = s_flg
        self.qrv = qrv
        self.qqic = qqic
        self.num = num
        srcs = srcs or []
        assert isinstance(srcs, list)
        for src in srcs:
            assert isinstance(src, str)
        self.srcs = srcs

    @classmethod
    def parser(cls, buf):
        (maxresp, address, s_qrv, qqic, num
         ) = struct.unpack_from(cls._PACK_STR, buf)
        s_flg = (s_qrv >> 3) & 0b1
        qrv = s_qrv & 0b111
        offset = cls._MIN_LEN
        srcs = []
        while 0 < len(buf[offset:]) and num > len(srcs):
            assert 16 <= len(buf[offset:])
            (src, ) = struct.unpack_from('16s', buf, offset)
            srcs.append(addrconv.ipv6.bin_to_text(src))
            offset += 16
        assert num == len(srcs)
        return cls(maxresp, addrconv.ipv6.bin_to_text(address), s_flg,
                   qrv, qqic, num, srcs)

    def serialize(self):
        s_qrv = self.s_flg << 3 | self.qrv
        buf = bytearray(struct.pack(self._PACK_STR, self.maxresp,
                        addrconv.ipv6.text_to_bin(self.address), s_qrv,
                        self.qqic, self.num))
        for src in self.srcs:
            buf.extend(struct.pack('16s', addrconv.ipv6.text_to_bin(src)))
        if 0 == self.num:
            self.num = len(self.srcs)
            struct.pack_into('!H', buf, 22, self.num)
        return six.binary_type(buf)

    def __len__(self):
        return self._MIN_LEN + len(self.srcs) * 16

@icmpv6.register_icmpv6_type(MLDV2_LISTENER_REPORT)
class mldv2_report(mld):
    """
    ICMPv6 sub encoder/decoder class for MLD v2 Lister Report messages.
    (RFC 3810)

    http://www.ietf.org/rfc/rfc3810.txt

    This is used with ryu.lib.packet.icmpv6.icmpv6.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte order.
    __init__ takes the corresponding args in this order.

    ============== =========================================
    Attribute      Description
    ============== =========================================
    record_num     a number of the group records.
    records        a list of ryu.lib.packet.icmpv6.mldv2_report_group.
                   None if no records.
    ============== =========================================
    """

    _PACK_STR = '!2xH'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _class_prefixes = ['mldv2_report_group']

    def __init__(self, record_num=0, records=None):
        self.record_num = record_num
        records = records or []
        assert isinstance(records, list)
        for record in records:
            assert isinstance(record, mldv2_report_group)
        self.records = records

    @classmethod
    def parser(cls, buf, offset):
        (record_num, ) = struct.unpack_from(cls._PACK_STR, buf, offset)
        offset += cls._MIN_LEN
        records = []
        while 0 < len(buf[offset:]) and record_num > len(records):
            record = mldv2_report_group.parser(buf[offset:])
            records.append(record)
            offset += len(record)
        assert record_num == len(records)
        return cls(record_num, records)

    def serialize(self):
        buf = bytearray(struct.pack(self._PACK_STR, self.record_num))
        for record in self.records:
            buf.extend(record.serialize())
        if 0 == self.record_num:
            self.record_num = len(self.records)
            struct.pack_into('!H', buf, 2, self.record_num)
        return six.binary_type(buf)

    def __len__(self):
        records_len = 0
        for record in self.records:
            records_len += len(record)
        return self._MIN_LEN + records_len

class mldv2_report_group(stringify.StringifyMixin):
    """
    ICMPv6 sub encoder/decoder class for MLD v2 Lister Report Group
    Record messages. (RFC 3810)

    This is used with ryu.lib.packet.icmpv6.mldv2_report.

    An instance has the following attributes at least.
    Most of them are same to the on-wire counterparts but in host byte
    order.
    __init__ takes the corresponding args in this order.

    =============== ====================================================
    Attribute       Description
    =============== ====================================================
    type\_          a group record type for v3.
    aux_len         the length of the auxiliary data in 32-bit words.
    num             a number of the multicast servers.
    address         a group address value.
    srcs            a list of IPv6 addresses of the multicast servers.
    aux             the auxiliary data.
    =============== ====================================================
    """
    _PACK_STR = '!BBH16s'
    _MIN_LEN = struct.calcsize(_PACK_STR)
    _TYPE = {
        'ascii': [
            'address'
        ],
        'asciilist': [
            'srcs'
        ]
    }

    def __init__(self, type_=0, aux_len=0, num=0, address='::',
                 srcs=None, aux=None):
        self.type_ = type_
        self.aux_len = aux_len
        self.num = num
        self.address = address
        srcs = srcs or []
        assert isinstance(srcs, list)
        for src in srcs:
            assert isinstance(src, str)
        self.srcs = srcs
        self.aux = aux

    @classmethod
    def parser(cls, buf):
        (type_, aux_len, num, address
         ) = struct.unpack_from(cls._PACK_STR, buf)
        offset = cls._MIN_LEN
        srcs = []
        while 0 < len(buf[offset:]) and num > len(srcs):
            assert 16 <= len(buf[offset:])
            (src, ) = struct.unpack_from('16s', buf, offset)
            srcs.append(addrconv.ipv6.bin_to_text(src))
            offset += 16
        assert num == len(srcs)
        aux = None
        if aux_len:
            (aux, ) = struct.unpack_from('%ds' % (aux_len * 4), buf, offset)
        msg = cls(type_, aux_len, num, addrconv.ipv6.bin_to_text(address),
                  srcs, aux)
        return msg

    def serialize(self):
        buf = bytearray(struct.pack(self._PACK_STR, self.type_,
                        self.aux_len, self.num,
                        addrconv.ipv6.text_to_bin(self.address)))
        for src in self.srcs:
            buf.extend(struct.pack('16s', addrconv.ipv6.text_to_bin(src)))
        if 0 == self.num:
            self.num = len(self.srcs)
            struct.pack_into('!H', buf, 2, self.num)
        if self.aux is not None:
            mod = len(self.aux) % 4
            if mod:
                self.aux += bytearray(4 - mod)
                self.aux = six.binary_type(self.aux)
            buf.extend(self.aux)
            if 0 == self.aux_len:
                self.aux_len = len(self.aux) // 4
                struct.pack_into('!B', buf, 1, self.aux_len)
        return six.binary_type(buf)

    def __len__(self):
        return self._MIN_LEN + len(self.srcs) * 16 + self.aux_len * 4

icmpv6.set_classes(icmpv6._ICMPV6_TYPES)
nd_neighbor.set_classes(nd_neighbor._ND_OPTION_TYPES)
nd_router_solicit.set_classes(nd_router_solicit._ND_OPTION_TYPES)
nd_router_advert.set_classes(nd_router_advert._ND_OPTION_TYPES)


text:
package dk.brics.tajs.test;

import dk.brics.tajs.Main;
import dk.brics.tajs.options.Options;
import org.junit.Before;
import org.junit.Test;

@SuppressWarnings("static-method")
public class TestMakeContextSensitive {

    @Before
    public void init() {
        Main.reset();
        Options.get().enableTest();
    }

    @Test
    public void makecontextsensitive_syntax() {
        Misc.run("test-resources/src/makecontextsensitive/syntax.js");
    }

    @Test
    public void makecontextsensitive_syntax2() {
        Misc.run("test-resources/src/makecontextsensitive/syntax2.js");
    }

    @Test
    public void makecontextsensitive_single() {
        Misc.run("test-resources/src/makecontextsensitive/single.js");
    }

    @Test
    public void makecontextsensitive_multi() {
        Misc.run("test-resources/src/makecontextsensitive/multi.js");
    }

    @Test
    public void makecontextsensitive_confuse() {
        Misc.run("test-resources/src/makecontextsensitive/confuse.js");
    }

    @Test
    public void makecontextsensitive_finiteRecursion() {
        Misc.run("test-resources/src/makecontextsensitive/finiteRecursion.js");
    }

    @Test
    public void makecontextsensitive_finiteStringRecursion() {
        Misc.run("test-resources/src/makecontextsensitive/finiteStringRecursion.js");
    }

    @Test
    public void makecontextsensitive_objectSensitivity() {
        Misc.run("test-resources/src/makecontextsensitive/objectSensitivity.js");
    }

    @Test
    public void makecontextsensitive_guard() {
        Misc.run("test-resources/src/makecontextsensitive/guard.js");
    }

    @Test
    public void makecontextsensitive_closureVariables() {
        Misc.run("test-resources/src/makecontextsensitive/closureVariables.js");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.find.editorHeaderActions;

import com.intellij.find.SearchSession;
import com.intellij.ide.lightEdit.LightEditCompatible;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public abstract class PrevNextOccurrenceAction extends DumbAwareAction implements ContextAwareShortcutProvider,
                                                                                LightEditCompatible {
  protected final boolean mySearch;

  public PrevNextOccurrenceAction(@NotNull String templateActionId, boolean search) {
    mySearch = search;
    ActionUtil.copyFrom(this, templateActionId);
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    SearchSession search = e.getData(SearchSession.KEY);
    e.getPresentation().setEnabled(search != null && !search.isSearchInProgress() && search.hasMatches());
  }

  @Override
  public final ShortcutSet getShortcut(@NotNull DataContext context) {
    SearchSession search = SearchSession.KEY.getData(context);
    boolean singleLine = search != null && !search.getFindModel().isMultiline();
    return Utils.shortcutSetOf(singleLine ? ContainerUtil.concat(getDefaultShortcuts(), getSingleLineShortcuts()) : getDefaultShortcuts());
  }

  @NotNull
  protected abstract List<Shortcut> getDefaultShortcuts();

  @NotNull
  protected abstract List<Shortcut> getSingleLineShortcuts();
}


text:
namespace Const {
class archiv;
extern int MainCounter;
extern int PackBayte;
extern QString filePath;
}

class archiv
{
public:
    archiv(QString filePath);
    void extract(std::__cxx11::string finalPath);

private:
    QString readFile(QString url);
    void writeFile(std::__cxx11::string file, std::__cxx11::string content);
    bool checkNextItems(int count, int byte, int index, QStringList* ls);
    std::__cxx11::string convertIntToChar(int value);
    std::vector<std::__cxx11::string> split(std::__cxx11::string sequence, char sep);
    void replaceString(std::string *str, const std::__cxx11::string search, const std::__cxx11::string replace);
    std::string correctionPath(std::string file);
    void createDirectory(std::string path);

signals:

public slots:
};

#endif // ARCHIV_H


text:
dist_files = Makefile $(SCHEMA_FILES)
SCHEMA_FILES = $(wildcard *.xsd)

all: default-all

install: default-install $(DESTDIR)$(datadir)/catalog-service
	install $(SCHEMA_FILES) $(DESTDIR)$(datadir)/catalog-service

$(DESTDIR)$(datadir)/catalog-service:
	install -d -m755 $@

validate-schema:
	xmllint -schema http://www.w3.org/2001/XMLSchema.xsd $(SCHEMA_FILES) > /dev/null

dist: default-dist

clean: default-clean

export TOPDIR=$(shell pwd)/..
include $(TOPDIR)/Make.rules
include $(TOPDIR)/Make.defs


text:
module Variation
class Change
  attr_reader :length, :end_value

  # Pass :length and :end_value by hash. Length must be > 0.
  def initialize hashed_args
    raise HashedArgMissingError unless hashed_args.has_key?(:length)
    raise HashedArgMissingError unless hashed_args.has_key?(:end_value)

    self.length = hashed_args[:length]
    self.end_value = hashed_args[:end_value]
  end

  def length= length
    raise NegativeLengthError if length < 0
    @length = length
  end

  def end_value= end_value
    @end_value = end_value
  end

  def ==(other)
    length == other.length &&
    end_value == other.end_value &&
    self.class == other.class
  end
end
end


text:
namespace jxl {

// Contains encoder state.
struct PassesEncoderState {
  PassesSharedState shared;

  ImageF initial_quant_field;    // Invalid in Falcon mode.
  ImageF initial_quant_masking;  // Invalid in Falcon mode.

  // Per-pass DCT coefficients for the image. One row per group.
  std::vector<std::unique_ptr<ACImage>> coeffs;

  // Raw data for special (reference+DC) frames.
  std::vector<std::unique_ptr<BitWriter>> special_frames;

  // For splitting into passes.
  ProgressiveSplitter progressive_splitter;

  CompressParams cparams;

  struct PassData {
    std::vector<std::vector<Token>> ac_tokens;
    std::vector<uint8_t> context_map;
    EntropyEncodingData codes;
  };

  std::vector<PassData> passes;
  std::vector<uint8_t> histogram_idx;

  // Coefficient orders that are non-default.
  std::vector<uint32_t> used_orders;

  // Multiplier to be applied to the quant matrices of the x channel.
  float x_qm_multiplier = 1.0f;
  float b_qm_multiplier = 1.0f;

  // Heuristics to be used by the encoder.
  std::unique_ptr<EncoderHeuristics> heuristics =
      make_unique<DefaultEncoderHeuristics>();
};

// Initialize per-frame information.
class ModularFrameEncoder;
Status InitializePassesEncoder(const Image3F& opsin, const JxlCmsInterface& cms,
                               ThreadPool* pool,
                               PassesEncoderState* passes_enc_state,
                               ModularFrameEncoder* modular_frame_encoder,
                               AuxOut* aux_out);

// Working area for ComputeCoefficients (per-group!)
struct EncCache {
  // Allocates memory when first called, shrinks images to current group size.
  void InitOnce();

  // TokenizeCoefficients
  Image3I num_nzeroes;
};

}  // namespace jxl

#endif  // LIB_JXL_ENC_CACHE_H_


text:
package com.zkzong.mybatis.service;

import com.zkzong.mybatis.domain.Tutor;
import com.zkzong.mybatis.mapper.TutorMapper;
import com.zkzong.mybatis.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Zong on 2017/3/11.
 */
public class TutorService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public Tutor findTutorById(int tutorId) {
        logger.debug("findTutorById : " + tutorId);
        SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
        try {
            TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
            return mapper.selectTutorById(tutorId);
        } finally {
            sqlSession.close();
        }
    }

    public Tutor selectTutorWithCourses(int tutorId) {
        logger.debug("findTutorById : " + tutorId);
        SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
        try {
            TutorMapper mapper = sqlSession.getMapper(TutorMapper.class);
            return mapper.selectTutorWithCourses(tutorId);
        } finally {
            sqlSession.close();
        }
    }

}


text:
package com.tempoiq;

import java.util.Iterator;
import java.util.NoSuchElementException;
import static com.tempoiq.util.Preconditions.*;

public abstract class PageLoader<T> implements Iterator<Segment<T>> {
  protected Segment<T> current;

  public PageLoader(Segment<T> first) {
    this.current = checkNotNull(first);
  }

  @Override
  public boolean hasNext() {
    if (current != null) {
      return true;
    } else {
      return false;
    }
  }

  public abstract Segment<T> fetchNext();

  @Override
  public Segment<T> next() {
    if (current != null) {
      Segment<T> tmp = current;
      current = fetchNext();
      return tmp;
    } else {
      throw new NoSuchElementException();
    }
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException();
  }
}


text:
# Routing

Kohana provides a very powerful routing system.  In essence, routes provide an interface between the urls and your controllers and actions.  With the correct routes you could make almost any url scheme correspond to almost any arrangement of controllers, and you could change one without impacting the other.

As mentioned in the [Request Flow](flow) section, a request is handled by the [Request] class, which will look for a matching [Route] and load the appropriate controller to handle that request.

[!!] It is important to understand that **routes are matched in the order they are added**, and as soon as a URL matches a route, routing is essentially "stopped" and *the remaining routes are never tried*.  Because the default route matches almost anything, including an empty url, new routes must be place before it.

## Creating routes

If you look in `APPPATH/bootstrap.php` you will see the "default" route as follows:

	Route::set('default', '(<controller>(/<action>(/<id>)))')
	->defaults(array(
		'controller' => 'Welcome',
		'action'     => 'index',
	));

[!!] The default route is simply provided as a sample, you can remove it and replace it with your own routes.

So this creates a route with the name `default` that will match urls in the format of `(<controller>(/<action>(/<id>)))`.

Let's take a closer look at each of the parameters of [Route::set], which are `name`, `uri`, and an optional array `regex`.

### Name

The name of the route must be a **unique** string.  If it is not it will overwrite the older route with the same name. The name is used for creating urls by reverse routing, or checking which route was matched.

### URI

The uri is a string that represents the format of urls that should be matched.  The tokens surrounded with `<>` are *keys* and anything surrounded with `()` are *optional* parts of the uri. In Kohana routes, any character is allowed and treated literally aside from `()<>`.  The `/` has no meaning besides being a character that must match in the uri.  Usually the `/` is used as a static seperator but as long as the regex makes sense, there are no restrictions to how you can format your routes.

Lets look at the default route again, the uri is `(<controller>(/<action>(/<id>)))`.  We have three keys or params: controller, action, and id.   In this case, the entire uri is optional, so a blank uri would match and the default controller and action (set by defaults(), [covered below](#defaults)) would be assumed resulting in the `Controller_Welcome` class being loaded and the `action_index` method being called to handle the request.

You can use any name you want for your keys, but the following keys have special meaning to the [Request] object, and will influence which controller and action are called:

 * **Directory** - The sub-directory of `classes/Controller` to look for the controller (\[covered below]\(#directory))
 * **Controller** - The controller that the request should execute.
 * **Action** - The action method to call.

### Regex

The Kohana route system uses [perl compatible regular expressions](http://perldoc.perl.org/perlre.html) in its matching process.  By default each key (surrounded by `<>`) will match `[^/.,;?\n]++` (or in english: anything that is not a slash, period, comma, semicolon, question mark, or newline).  You can define your own patterns for each key by passing an associative array of keys and patterns as an additional third argument to Route::set.

In this example, we have controllers in two directories, `admin` and `affiliate`.  Because this route will only match urls that begin with `admin` or `affiliate`, the default route would still work for controllers in `classes/Controller`.

	Route::set('sections', '<directory>(/<controller>(/<action>(/<id>)))',
		array(
			'directory' => '(admin|affiliate)'
		))
		->defaults(array(
			'controller' => 'Home',
			'action'     => 'index',
		));

You can also use a less restrictive regex to match unlimited parameters, or to ignore overflow in a route.  In this example, the url `foobar/baz/and-anything/else_that/is-on-the/url` would be routed to `Controller_Foobar::action_baz()` and the `"stuff"` parameter would be `"and-anything/else_that/is-on-the/url"`.  If you wanted to use this for unlimited parameters, you could [explode](http://php.net/manual/en/function.explode.php) it, or you just ignore the overflow.

	Route::set('default', '(<controller>(/<action>(/<stuff>)))', array('stuff' => '.*'))
		->defaults(array(
			'controller' => 'Welcome',
			'action' => 'index',
	  ));

### Default values

If a key in a route is optional (or not present in the route), you can provide a default value for that key by passing an associated array of keys and default values to [Route::defaults], chained after your [Route::set].  This can be useful to provide a default controller or action for your site, among other things.

[!!] The `controller` and `action` key must always have a value, so they either need to be required in your route (not inside of parentheses) or have a default value provided.

[!!] Kohana automatically converts controllers to follow the standard naming convention. For example /blog/view/123 would look for the controller Controller_Blog in classes/Controller/Blog.php and trigger the action_view() method on it.

In the default route, all the keys are optional, and the controller and action are given a default.   If we called an empty url, the defaults would fill in and `Controller_Welcome::action_index()` would be called.  If we called `foobar` then only the default for action would be used, so it would call `Controller_Foobar::action_index()` and finally, if we called `foobar/baz` then neither default would be used and `Controller_Foobar::action_baz()` would be called.

TODO: need an example here

You can also use defaults to set a key that isn't in the route at all.

TODO: example of either using directory or controller where it isn't in the route, but set by defaults

### Directory

## Route Filters

In 3.3, you can specify advanced routing schemes by using filter callbacks. When you need to match a route based on more than just the URI of a request, for example, based on the method request (GET/POST/DELETE), a filter will allow you to do so. These filters will receive the `Route` object being tested, the currently matched `$params` array, and the `Request` object as the three parameters. Here's a simple example:

	Route::set('save-form', 'save')
		->filter(function($route, $params, $request)
		{
			if ($request->method() !== HTTP_Request::POST)
			{
				return FALSE; // This route only matches POST requests
			}
		});

Filters can also replace or alter the array of parameters:

	Route::set('rest-api', 'api/<action>')
		->filter(function($route, $params, $request)
		{
			// Prefix the method to the action name
			$params['action'] = strtolower($request->method()).'_'.$params['action'];
			return $params; // Returning an array will replace the parameters
		})
		->defaults(array(
			'controller' => 'api',
		));

If you are using php 5.2, you can still use any valid callback for this behavior:

	Route::set('testing', 'foo')
		->filter(array('Class', 'method_to_process_my_uri'));

## Examples

There are countless other possibilities for routes. Here are some more examples:

    /*
     * Authentication shortcuts
     */
    Route::set('auth', '<action>',
      array(
        'action' => '(login|logout)'
      ))
      ->defaults(array(
        'controller' => 'Auth'
      ));

    /*
     * Multi-format feeds
     *   452346/comments.rss
     *   5373.json
     */
    Route::set('feeds', '<user_id>(/<action>).<format>',
      array(
        'user_id' => '\d+',
        'format' => '(rss|atom|json)',
      ))
      ->defaults(array(
        'controller' => 'Feeds',
        'action' => 'status',
      ));

    /*
     * Static pages
     */
    Route::set('static', '<path>.html',
      array(
        'path' => '[a-zA-Z0-9_/]+',
      ))
      ->defaults(array(
        'controller' => 'Static',
        'action' => 'index',
      ));

    /*
     * You don't like slashes?
     *   EditGallery:bahamas
     *   Watch:wakeboarding
     */
    Route::set('gallery', '<action>(<controller>):<id>',
      array(
        'controller' => '[A-Z][a-z]++',
        'action'     => '[A-Z][a-z]++',
      ))
      ->defaults(array(
        'controller' => 'Slideshow',
      ));

    /*
     * Quick search
     */
    Route::set('search', ':<query>', array('query' => '.*'))
      ->defaults(array(
        'controller' => 'Search',
        'action' => 'index',
      ));

## Request parameters

The `directory`, `controller` and `action` can be accessed from the [Request] as public properties like so:

	// From within a controller:
	$this->request->action();
	$this->request->controller();
	$this->request->directory();

	// Can be used anywhere:
	Request::current()->action();
	Request::current()->controller();
	Request::current()->directory();

All other keys specified in a route can be accessed via [Request::param()]:

	// From within a controller:
	$this->request->param('key_name');

	// Can be used anywhere:
	Request::current()->param('key_name');

The [Request::param] method takes an optional second argument to specify a default return value in case the key is not set by the route. If no arguments are given, all keys are returned as an associative array.  In addition, `action`, `controller` and `directory` are not accessible via [Request::param()].

For example, with the following route:

	Route::set('ads','ad/<ad>(/<affiliate>)')
	->defaults(array(
		'controller' => 'ads',
		'action'     => 'index',
	));

If a url matches the route, then `Controller_Ads::index()` will be called.  You can access the parameters by using the `param()` method of the controller's [Request]. Remember to define a default value (via the second, optional parameter of [Request::param]) if you didn't in `->defaults()`.

	class Controller_Ads extends Controller {
		public function action_index()
		{
			$ad = $this->request->param('ad');
			$affiliate = $this->request->param('affiliate',NULL);
		}

## Where should routes be defined?

The established convention is to either place your custom routes in the `MODPATH/<module>/init.php` file of your module if the routes belong to a module, or simply insert them into the `APPPATH/bootstrap.php` file (be sure to put them **above** the default route) if they are specific to the application. Of course, nothing stops you from including them from an external file, or even generating them dynamically.

## A deeper look at how routes work

TODO: talk about how routes are compiled

## Creating URLs and links using routes

Along with Kohana's powerful routing capabilities are included some methods for generating URLs for your routes' uris. You can always specify your uris as a string using [URL::site] to create a full URL like so:

    URL::site('admin/edit/user/'.$user_id);

However, Kohana also provides a method to generate the uri from the route's definition. This is extremely useful if your routing could ever change since it would relieve you from having to go back through your code and change everywhere that you specified a uri as a string. Here is an example of dynamic generation that corresponds to the `feeds` route example from above:

    Route::get('feeds')->uri(array(
      'user_id' => $user_id,
      'action' => 'comments',
      'format' => 'rss'
    ));

Let's say you decided later to make that route definition more verbose by changing it to `feeds/<user_id>(/<action>).<format>`. If you wrote your code with the above uri generation method you wouldn't have to change a single line! When a part of the uri is enclosed in parentheses and specifies a key for which there in no value provided for uri generation and no default value specified in the route, then that part will be removed from the uri. An example of this is the `(/<id>)` part of the default route; this will not be included in the generated uri if an id is not provided.

One method you might use frequently is the shortcut [Request::uri] which is the same as the above except it assumes the current route, directory, controller and action. If our current route is the default and the uri was `users/list`, we can do the following to generate uris in the format `users/view/$id`:

    $this->request->uri(array('action' => 'view', 'id' => $user_id));

Or if within a view, the preferable method is:

    Request::instance()->uri(array('action' => 'view', 'id' => $user_id));

TODO: examples of using HTML::anchor in addition to the above examples

## Testing routes

TODO: mention bluehawk's devtools module


text:
const { PROMETHEUS } = require('../../jdl/jhipster/monitoring-types');
const { MICROSERVICE } = require('../../jdl/jhipster/application-types');
const { OAUTH2 } = require('../../jdl/jhipster/authentication-types');

module.exports = {
  writeFiles,
};

function writeFiles() {
  return {
    writeDockerCompose() {
      this.template('docker-compose.yml.ejs', 'docker-compose.yml');
      this.template('README-DOCKER-COMPOSE.md.ejs', 'README-DOCKER-COMPOSE.md');
    },

    writeRegistryFiles() {
      if (this.serviceDiscoveryType) {
        this.template('central-server-config/application.yml.ejs', 'central-server-config/application.yml');
      }
    },

    writeKeycloakFiles() {
      if (this.authenticationType === OAUTH2 && this.applicationType !== MICROSERVICE) {
        this.template('realm-config/jhipster-realm.json.ejs', 'realm-config/jhipster-realm.json');
        this.template('realm-config/jhipster-users-0.json.ejs', 'realm-config/jhipster-users-0.json');
      }
    },

    writePrometheusFiles() {
      if (this.monitoring !== PROMETHEUS) return;

      // Generate a list of target apps to monitor for the prometheus config
      const appsToMonitor = [];
      for (let i = 0; i < this.appConfigs.length; i++) {
        appsToMonitor.push(`        - ${this.appConfigs[i].baseName}:${this.appConfigs[i].serverPort}`);
      }

      // Format the application target list as a YAML array
      this.appsToMonitorList = appsToMonitor.join('\n').replace(/'/g, '');

      this.template('prometheus-conf/prometheus.yml.ejs', 'prometheus-conf/prometheus.yml');
      this.template('prometheus-conf/alert_rules.yml.ejs', 'prometheus-conf/alert_rules.yml');
      this.template('alertmanager-conf/config.yml.ejs', 'alertmanager-conf/config.yml');
    },
  };
}


text:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import settings
sys.path.append(settings.CAFFE_PYTHON_PATH)

import skimage.io
import caffe
import numpy as np
import click
from glob import glob
import utils

@click.command()
@click.option('--cub-path', prompt=True, type=click.Path(exists=True), default='/home/ipl/datasets/CUB-200-2011/CUB_200_2011/CUB_200_2011/images/')
@click.option('--seg-path', prompt=True, type=click.Path(exists=True), default='/home/ipl/datasets/CUB-200-2011/segmentations/')
@click.option('--out-path', prompt=True, type=click.Path(exists=True))
def main(cub_path, seg_path, out_path):
    cub_images = glob(os.path.join(cub_path, '*/*.jpg'))
    for image_path in cub_images:
        rel_image_path = image_path[len(cub_path):]
        print rel_image_path
        o_image = caffe.io.load_image(image_path)

        # I know, I had to change the extention from jpg to png!
        seg_image_path = os.path.join(seg_path, rel_image_path)[:-3] + 'png'

        s_image = caffe.io.load_image(seg_image_path)

        # The following line could be improved when we can use the imagenet
        # mean file
        background = np.ones_like(s_image) * 0.5
        threshold = np.median(s_image)  # one could use anything else, like max or min!

        so_image = np.where(s_image <= threshold, background, o_image)
        out_image_path = os.path.join(out_path, rel_image_path)
        utils.ensure_dir(os.path.dirname(out_image_path))
        skimage.io.imsave(out_image_path, so_image)

if __name__ == '__main__':
    main()


text:
[![testling badge](https://ci.testling.com/thlorenz/runnel.png)](https://ci.testling.com/thlorenz/runnel)

**run·nel/ˈrənl/** -  *A narrow channel in the ground for liquid to flow through.*

Simple and small (~ 80 loc) flow control library to execute async functions in sequence.

**Table of Contents**  *generated with [DocToc](http://doctoc.herokuapp.com/)*

- [Installation](#installation)
- [Examples](#examples)
  - [Parameter passing](#parameter-passing)
  - [Passing Array of functions](#passing-array-of-functions)
  - [Seeding a start value](#seeding-a-start-value)
- [Features](#features)
- [API](#api)
  - [*runnel(fn1[, fn2][, fn3][, ...], done)*](#runnelfn1-fn2-fn3--done)
  - [*runnel([fn1, fn2, .., done])*](#runnelfn1-fn2--done)
  - [*runnel.seed(value)*](#runnelseedvalue)
- [Compatibility](#compatibility)
- [Early failure](#early-failure)
- [Why another flow control library](#why-another-flow-control-library)
- [More Examples](#more-examples)
- [Similar libraries with larger feature set](#similar-libraries-with-larger-feature-set)

## Installation

    npm install runnel

## Examples

### Parameter passing

```javascript
var runnel = require('runnel');

function uno (cb) {
  setTimeout(function () { cb(null, 'eins'); } , 100);
}

function dos (resuno, cb) {
  setTimeout(function () { cb(null, resuno, 'zwei'); } , 100);
}

function tres (resuno, resdos, cb) {
  setTimeout(function () { cb(null, resuno, resdos, 'drei'); } , 100);
}

runnel(
    uno
  , dos
  , tres
  , function done(err, resuno, resdos, restres) {
      if (err) return console.error('Error: ', err);
      console.log('Success: uno: %s, dos: %s, tres: %s', resuno, resdos, restres);
    }
);

// => Success: uno: eins, dos: zwei, tres: drei
```

### Passing Array of functions

```js
// using uno, dos, tres and done functions from above

var funcs = [uno, dos, tres ];
funcs.push(done);

runnel(funcs);
```

### Seeding a start value

```js
function size (file, acc, cb) {
  var p = path.join(__dirname, '..', file);

  fs.stat(p, function (err, stat) {
    if (err) return cb(err);

    acc[file] = stat.size;
    cb(null, acc);
  });
}

runnel(
    // {} will be passed as the first value to next function
    // and thus become 'acc', the accumulator
    runnel.seed({})

    // after we bind 'file' to the size function the resulting
    // custom size function has signature 'function (acc, cb) {}'
  , size.bind(null, '.gitignore')
  , size.bind(null, '.jshintrc')
  , size.bind(null, '.travis.yml')

  , function done (err, acc) {
      if (err) return console.error(err);
      console.log('sizes:', acc);
    }
);

// => sizes: { '.gitignore': 96, '.jshintrc': 249, '.travis.yml': 52 }
```
[full example](https://github.com/thlorenz/runnel/blob/master/examples/runnel-seed-explicit-functions.js)

[same example using array of functions](https://github.com/thlorenz/runnel/blob/master/examples/runnel-seed.js)

## Features

- intuitive argument passing
- seeding a start value to enable async reduce like functionality
- [fails early](#early-failure)
- **no magic**
  - no special (ab)uses of `this`
  - no context passing
- adheres to known nodejs pattern i.e., callbacks are expected to be of the form `function (err[,res]*) { ... }`
- super small
- browser support

## API

All functions below are expected to invoke the callback like so:
  - `cb(null, res1[, res2][,..]` if no error occurred
  - `cb(err)` if an error occurred

### *runnel(fn1[, fn2][, fn3][, ...], done)*

Sequentially runs all the given functions, passing results from one to the next. In case any of the functions calls back
with an error `done` will be called with that error immediately.

### *runnel([fn1, fn2, .., done])*

Same as above except that functions are passed as an array rather than as separate values, which allows building up a
flows with array operations like `concat` and `push` like is done in [this example](
https://github.com/thlorenz/runnel/blob/master/examples/runnel-seed.js).

More importantly it allows `map`ping values to async functions and then execute them sequentially, akin to
[`Q.all`](https://github.com/kriskowal/q#combination).

For more information see [this real world example](https://github.com/thlorenz/bromote/blob/master/index.js).

### *runnel.seed(value)*

Returns a function that will call back with the seeded `value` as the result, which can then be consumed by the next
function in line. This allows easily implementing async reduce flows as shown in [this
example](https://github.com/thlorenz/runnel#seeding-a-start-value)

## Compatibility

- commonJS compatible, so it works with nodejs and browserify
- AMD compliant (i.e., shimlessly works with [requirejs](https://github.com/jrburke/requirejs))
- attaches itself to the `window` object if neither commonJS or AMD support is detected

## Early failure

In order to avoid surprises runnel aborts the entire call chain once any function calls back with an error.

In that case the last function in the chain is called with the error in order to provide feedback that something went wrong.

## Why another flow control library

From my experience simple, sequential flow control is sufficient in 90% of the cases and therefore using fuller featured
and therefore also larger flow control libraries is unnecessary in those instances.

runnel however was designed for exactly these situations.

It helps avoid nesting callbacks and results in much more readable and maintainable code.

It also helps minimize repetitive `if (err) { cb(err); return; } ...` occurences.

Finally because runnel focuses only on one thing it's a very small module (~ 80 loc).

## More Examples

Looky here: [examples](https://github.com/thlorenz/runnel/tree/master/examples) or consult the [tests](https://github.com/thlorenz/runnel/tree/master/test).

## Similar libraries with larger feature set

- [async](https://github.com/caolan/async)
- [asyncjs](https://github.com/fjakobs/async.js)
- [step](https://github.com/creationix/step)
- [q](https://github.com/kriskowal/q) (promises library)


text:
#pragma once
#include <moonstone/chain/protocol/types.hpp>
#include <moonstone/db/object.hpp>
#include <moonstone/db/generic_index.hpp>

namespace moonstone { namespace chain {

class witness_schedule_object;

class witness_schedule_object : public moonstone::db::abstract_object<witness_schedule_object>
{
   public:
      static const uint8_t space_id = implementation_ids;
      static const uint8_t type_id = impl_witness_schedule_object_type;

      vector< witness_id_type > current_shuffled_witnesses;
};

} }

FC_REFLECT_DERIVED(
   moonstone::chain::witness_schedule_object,
   (moonstone::db::object),
   (current_shuffled_witnesses)
)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.cxf.common (Apache CXF API 2.7.5 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.cxf.common

Classes

WSDLConstants

Enums

WSDLConstants.WSDLVersion


text:
<?php

namespace Jobby;

use Jobby\Helper;
use Jobby\Exception;

/**
 *
 */
class Jobby
{
    /**
     * @var array
     */
    private $config = array();

    /**
     * @var string
     */
    private $script;

    /**
     * @var array
     */
    private $jobs = array();

    /**
     * @var Helper
     */
    private $helper;

    /**
     * @param array $config
     */
    public function __construct(array $config = array())
    {
        $this->setConfig($this->getDefaultConfig());
        $this->setConfig($config);

        $this->script = __DIR__ . DIRECTORY_SEPARATOR . 'BackgroundJob.php';
    }

    /**
     * @return Helper
     */
    private function getHelper()
    {
        if ($this->helper === null) {
            $this->helper = new Helper();
        }

        return $this->helper;
    }

    /**
     * @return array
     */
    public function getDefaultConfig()
    {
        return array(
            'recipients' => null,
            'mailer' => 'sendmail',
            'maxRuntime' => null,
            'smtpHost' => null,
            'smtpPort' => 25,
            'smtpUsername' => null,
            'smtpPassword' => null,
            'runAs' => null,
            'environment' => $this->getHelper()->getApplicationEnv(),
            'runOnHost' => $this->getHelper()->getHost(),
            'output' => null,
            'dateFormat' => 'Y-m-d H:i:s',
            'enabled' => true,
            'debug' => false,
        );
    }

    /**
     * @param array
     */
    public function setConfig(array $config)
    {
        $this->config = array_merge($this->config, $config);
    }

    /**
     * @return array
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param string $job
     * @param array $config
     */
    public function add($job, array $config)
    {
        foreach (array("command", "schedule") as $field) {
            if (empty($config[$field])) {
                throw new Exception("'$field' is required for '$job' job");
            }
        }

        $config = array_merge($this->config, $config);
        $this->jobs[$job] = $config;
    }

    /**
     *
     */
    public function run()
    {
        if (! extension_loaded('posix')) {
            throw new Exception("'posix' extension is required");
        }

        foreach ($this->jobs as $job => $config) {
            if ($this->getHelper()->getPlatform() === Helper::WINDOWS) {
                $this->runWindows($job, $config);
            } else {
                $this->runUnix($job, $config);
            }
        }
    }

    /**
     * @param string $job
     * @param array $config
     */
    private function runUnix($job, array $config)
    {
        if ($config['debug']) {
            $output = 'debug.log';
        } else {
            $output = '/dev/null';
        }

        $command = $this->getExecutableCommand($job, $config);
        exec("php $command 1> $output 2>&1 &");
    }

    // @codeCoverageIgnoreStart
    /**
     * @param string $job
     * @param array $config
     */
    private function runWindows($job, array $config)
    {
        // Run in background (non-blocking). From
        // http://us3.php.net/manual/en/function.exec.php#43834

        $command = $this->getExecutableCommand($job, $config);
        pclose(popen("start \"blah\" /B \"php.exe\" $command", "r"));
    }
    // @codeCoverageIgnoreEnd

    /**
     * @param string $job
     * @param array $config
     * @return string
     */
    private function getExecutableCommand($job, array $config)
    {
        // Convert closures to its source code as a string so that we
        // can send it on the command line.
        if ($config['command'] instanceof \Closure) {
            $config['command'] = $this->getHelper()
                ->closureToString($config['command']);
        }

        $configQuery = http_build_query($config);
        return "\"$this->script\" \"$job\" \"$configQuery\"";
    }
}


text:
+++
categories = ["development"]
tags = ["CSharp", "AspNetCore", "xUnit"]
date = "2016-06-16T20:33:04-07:00"
title = "Unemployed project - Progress"

+++

Slow but steady progress toward a usable application.

I haven't had much to write about because things have been going so smoothly. At
this point I have several frontiers I can push forward on. I can play with the
back end code - models, repos, controllers. I now have testing working, so I can
make progress jumping back and forth between tests and implementation. And I
have the front end code which I can tweak endlessly.

I did discover one interesting detail the other day that is worth mentioning.
When I started writing tests for the LogListController I ran into a problem - I
couldn't access the `JsonResult` values to confirm behavior. The problem was
that I was using ad-hoc objects to define the json, which are marked internal by
default. In order to access them in my tests (which are in a separate
sub-project) I had to make the tests a *friend assembly* to my main project.

As usual all the information on the Internet is either wrong or outdated. The
guidance I found was that I just needed to add an attribute to my
`properties > AssemblyInfo.cs` file. It seems though that an Asp.net Core
application doesn't have assembly info. Visual Studio also wouldn't let me
create any files under properties. Even when I manually created the file with
the correct settings my tests still wouldn't run... until they did. I tried
several times before getting the builds to go off in just the right way so

[Here is a link](https://github.com/kitsu/JobLogger/blob/e8e0436140e67edfd369942793a8bbed3cc3920f/src/JobLogger/Properties/AssemblyInfo.cs)
to the file in question.

The other thing I've been doing is refining the UI. I just decided today to
scrap all the *LogList* pages I've built and replace them with a single unified
page. Since I was already using ajax for all my interactions it felt really
silly to have them in different places. The initial motivation was that the edit
forms for existing logs were going to be complete ripoffs of the add log form. I
also wanted to reuse the Knockout models I built for the add page on the list
page. I also couldn't figure out what to do upon successful submission on the
add page. Now I don't have any of those problems.

My design has basically morphed into a Single Page Application (SPA), modulo a
few ancillary pages. I am seriously debating having Knockout run the entire
front end, and making the back end primarily serve json to ajax requests. There
is no point building all the elements and Javascript code in Razor when I still
have to support live updates in the client anyway. Just push all the rendering
logic to the client and serve data ala-cart.


text:
@interface PayUserWrapper : NSObject
@property (nonatomic, strong) PayUser *user;
@end


text:
package me.dengfengdecao.singleton;

/**
 * 懒汉式
 * 非线程安全
 * @author linyu
 *
 */
public class Singleton2 {

	private static Singleton2 object;

	private Singleton2() {
	}

	public static Singleton2 newInstance() {
		if (object == null) {
			object = new Singleton2();
		}

		return object;
	}
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\MobileOperatorSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Мобильные операторы';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Добавить мобильного оператора', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'name',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
using System.Collections.Generic;
using System.Linq;

namespace DesignPatterns.Strategy
{
    internal class AscendingSort : ISortingStrategy<int>
    {
        public IEnumerable<int> Sort(IEnumerable<int> source)
        {
            return source.OrderBy(x => x);
        }
    }
}


text:
package org.apache.nifi.registry.security.authentication;

import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.registry.extension.ExtensionManager;
import org.apache.nifi.registry.properties.NiFiRegistryProperties;
import org.apache.nifi.registry.properties.SensitivePropertyProtectionException;
import org.apache.nifi.registry.properties.SensitivePropertyProvider;
import org.apache.nifi.registry.security.authentication.annotation.IdentityProviderContext;
import org.apache.nifi.registry.security.authentication.generated.IdentityProviders;
import org.apache.nifi.registry.security.authentication.generated.Property;
import org.apache.nifi.registry.security.authentication.generated.Provider;
import org.apache.nifi.registry.security.util.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.lang.Nullable;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class IdentityProviderFactory implements IdentityProviderLookup, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(IdentityProviderFactory.class);
    private static final String LOGIN_IDENTITY_PROVIDERS_XSD = "/identity-providers.xsd";
    private static final String JAXB_GENERATED_PATH = "org.apache.nifi.registry.security.authentication.generated";
    private static final JAXBContext JAXB_CONTEXT = initializeJaxbContext();

    private static JAXBContext initializeJaxbContext() {
        try {
            return JAXBContext.newInstance(JAXB_GENERATED_PATH, IdentityProviderFactory.class.getClassLoader());
        } catch (JAXBException e) {
            throw new RuntimeException("Unable to create JAXBContext.");
        }
    }

    private NiFiRegistryProperties properties;
    private ExtensionManager extensionManager;
    private SensitivePropertyProvider sensitivePropertyProvider;
    private IdentityProvider identityProvider;
    private final Map<String, IdentityProvider> identityProviders = new HashMap<>();

    @Autowired
    public IdentityProviderFactory(
            final NiFiRegistryProperties properties,
            final ExtensionManager extensionManager,
            @Nullable final SensitivePropertyProvider sensitivePropertyProvider) {
        this.properties = properties;
        this.extensionManager = extensionManager;
        this.sensitivePropertyProvider = sensitivePropertyProvider;

        if (this.properties == null) {
            throw new IllegalStateException("NiFiRegistryProperties cannot be null");
        }

        if (this.extensionManager == null) {
            throw new IllegalStateException("ExtensionManager cannot be null");
        }
    }

    @Override
    public IdentityProvider getIdentityProvider(String identifier) {
        return identityProviders.get(identifier);
    }

    @Bean
    @Primary
    public IdentityProvider getIdentityProvider() throws Exception {
        if (identityProvider == null) {
            // look up the login identity provider to use
            final String loginIdentityProviderIdentifier = properties.getProperty(NiFiRegistryProperties.SECURITY_IDENTITY_PROVIDER);

            // ensure the login identity provider class name was specified
            if (StringUtils.isNotBlank(loginIdentityProviderIdentifier)) {
                final IdentityProviders loginIdentityProviderConfiguration = loadLoginIdentityProvidersConfiguration();

                // create each login identity provider
                for (final Provider provider : loginIdentityProviderConfiguration.getProvider()) {
                    identityProviders.put(provider.getIdentifier(), createLoginIdentityProvider(provider.getIdentifier(), provider.getClazz()));
                }

                // configure each login identity provider
                for (final Provider provider : loginIdentityProviderConfiguration.getProvider()) {
                    final IdentityProvider instance = identityProviders.get(provider.getIdentifier());
                    instance.onConfigured(loadLoginIdentityProviderConfiguration(provider));
                }

                // get the login identity provider instance
                identityProvider = getIdentityProvider(loginIdentityProviderIdentifier);

                // ensure it was found
                if (identityProvider == null) {
                    throw new Exception(String.format("The specified login identity provider '%s' could not be found.", loginIdentityProviderIdentifier));
                }
            }
        }

        return identityProvider;
    }

    @Override
    public void destroy() throws Exception {
        if (identityProviders != null) {
            identityProviders.entrySet().stream().forEach(e -> e.getValue().preDestruction());
        }
    }

    private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
        final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();

        // load the users from the specified file
        if (loginIdentityProvidersConfigurationFile.exists()) {
            try {
                // find the schema
                final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                final Schema schema = schemaFactory.newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));

                // attempt to unmarshal
                XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(loginIdentityProvidersConfigurationFile));
                final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
                unmarshaller.setSchema(schema);
                final JAXBElement<IdentityProviders> element = unmarshaller.unmarshal(xsr, IdentityProviders.class);
                return element.getValue();
            } catch (SAXException | JAXBException e) {
                throw new Exception("Unable to load the login identity provider configuration file at: " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
            }
        } else {
            throw new Exception("Unable to find the login identity provider configuration file at " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
        }
    }

    private IdentityProvider createLoginIdentityProvider(final String identifier, final String loginIdentityProviderClassName) throws Exception {
        final IdentityProvider instance;

        final ClassLoader classLoader = extensionManager.getExtensionClassLoader(loginIdentityProviderClassName);
        if (classLoader == null) {
            throw new IllegalStateException("Extension not found in any of the configured class loaders: " + loginIdentityProviderClassName);
        }

        // attempt to load the class
        Class<?> rawLoginIdentityProviderClass = Class.forName(loginIdentityProviderClassName, true, classLoader);
        Class<? extends IdentityProvider> loginIdentityProviderClass = rawLoginIdentityProviderClass.asSubclass(IdentityProvider.class);

        // otherwise create a new instance
        Constructor constructor = loginIdentityProviderClass.getConstructor();
        instance = (IdentityProvider) constructor.newInstance();

        // method injection
        performMethodInjection(instance, loginIdentityProviderClass);

        // field injection
        performFieldInjection(instance, loginIdentityProviderClass);

        return instance;
    }

    private IdentityProviderConfigurationContext loadLoginIdentityProviderConfiguration(final Provider provider) {
        final Map<String, String> providerProperties = new HashMap<>();

        for (final Property property : provider.getProperty()) {
            if (!StringUtils.isBlank(property.getEncryption())) {
                String decryptedValue = decryptValue(property.getValue(), property.getEncryption());
                providerProperties.put(property.getName(), decryptedValue);
            } else {
                providerProperties.put(property.getName(), property.getValue());
            }
        }

        return new StandardIdentityProviderConfigurationContext(provider.getIdentifier(), this, providerProperties);
    }

    private void performMethodInjection(final IdentityProvider instance, final Class loginIdentityProviderClass)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        for (final Method method : loginIdentityProviderClass.getMethods()) {
            if (method.isAnnotationPresent(IdentityProviderContext.class)) {
                // make the method accessible
                final boolean isAccessible = method.isAccessible();
                method.setAccessible(true);

                try {
                    final Class<?>[] argumentTypes = method.getParameterTypes();

                    // look for setters (single argument)
                    if (argumentTypes.length == 1) {
                        final Class<?> argumentType = argumentTypes[0];

                        // look for well known types
                        if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) {
                            // nifi properties injection
                            method.invoke(instance, properties);
                        }
                    }
                } finally {
                    method.setAccessible(isAccessible);
                }
            }
        }

        final Class parentClass = loginIdentityProviderClass.getSuperclass();
        if (parentClass != null && IdentityProvider.class.isAssignableFrom(parentClass)) {
            performMethodInjection(instance, parentClass);
        }
    }

    private void performFieldInjection(final IdentityProvider instance, final Class loginIdentityProviderClass) throws IllegalArgumentException, IllegalAccessException {
        for (final Field field : loginIdentityProviderClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(IdentityProviderContext.class)) {
                // make the method accessible
                final boolean isAccessible = field.isAccessible();
                field.setAccessible(true);

                try {
                    // get the type
                    final Class<?> fieldType = field.getType();

                    // only consider this field if it isn't set yet
                    if (field.get(instance) == null) {
                        // look for well known types
                        if (NiFiRegistryProperties.class.isAssignableFrom(fieldType)) {
                            // nifi properties injection
                            field.set(instance, properties);
                        }
                    }

                } finally {
                    field.setAccessible(isAccessible);
                }
            }
        }

        final Class parentClass = loginIdentityProviderClass.getSuperclass();
        if (parentClass != null && IdentityProvider.class.isAssignableFrom(parentClass)) {
            performFieldInjection(instance, parentClass);
        }
    }

    private String decryptValue(String cipherText, String encryptionScheme) throws SensitivePropertyProtectionException {
        if (sensitivePropertyProvider == null) {
            throw new SensitivePropertyProtectionException("Sensitive Property Provider dependency was never wired, so protected " +
                    "properties cannot be decrypted. This usually indicates that a master key for this NiFi Registry was not " +
                    "detected and configured during the bootstrap startup sequence. Contact the system administrator.");
        }

        if (!sensitivePropertyProvider.getIdentifierKey().equalsIgnoreCase(encryptionScheme)) {
            throw new SensitivePropertyProtectionException("Identity Provider configuration XML was protected using " +
                    encryptionScheme +
                    ", but the configured Sensitive Property Provider supports " +
                    sensitivePropertyProvider.getIdentifierKey() +
                    ". Cannot configure this Identity Provider due to failing to decrypt protected configuration properties.");
        }

        return sensitivePropertyProvider.unprotect(cipherText);
    }

}


text:
<?php
/**
 * Created by mcfedr on 30/06/15 21:06
 */

namespace NelmioApiDocBundle\Tests\Parser;

use Nelmio\ApiDocBundle\Parser\JsonSerializableParser;

class JsonSerializableParserTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var JsonSerializableParser
     */
    private $parser;

    public function setUp()
    {
        $this->parser = new JsonSerializableParser();
    }

    /**
     * @dataProvider dataTestParser
     */
    public function testParser($property, $expected)
    {
        $result = $this->parser->parse(array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableTest'));
        foreach ($expected as $name => $value) {
            $this->assertArrayHasKey($property, $result);
            $this->assertArrayHasKey($name, $result[$property]);
            $this->assertEquals($result[$property][$name], $expected[$name]);
        }
    }

    /**
     * @dataProvider dataTestSupports
     */
    public function testSupports($class, $expected)
    {
        $this->assertEquals($this->parser->supports(array('class' => $class)), $expected);
    }

    public function dataTestParser()
    {
        return array(
            array(
                'property' => 'id',
                'expected' => array(
                    'dataType' => 'integer'
                )
            ),
            array(
                'property' => 'name',
                'expected' => array(
                    'dataType' => 'string'
                )
            ),
            array(
                'property' => 'child',
                'expected' => array(
                    'dataType' => 'object',
                    'children' => array(
                        'value' => array(
                            'dataType' => 'array',
                            'actualType' => 'array',
                            'subType' => null,
                            'required' => null,
                            'description' => null,
                            'readonly' => null
                        )
                    )
                )
            )
        );
    }

    public function dataTestSupports()
    {
        return array(
            array(
                'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableTest',
                'expected' => true
            ),
            array(
                'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableRequiredConstructorTest',
                'expected' => false
            ),
            array(
                'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableOptionalConstructorTest',
                'expected' => true
            ),
            array(
                'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\Popo',
                'expected' => false
            )
        );
    }
}


text:
package net.anotheria.moskito.core.accumulation;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.anotheria.moskito.core.config.MoskitoConfigurationHolder;
import net.anotheria.moskito.core.config.accumulators.AccumulatorConfig;
import net.anotheria.moskito.core.config.accumulators.AccumulatorsConfig;
import net.anotheria.moskito.core.dynamic.OnDemandStatsProducer;
import net.anotheria.moskito.core.helper.TieableDefinition;
import net.anotheria.moskito.core.helper.TieableRepository;
import net.anotheria.moskito.core.producers.IStats;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.stats.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Repository that holds and manages accumulators.
 * @author lrosenberg
 *
 */
public final class AccumulatorRepository extends TieableRepository<Accumulator> {

	/**
	 * Logger
	 */
	private static Logger log = LoggerFactory.getLogger(AccumulatorRepository.class);

	/**
	 * The singleton instance.
	 */
	private static AccumulatorRepository INSTANCE = new AccumulatorRepository();
	/**
	 * Returns the singleton instance of the AccumulatorRepository.
	 * @return the one and only instance.
	 */
	public static AccumulatorRepository getInstance(){
		return INSTANCE;
	}

	private AccumulatorRepository(){
		readConfig();
	}

	@Override
	protected boolean tie(Accumulator acc, IStatsProducer<? extends IStats> producer) {
		AccumulatorDefinition definition = acc.getDefinition();
		IStats target = null;
		for (IStats s : producer.getStats()){
			if (s.getName().equals(definition.getStatName())){
				target = s;
				break;
			}
		}

		if (target==null){
			if (producer instanceof OnDemandStatsProducer){
				addToAutoTie(acc, producer);
			}else{
				throw new IllegalArgumentException("StatObject not found "+definition.getStatName()+" in "+definition);
			}
		}

		acc.tieToStats(target);
		return true;

	}

	@Override
	protected Accumulator create(TieableDefinition def){
		return new Accumulator((AccumulatorDefinition)def);
	}
	/**
	 * Returns configured accumulators.
	 * @return
	 */
	public List<Accumulator> getAccumulators(){
		return getTieables();
	}

	public Accumulator createAccumulator(TieableDefinition def){
		return createTieable(def);
	}

	/**
	 * Reads the config and creates configured accumulators. For now this method is only executed on startup.
	 */
	private void readConfig(){
		AccumulatorsConfig config = MoskitoConfigurationHolder.getConfiguration().getAccumulatorsConfig();
		AccumulatorConfig[] acs = config.getAccumulators();
		if (acs!=null && acs.length>0){
			for (AccumulatorConfig ac  : acs){
				AccumulatorDefinition ad = new AccumulatorDefinition();
				ad.setName(ac.getName());
				ad.setIntervalName(ac.getIntervalName());
				ad.setProducerName(ac.getProducerName());
				ad.setStatName(ac.getStatName());
				ad.setTimeUnit(TimeUnit.valueOf(ac.getTimeUnit()));
				ad.setValueName(ac.getValueName());
				Accumulator acc = createAccumulator(ad);
				if (log.isDebugEnabled()){
					log.debug("Created accumulator "+acc);
				}
			}
		}
	}

    /**
     * This method is for unit testing ONLY.
	 * The Findbugs warning is suppressed, because this method is for unit testing only.
     */
	@SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "This method is for unit testing only.")
    void reset() {
        cleanup();
		INSTANCE = new AccumulatorRepository();
	}

}


text:
/*global indexedDB */
/**
 * Library for handling the storing of map tiles in IndexedDB.
 *
 * Author: Andy Gup (@agup)
 * Contributor: Javier Abadia (@javierabadia)
 */

O.esri.Tiles.TilesStore = function(){
    /**
     * Internal reference to the local database
     * @type {null}
     * @private
     */
    this._db = null;

    this.dbName = "offline_tile_store";
    this.objectStoreName = "tilepath";

    /**
     * Determines if indexedDB is supported
     * @returns {boolean}
     */
    this.isSupported = function(){

        if(!window.indexedDB && !window.openDatabase){
            return false;
        }

        return true;
    };

    /**
     * Adds an object to the database
     * @param urlDataPair
     * @param callback callback(boolean, err)
     */
    this.store = function(urlDataPair,callback)
    {
        try
        {
            var transaction = this._db.transaction([this.objectStoreName],"readwrite");

            transaction.oncomplete = function()
            {
                callback(true);
            };

            transaction.onerror = function(event)
            {
                callback(false,event.target.error.message);
            };

            var objectStore = transaction.objectStore(this.objectStoreName);
            var request = objectStore.put(urlDataPair);
            request.onsuccess = function()
            {
                //console.log("item added to db " + event.target.result);
            };
        }
        catch(err)
        {
            console.log("TilesStore: " + err.stack);
            callback(false, err.stack);
        }
    };

    /**
     * Retrieve a record.
     * @param url
     * @param callback
     */
    this.retrieve = function(/* String */ url,callback)
    {
        if(this._db !== null)
        {
            var objectStore = this._db.transaction([this.objectStoreName]).objectStore(this.objectStoreName);
            var request = objectStore.get(url);
            request.onsuccess = function(event)
            {
                var result = event.target.result;
                if(result === undefined)
                {
                    callback(false,"not found");
                }
                else
                {
                    callback(true,result);
                }
            };
            request.onerror = function(err)
            {
                console.log(err);
                callback(false, err);
            };
        }
    };

    /**
     * Deletes entire database
     * @param callback callback(boolean, err)
     */
    this.deleteAll = function(callback)
    {
        if(this._db !== null)
        {
            var request = this._db.transaction([this.objectStoreName],"readwrite")
                .objectStore(this.objectStoreName)
                .clear();
            request.onsuccess = function()
            {
                callback(true);
            };
            request.onerror = function(err)
            {
                callback(false, err);
            };
        }
        else
        {
            callback(false,null);
        }
    };

    /**
     * Delete an individual entry
     * @param url
     * @param callback callback(boolean, err)
     */
    this.delete = function(/* String */ url,callback)
    {
        if(this._db !== null)
        {
            var request = this._db.transaction([this.objectStoreName],"readwrite")
                .objectStore(this.objectStoreName)
                .delete(url);
            request.onsuccess = function()
            {
                callback(true);
            };
            request.onerror = function(err)
            {
                callback(false, err);
            };
        }
        else
        {
            callback(false,null);
        }
    };

    /**
     * Retrieve all tiles from indexeddb
     * @param callback callback(url, img, err)
     */
    this.getAllTiles = function(callback)
    {
        if(this._db !== null){
            var transaction = this._db.transaction([this.objectStoreName])
                .objectStore(this.objectStoreName)
                .openCursor();

            transaction.onsuccess = function(event)
            {
                var cursor = event.target.result;
                if(cursor){
                    var url = cursor.value.url;
                    var img = cursor.value.img;
                    callback(url,img,null);
                    cursor.continue();
                }
                else
                {
                    callback(null, null, "end");
                }
            }.bind(this);
            transaction.onerror = function(err)
            {
                callback(null, null, err);
            };
        }
        else
        {
            callback(null, null, "no db");
        }
    };

    /**
     * Provides the size of database in bytes
     * @param callback callback(size, null) or callback(null, error)
     */
    this.usedSpace = function(callback){
        if(this._db !== null){
            var usage = { sizeBytes: 0, tileCount: 0 };

            var transaction = this._db.transaction([this.objectStoreName])
                .objectStore(this.objectStoreName)
                .openCursor();

            transaction.onsuccess = function(event){
                var cursor = event.target.result;
                if(cursor){
                    var storedObject = cursor.value;
                    var json = JSON.stringify(storedObject);
                    usage.sizeBytes += this._stringBytes(json);
                    usage.tileCount += 1;
                    cursor.continue();
                }
                else
                {
                    callback(usage,null);
                }
            }.bind(this);
            transaction.onerror = function(err)
            {
                callback(null, err);
            };
        }
        else
        {
            callback(null,null);
        }
    };

    this._stringBytes = function(str) {
        return str.length /**2*/ ;
    };

    this.init = function(callback)
    {
        var request = indexedDB.open(this.dbName, 4);
        callback = callback || function(success) { console.log("TilesStore::init() success:", success); }.bind(this);

        request.onerror = function(event)
        {
            console.log("indexedDB error: " + event.target.errorCode);
            callback(false,event.target.errorCode);
        }.bind(this);

        request.onupgradeneeded = function(event)
        {
            var db = event.target.result;

            if( db.objectStoreNames.contains(this.objectStoreName))
            {
                db.deleteObjectStore(this.objectStoreName);
            }

            db.createObjectStore(this.objectStoreName, { keyPath: "url" });
        }.bind(this);

        request.onsuccess = function(event)
        {
            this._db = event.target.result;
            console.log("database opened successfully");
            callback(true);
        }.bind(this);
    };
};


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class Tag extends DynamicData
{
  public String key;

  public String getKey()
  {
    return this.key;
  }

  public void setKey(String key)
  {
    this.key=key;
  }
}