text:
"""
General utility functions.
"""

from __future__ import with_statement
import os,sys,socket,types
import random,time
import gzip,zlib,cPickle
import re,struct,array
import subprocess

import warnings
warnings.filterwarnings("ignore","tempnam",RuntimeWarning, __name__)

from config import conf
from data import MTU
from error import log_runtime,log_loading,log_interactive, Scapy_Exception
from base_classes import BasePacketList

WINDOWS=sys.platform.startswith("win32")

###########
## Tools ##
###########

def get_temp_file(keep=False, autoext=""):
    f = os.tempnam("","scapy")
    if not keep:
        conf.temp_files.append(f+autoext)
    return f

def sane_color(x):
    r=""
    for i in x:
        j = ord(i)
        if (j < 32) or (j >= 127):
            r=r+conf.color_theme.not_printable(".")
        else:
            r=r+i
    return r

def sane(x):
    r=""
    for i in x:
        j = ord(i)
        if (j < 32) or (j >= 127):
            r=r+"."
        else:
            r=r+i
    return r

def lhex(x):
    if type(x) in (int,long):
        return hex(x)
    elif type(x) is tuple:
        return "(%s)" % ", ".join(map(lhex, x))
    elif type(x) is list:
        return "[%s]" % ", ".join(map(lhex, x))
    else:
        return x

@conf.commands.register
def hexdump(x):
    x=str(x)
    l = len(x)
    i = 0
    while i < l:
        print "%04x  " % i,
        for j in xrange(16):
            if i+j < l:
                print "%02X" % ord(x[i+j]),
            else:
                print "  ",
            if j%16 == 7:
                print "",
        print " ",
        print sane_color(x[i:i+16])
        i += 16

@conf.commands.register
def linehexdump(x, onlyasc=0, onlyhex=0):
    x = str(x)
    l = len(x)
    if not onlyasc:
        for i in xrange(l):
            print "%02X" % ord(x[i]),
        print "",
    if not onlyhex:
        print sane_color(x)

def chexdump(x):
    x=str(x)
    print ", ".join(map(lambda x: "%#04x"%ord(x), x))

def hexstr(x, onlyasc=0, onlyhex=0):
    s = []
    if not onlyasc:
        s.append(" ".join(map(lambda x:"%02x"%ord(x), x)))
    if not onlyhex:
        s.append(sane(x))
    return "  ".join(s)

@conf.commands.register
def hexdiff(x,y):
    """Show differences between 2 binary strings"""
    x=str(x)[::-1]
    y=str(y)[::-1]
    SUBST=1
    INSERT=1
    d={}
    d[-1,-1] = 0,(-1,-1)
    for j in xrange(len(y)):
        d[-1,j] = d[-1,j-1][0]+INSERT, (-1,j-1)
    for i in xrange(len(x)):
        d[i,-1] = d[i-1,-1][0]+INSERT, (i-1,-1)

    for j in xrange(len(y)):
        for i in xrange(len(x)):
            d[i,j] = min( ( d[i-1,j-1][0]+SUBST*(x[i] != y[j]), (i-1,j-1) ),
                          ( d[i-1,j][0]+INSERT, (i-1,j) ),
                          ( d[i,j-1][0]+INSERT, (i,j-1) ) )

    backtrackx = []
    backtracky = []
    i=len(x)-1
    j=len(y)-1
    while not (i == j == -1):
        i2,j2 = d[i,j][1]
        backtrackx.append(x[i2+1:i+1])
        backtracky.append(y[j2+1:j+1])
        i,j = i2,j2

    x = y = i = 0
    colorize = { 0: lambda x:x,
                -1: conf.color_theme.left,
                 1: conf.color_theme.right }

    dox=1
    doy=0
    l = len(backtrackx)
    while i < l:
        separate=0
        linex = backtrackx[i:i+16]
        liney = backtracky[i:i+16]
        xx = sum(len(k) for k in linex)
        yy = sum(len(k) for k in liney)
        if dox and not xx:
            dox = 0
            doy = 1
        if dox and linex == liney:
            doy=1

        if dox:
            xd = y
            j = 0
            while not linex[j]:
                j += 1
                xd -= 1
            print colorize[doy-dox]("%04x" % xd),
            x += xx
            line=linex
        else:
            print "    ",
        if doy:
            yd = y
            j = 0
            while not liney[j]:
                j += 1
                yd -= 1
            print colorize[doy-dox]("%04x" % yd),
            y += yy
            line=liney
        else:
            print "    ",

        print " ",

        cl = ""
        for j in xrange(16):
            if i+j < l:
                if line[j]:
                    col = colorize[(linex[j]!=liney[j])*(doy-dox)]
                    print col("%02X" % ord(line[j])),
                    if linex[j]==liney[j]:
                        cl += sane_color(line[j])
                    else:
                        cl += col(sane(line[j]))
                else:
                    print "  ",
                    cl += " "
            else:
                print "  ",
            if j == 7:
                print "",

        print " ",cl

        if doy or not yy:
            doy=0
            dox=1
            i += 16
        else:
            if yy:
                dox=0
                doy=1
            else:
                i += 16

crc32 = zlib.crc32

if struct.pack("H",1) == "\x00\x01": # big endian
    def checksum(pkt):
        if len(pkt) % 2 == 1:
            pkt += "\0"
        s = sum(array.array("H", pkt))
        s = (s >> 16) + (s & 0xffff)
        s += s >> 16
        s = ~s
        return s & 0xffff
else:
    def checksum(pkt):
        if len(pkt) % 2 == 1:
            pkt += "\0"
        s = sum(array.array("H", pkt))
        s = (s >> 16) + (s & 0xffff)
        s += s >> 16
        s = ~s
        return (((s>>8)&0xff)|s<<8) & 0xffff

def _fletcher16(charbuf):
    # This is based on the GPLed C implementation in Zebra <http://www.zebra.org/>
    c0 = c1 = 0
    for char in charbuf:
        c0 += ord(char)
        c1 += c0

    c0 %= 255
    c1 %= 255
    return (c0,c1)

@conf.commands.register
def fletcher16_checksum(binbuf):
    """ Calculates Fletcher-16 checksum of the given buffer.

        Note:
        If the buffer contains the two checkbytes derived from the Fletcher-16 checksum
        the result of this function has to be 0. Otherwise the buffer has been corrupted.
    """
    (c0,c1)= _fletcher16(binbuf)
    return (c1 << 8) | c0

@conf.commands.register
def fletcher16_checkbytes(binbuf, offset):
    """ Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.

        Including the bytes into the buffer (at the position marked by offset) the
        global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify
        the integrity of the buffer on the receiver side.

        For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B.
    """

    # This is based on the GPLed C implementation in Zebra <http://www.zebra.org/>
    if len(binbuf) < offset:
        raise Exception("Packet too short for checkbytes %d" % len(binbuf))

    binbuf = binbuf[:offset] + "\x00\x00" + binbuf[offset + 2:]
    (c0,c1)= _fletcher16(binbuf)

    x = ((len(binbuf) - offset - 1) * c0 - c1) % 255

    if (x <= 0):
        x += 255

    y = 510 - c0 - x

    if (y > 255):
        y -= 255
    return chr(x) + chr(y)

def warning(x):
    log_runtime.warning(x)

def mac2str(mac):
    return "".join(map(lambda x: chr(int(x,16)), mac.split(":")))

def str2mac(s):
    return ("%02x:"*6)[:-1] % tuple(map(ord, s))

def strxor(x,y):
    return "".join(map(lambda x,y:chr(ord(x)^ord(y)),x,y))

# Workarround bug 643005 : https://sourceforge.net/tracker/?func=detail&atid=105470&aid=643005&group_id=5470
try:
    socket.inet_aton("255.255.255.255")
except socket.error:
    def inet_aton(x):
        if x == "255.255.255.255":
            return "\xff"*4
        else:
            return socket.inet_aton(x)
else:
    inet_aton = socket.inet_aton

inet_ntoa = socket.inet_ntoa
try:
    inet_ntop = socket.inet_ntop
    inet_pton = socket.inet_pton
except AttributeError:
    from scapy.pton_ntop import *
    log_loading.info("inet_ntop/pton functions not found. Python IPv6 support not present")

def atol(x):
    try:
        ip = inet_aton(x)
    except socket.error:
        ip = inet_aton(socket.gethostbyname(x))
    return struct.unpack("!I", ip)[0]
def ltoa(x):
    return inet_ntoa(struct.pack("!I", x&0xffffffff))

def itom(x):
    return (0xffffffff00000000L>>x)&0xffffffffL

def do_graph(graph,prog=None,format=None,target=None,type=None,string=None,options=None):
    """do_graph(graph, prog=conf.prog.dot, format="svg",
         target="| conf.prog.display", options=None, [string=1]):
    string: if not None, simply return the graph string
    graph: GraphViz graph description
    format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option
    target: filename or redirect. Defaults pipe to Imagemagick's display program
    prog: which graphviz program to use
    options: options to be passed to prog"""

    if format is None:
        if WINDOWS:
            format = "png" # use common format to make sure a viewer is installed
        else:
            format = "svg"
    if string:
        return graph
    if type is not None:
        format=type
    if prog is None:
        prog = conf.prog.dot
    start_viewer=False
    if target is None:
        if WINDOWS:
            tempfile = os.tempnam("", "scapy") + "." + format
            target = "> %s" % tempfile
            start_viewer = True
        else:
            target = "| %s" % conf.prog.display
    if format is not None:
        format = "-T %s" % format
    w,r = os.popen2("%s %s %s %s" % (prog,options or "", format or "", target))
    w.write(graph)
    w.close()
    if start_viewer:
        # Workaround for file not found error: We wait until tempfile is written.
        waiting_start = time.time()
        while not os.path.exists(tempfile):
            time.sleep(0.1)
            if time.time() - waiting_start > 3:
                warning("Temporary file '%s' could not be written. Graphic will not be displayed." % tempfile)
                break
        else:
            if conf.prog.display == conf.prog._default:
                os.startfile(tempfile)
            else:
                subprocess.Popen([conf.prog.display, tempfile])

_TEX_TR = {
    "{":"{\\tt\\char123}",
    "}":"{\\tt\\char125}",
    "\\":"{\\tt\\char92}",
    "^":"\\^{}",
    "$":"\\$",
    "#":"\\#",
    "~":"\\~",
    "_":"\\_",
    "&":"\\&",
    "%":"\\%",
    "|":"{\\tt\\char124}",
    "~":"{\\tt\\char126}",
    "<":"{\\tt\\char60}",
    ">":"{\\tt\\char62}",
    }

def tex_escape(x):
    s = ""
    for c in x:
        s += _TEX_TR.get(c,c)
    return s

def colgen(*lstcol,**kargs):
    """Returns a generator that mixes provided quantities forever
    trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by default"""
    if len(lstcol) < 2:
        lstcol *= 2
    trans = kargs.get("trans", lambda x,y,z: (x,y,z))
    while 1:
        for i in xrange(len(lstcol)):
            for j in xrange(len(lstcol)):
                for k in xrange(len(lstcol)):
                    if i != j or j != k or k != i:
                        yield trans(lstcol[(i+j)%len(lstcol)],lstcol[(j+k)%len(lstcol)],lstcol[(k+i)%len(lstcol)])

def incremental_label(label="tag%05i", start=0):
    while True:
        yield label % start
        start += 1

# Python <= 2.5 do not provide bin() built-in function
try:
    bin(0)
except NameError:
    def _binrepr(val):
        while val:
            yield val & 1
            val >>= 1

    binrepr = lambda val: "".join(reversed([str(bit) for bit in
                                            _binrepr(val)])) or "0"
else:
    binrepr = lambda val: bin(val)[2:]

#########################
#### Enum management ####
#########################

class EnumElement:
    _value=None
    def __init__(self, key, value):
        self._key = key
        self._value = value
    def __repr__(self):
        return "<%s %s[%r]>" % (self.__dict__.get("_name", self.__class__.__name__), self._key, self._value)
    def __getattr__(self, attr):
        return getattr(self._value, attr)
    def __str__(self):
        return self._key
    def __eq__(self, other):
        return self._value == int(other)

class Enum_metaclass(type):
    element_class = EnumElement
    def __new__(cls, name, bases, dct):
        rdict={}
        for k,v in dct.iteritems():
            if type(v) is int:
                v = cls.element_class(k,v)
                dct[k] = v
                rdict[v] = k
        dct["__rdict__"] = rdict
        return super(Enum_metaclass, cls).__new__(cls, name, bases, dct)
    def __getitem__(self, attr):
        return self.__rdict__[attr]
    def __contains__(self, val):
        return val in self.__rdict__
    def get(self, attr, val=None):
        return self.__rdict__.get(attr, val)
    def __repr__(self):
        return "<%s>" % self.__dict__.get("name", self.__name__)

###################
## Object saving ##
###################

def export_object(obj):
    print gzip.zlib.compress(cPickle.dumps(obj,2),9).encode("base64")

def import_object(obj=None):
    if obj is None:
        obj = sys.stdin.read()
    return cPickle.loads(gzip.zlib.decompress(obj.strip().decode("base64")))

def save_object(fname, obj):
    cPickle.dump(obj,gzip.open(fname,"wb"))

def load_object(fname):
    return cPickle.load(gzip.open(fname,"rb"))

@conf.commands.register
def corrupt_bytes(s, p=0.01, n=None):
    """Corrupt a given percentage or number of bytes from a string"""
    s = array.array("B",str(s))
    l = len(s)
    if n is None:
        n = max(1,int(l*p))
    for i in random.sample(xrange(l), n):
        s[i] = (s[i]+random.randint(1,255))%256
    return s.tostring()

@conf.commands.register
def corrupt_bits(s, p=0.01, n=None):
    """Flip a given percentage or number of bits from a string"""
    s = array.array("B",str(s))
    l = len(s)*8
    if n is None:
        n = max(1,int(l*p))
    for i in random.sample(xrange(l), n):
        s[i/8] ^= 1 << (i%8)
    return s.tostring()

#############################
## pcap capture file stuff ##
#############################

@conf.commands.register
def wrpcap(filename, pkt, *args, **kargs):
    """Write a list of packets to a pcap file

filename: the name of the file to write packets to, or an open,
          writable file-like object. The file descriptor will be
          closed at the end of the call, so do not use an object you
          do not want to close (e.g., running wrpcap(sys.stdout, [])
          in interactive mode will crash Scapy).
gz: set to 1 to save a gzipped capture
linktype: force linktype value
endianness: "<" or ">", force endianness
sync: do not bufferize writes to the capture file

    """
    with PcapWriter(filename, *args, **kargs) as fdesc:
        fdesc.write(pkt)

@conf.commands.register
def rdpcap(filename, count=-1):
    """Read a pcap or pcapng file and return a packet list

count: read only <count> packets

    """
    with PcapReader(filename) as fdesc:
        return fdesc.read_all(count=count)

class PcapReader_metaclass(type):
    """Metaclass for (Raw)Pcap(Ng)Readers"""

    def __new__(cls, name, bases, dct):
        """The `alternative` class attribute is declared in the PcapNg
        variant, and set here to the Pcap variant.

        """
        newcls = super(PcapReader_metaclass, cls).__new__(cls, name, bases, dct)
        if 'alternative' in dct:
            dct['alternative'].alternative = newcls
        return newcls

    def __call__(cls, filename):
        """Creates a cls instance, use the `alternative` if that
        fails.

        """
        i = cls.__new__(cls, cls.__name__, cls.__bases__, cls.__dict__)
        filename, fdesc, magic = cls.open(filename)
        try:
            i.__init__(filename, fdesc, magic)
        except Scapy_Exception:
            if "alternative" in cls.__dict__:
                cls = cls.__dict__["alternative"]
                i = cls.__new__(cls, cls.__name__, cls.__bases__, cls.__dict__)
                try:
                    i.__init__(filename, fdesc, magic)
                except Scapy_Exception:
                    try:
                        self.f.seek(-4, 1)
                    except:
                        pass
                    raise Scapy_Exception("Not a supported capture file")

        return i

    @staticmethod
    def open(filename):
        """Open (if necessary) filename, and read the magic."""
        if isinstance(filename, basestring):
            try:
                fdesc = gzip.open(filename,"rb")
                magic = fdesc.read(4)
            except IOError:
                fdesc = open(filename,"rb")
                magic = fdesc.read(4)
        else:
            fdesc = filename
            filename = (fdesc.name
                        if hasattr(fdesc, "name") else
                        "No name")
            magic = fdesc.read(4)
        return filename, fdesc, magic

class RawPcapReader:
    """A stateful pcap reader. Each packet is returned as a string"""
    __metaclass__ = PcapReader_metaclass
    def __init__(self, filename, fdesc, magic):
        self.filename = filename
        self.f = fdesc
        if magic == "\xa1\xb2\xc3\xd4": #big endian
            self.endian = ">"
        elif magic == "\xd4\xc3\xb2\xa1": #little endian
            self.endian = "<"
        else:
            raise Scapy_Exception(
                "Not a pcap capture file (bad magic: %r)" % magic
            )
        hdr = self.f.read(20)
        if len(hdr)<20:
            raise Scapy_Exception("Invalid pcap file (too short)")
        vermaj, vermin, tz, sig, snaplen, linktype = struct.unpack(
            self.endian + "HHIIII", hdr
        )
        self.linktype = linktype

    def __iter__(self):
        return self

    def next(self):
        """implement the iterator protocol on a set of packets in a pcap file"""
        pkt = self.read_packet()
        if pkt == None:
            raise StopIteration
        return pkt

    def read_packet(self, size=MTU):
        """return a single packet read from the file

        returns None when no more packets are available
        """
        hdr = self.f.read(16)
        if len(hdr) < 16:
            return None
        sec,usec,caplen,wirelen = struct.unpack(self.endian+"IIII", hdr)
        s = self.f.read(caplen)[:size]
        return s,(sec,usec,wirelen) # caplen = len(s)

    def dispatch(self, callback):
        """call the specified callback routine for each packet read

        This is just a convienience function for the main loop
        that allows for easy launching of packet processing in a
        thread.
        """
        for p in self:
            callback(p)

    def read_all(self,count=-1):
        """return a list of all packets in the pcap file
        """
        res=[]
        while count != 0:
            count -= 1
            p = self.read_packet()
            if p is None:
                break
            res.append(p)
        return res

    def recv(self, size=MTU):
        """ Emulate a socket
        """
        return self.read_packet(size=size)[0]

    def fileno(self):
        return self.f.fileno()

    def close(self):
        return self.f.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tracback):
        self.close()

class PcapReader(RawPcapReader):
    def __init__(self, filename, fdesc, magic):
        RawPcapReader.__init__(self, filename, fdesc, magic)
        try:
            self.LLcls = conf.l2types[self.linktype]
        except KeyError:
            warning("PcapReader: unknown LL type [%i]/[%#x]. Using Raw packets" % (self.linktype,self.linktype))
            self.LLcls = conf.raw_layer
    def read_packet(self, size=MTU):
        rp = RawPcapReader.read_packet(self, size=size)
        if rp is None:
            return None
        s,(sec,usec,wirelen) = rp

        try:
            p = self.LLcls(s)
        except KeyboardInterrupt:
            raise
        except:
            if conf.debug_dissector:
                raise
            p = conf.raw_layer(s)
        p.time = sec+0.000001*usec
        return p
    def read_all(self,count=-1):
        res = RawPcapReader.read_all(self, count)
        import plist
        return plist.PacketList(res,name = os.path.basename(self.filename))
    def recv(self, size=MTU):
        return self.read_packet(size=size)

class RawPcapNgReader(RawPcapReader):
    """A stateful pcapng reader. Each packet is returned as a
    string.

    """

    alternative = RawPcapReader

    def __init__(self, filename, fdesc, magic):
        self.filename = filename
        self.f = fdesc
        # A list of (linktype, snaplen); will be populated by IDBs.
        self.interfaces = []
        self.blocktypes = {
            1: self.read_block_idb,
            6: self.read_block_epb,
        }
        if magic != "\x0a\x0d\x0d\x0a": # PcapNg:
            raise Scapy_Exception(
                "Not a pcapng capture file (bad magic: %r)" % magic
            )
        # see https://github.com/pcapng/pcapng
        blocklen, magic = self.f.read(4), self.f.read(4)
        if magic == "\x1a\x2b\x3c\x4d":
            self.endian = ">"
        elif magic == "\x4d\x3c\x2b\x1a":
            self.endian = "<"
        else:
            raise Scapy_Exception("Not a pcapng capture file (bad magic)")
        self.f.seek(0)

    def read_packet(self, size=MTU):
        """Read blocks until it reaches either EOF or a packet, and
        returns None or (packet, (linktype, sec, usec, wirelen)),
        where packet is a string.

        """
        while True:
            try:
                blocktype, blocklen = struct.unpack(self.endian + "2I",
                                                    self.f.read(8))
            except struct.error:
                return None
            block = self.f.read(blocklen - 12)
            try:
                if (blocklen,) != struct.unpack(self.endian + 'I',
                                                self.f.read(4)):
                    raise Scapy_Exception(
                        "Invalid pcapng block (bad blocklen)"
                    )
            except struct.error:
                return None
            res = self.blocktypes.get(blocktype,
                                      lambda block, size: None)(block, size)
            if res is not None:
                return res

    def read_block_idb(self, block, _):
        """Interface Description Block"""
        self.interfaces.append(struct.unpack(self.endian + "HxxI", block[:8]))

    def read_block_epb(self, block, size):
        """Enhanced Packet Block"""
        intid, sec, usec, caplen, wirelen = struct.unpack(self.endian + "5I",
                                                          block[:20])
        return (block[20:20 + caplen][:size],
                (self.interfaces[intid][0], sec, usec, wirelen))

class PcapNgReader(RawPcapNgReader):

    alternative = PcapReader

    def __init__(self, filename, fdesc, magic):
        RawPcapNgReader.__init__(self, filename, fdesc, magic)

    def read_packet(self, size=MTU):
        rp = RawPcapNgReader.read_packet(self, size=size)
        if rp is None:
            return None
        s, (linktype, sec, usec, wirelen) = rp
        try:
            p = conf.l2types[linktype](s)
        except KeyboardInterrupt:
            raise
        except:
            if conf.debug_dissector:
                raise
            p = conf.raw_layer(s)
        p.time = sec+0.000001*usec
        return p
    def read_all(self,count=-1):
        res = RawPcapNgReader.read_all(self, count)
        import plist
        return plist.PacketList(res, name=os.path.basename(self.filename))
    def recv(self, size=MTU):
        return self.read_packet()

class RawPcapWriter:
    """A stream PCAP writer with more control than wrpcap()"""
    def __init__(self, filename, linktype=None, gz=False, endianness="", append=False, sync=False):
        """
filename: the name of the file to write packets to, or an open,
          writable file-like object.
linktype: force linktype to a given value. If None, linktype is taken
          from the first writter packet
gz: compress the capture on the fly
endianness: force an endianness (little:"<", big:">"). Default is native
append: append packets to the capture file instead of truncating it
sync: do not bufferize writes to the capture file

        """

        self.linktype = linktype
        self.header_present = 0
        self.append = append
        self.gz = gz
        self.endian = endianness
        self.sync = sync
        bufsz=4096
        if sync:
            bufsz = 0

        if isinstance(filename, basestring):
            self.filename = filename
            self.f = [open,gzip.open][gz](filename,append and "ab" or "wb", gz and 9 or bufsz)
        else:
            self.f = filename
            self.filename = (filename.name
                             if hasattr(filename, "name") else
                             "No name")

    def fileno(self):
        return self.f.fileno()

    def _write_header(self, pkt):
        self.header_present=1

        if self.append:
            # Even if prone to race conditions, this seems to be
            # safest way to tell whether the header is already present
            # because we have to handle compressed streams that
            # are not as flexible as basic files
            g = [open,gzip.open][self.gz](self.filename,"rb")
            if g.read(16):
                return

        self.f.write(struct.pack(self.endian+"IHHIIII", 0xa1b2c3d4L,
                                 2, 4, 0, 0, MTU, self.linktype))
        self.f.flush()

    def write(self, pkt):
        """accepts either a single packet or a list of packets to be
        written to the dumpfile

        """
        if type(pkt) is str:
            if not self.header_present:
                self._write_header(pkt)
            self._write_packet(pkt)
        else:
            pkt = pkt.__iter__()
            if not self.header_present:
                try:
                    p = pkt.next()
                except StopIteration:
                    self._write_header("")
                    return
                self._write_header(p)
                self._write_packet(p)
            for p in pkt:
                self._write_packet(p)

    def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None):
        """writes a single packet to the pcap file
        """
        if caplen is None:
            caplen = len(packet)
        if wirelen is None:
            wirelen = caplen
        if sec is None or usec is None:
            t=time.time()
            it = int(t)
            if sec is None:
                sec = it
            if usec is None:
                usec = int(round((t-it)*1000000))
        self.f.write(struct.pack(self.endian+"IIII", sec, usec, caplen, wirelen))
        self.f.write(packet)
        if self.sync:
            self.f.flush()

    def flush(self):
        return self.f.flush()

    def close(self):
        return self.f.close()

    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, tracback):
        self.flush()
        self.close()

class PcapWriter(RawPcapWriter):
    """A stream PCAP writer with more control than wrpcap()"""
    def _write_header(self, pkt):
        if self.linktype == None:
            try:
                self.linktype = conf.l2types[pkt.__class__]
            except KeyError:
                warning("PcapWriter: unknown LL type for %s. Using type 1 (Ethernet)" % pkt.__class__.__name__)
                self.linktype = 1
        RawPcapWriter._write_header(self, pkt)

    def _write_packet(self, packet):
        sec = int(packet.time)
        usec = int(round((packet.time-sec)*1000000))
        s = str(packet)
        caplen = len(s)
        RawPcapWriter._write_packet(self, s, sec, usec, caplen, caplen)

re_extract_hexcap = re.compile("^((0x)?[0-9a-fA-F]{2,}[ :\t]{,3}|) *(([0-9a-fA-F]{2} {,2}){,16})")

def import_hexcap():
    p = ""
    try:
        while 1:
            l = raw_input().strip()
            try:
                p += re_extract_hexcap.match(l).groups()[2]
            except:
                warning("Parsing error during hexcap")
                continue
    except EOFError:
        pass

    p = p.replace(" ","")
    return p.decode("hex")

@conf.commands.register
def wireshark(pktlist):
    """Run wireshark on a list of packets"""
    f = get_temp_file()
    wrpcap(f, pktlist)
    subprocess.Popen([conf.prog.wireshark, "-r", f])

@conf.commands.register
def hexedit(x):
    x = str(x)
    f = get_temp_file()
    open(f,"w").write(x)
    subprocess.call([conf.prog.hexedit, f])
    x = open(f).read()
    os.unlink(f)
    return x

def __make_table(yfmtfunc, fmtfunc, endline, list, fxyz, sortx=None, sorty=None, seplinefunc=None):
    vx = {}
    vy = {}
    vz = {}
    vxf = {}
    vyf = {}
    l = 0
    for e in list:
        xx,yy,zz = map(str, fxyz(e))
        l = max(len(yy),l)
        vx[xx] = max(vx.get(xx,0), len(xx), len(zz))
        vy[yy] = None
        vz[(xx,yy)] = zz

    vxk = vx.keys()
    vyk = vy.keys()
    if sortx:
        vxk.sort(sortx)
    else:
        try:
            vxk.sort(lambda x,y:int(x)-int(y))
        except:
            try:
                vxk.sort(lambda x,y: cmp(atol(x),atol(y)))
            except:
                vxk.sort()
    if sorty:
        vyk.sort(sorty)
    else:
        try:
            vyk.sort(lambda x,y:int(x)-int(y))
        except:
            try:
                vyk.sort(lambda x,y: cmp(atol(x),atol(y)))
            except:
                vyk.sort()

    if seplinefunc:
        sepline = seplinefunc(l, map(lambda x:vx[x],vxk))
        print sepline

    fmt = yfmtfunc(l)
    print fmt % "",
    for x in vxk:
        vxf[x] = fmtfunc(vx[x])
        print vxf[x] % x,
    print endline
    if seplinefunc:
        print sepline
    for y in vyk:
        print fmt % y,
        for x in vxk:
            print vxf[x] % vz.get((x,y), "-"),
        print endline
    if seplinefunc:
        print sepline

def make_table(*args, **kargs):
    __make_table(lambda l:"%%-%is" % l, lambda l:"%%-%is" % l, "", *args, **kargs)

def make_lined_table(*args, **kargs):
    __make_table(lambda l:"%%-%is |" % l, lambda l:"%%-%is |" % l, "",
                 seplinefunc=lambda a,x:"+".join(map(lambda y:"-"*(y+2), [a-1]+x+[-2])),
                 *args, **kargs)

def make_tex_table(*args, **kargs):
    __make_table(lambda l: "%s", lambda l: "& %s", "\\\\", seplinefunc=lambda a,x:"\\hline", *args, **kargs)


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arun.externaldatabsedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.cgl.eng.activity.QuestionActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.arun.externaldatabsedemo.EmployeeRegistration">
         </activity>
         <activity
            android:name="com.arun.externaldatabsedemo.EmployeEdit">
         </activity>
    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
package io.reactivex.internal.operators;

import java.util.*;

import org.reactivestreams.Publisher;

import io.reactivex.Observer;
import io.reactivex.internal.util.*;

/**
 * Returns an Iterable that always returns the item most recently emitted by an Observable, or a
 * seed value if no item has yet been emitted.
 *

 *
 */
public enum BlockingOperatorMostRecent {
    ;
    /**
     * Returns an {@code Iterable} that always returns the item most recently emitted by the {@code Observable}.
     *
     * @param source
     *            the source {@code Observable}
     * @param initialValue
     *            a default item to return from the {@code Iterable} if {@code source} has not yet emitted any
     *            items
     * @return an {@code Iterable} that always returns the item most recently emitted by {@code source}, or
     *         {@code initialValue} if {@code source} has not yet emitted any items
     */
    public static <T> Iterable<T> mostRecent(final Publisher<? extends T> source, final T initialValue) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                MostRecentObserver<T> mostRecentObserver = new MostRecentObserver<>(initialValue);

                /**
                 * Subscribe instead of unsafeSubscribe since this is the final subscribe in the chain
                 * since it is for BlockingObservable.
                 */
                source.subscribe(mostRecentObserver);

                return mostRecentObserver.getIterable();
            }
        };
    }

    private static final class MostRecentObserver<T> extends Observer<T> {
        volatile Object value;

        private MostRecentObserver(T value) {
            this.value = NotificationLite.next(value);
        }

        @Override
        public void onComplete() {
            value = NotificationLite.complete();
        }

        @Override
        public void onError(Throwable e) {
            value = NotificationLite.error(e);
        }

        @Override
        public void onNext(T args) {
            value = NotificationLite.next(args);
        }

        /**
         * The {@link Iterator} return is not thread safe. In other words don't call {@link Iterator#hasNext()} in one
         * thread expect {@link Iterator#next()} called from a different thread to work.
         * @return
         */
        public Iterator<T> getIterable() {
            return new Iterator<T>() {
                /**
                 * buffer to make sure that the state of the iterator doesn't change between calling hasNext() and next().
                 */
                private Object buf = null;

                @Override
                public boolean hasNext() {
                    buf = value;
                    return !NotificationLite.isComplete(buf);
                }

                @Override
                public T next() {
                    try {
                        // if hasNext wasn't called before calling next.
                        if (buf == null)
                            buf = value;
                        if (NotificationLite.isComplete(buf))
                            throw new NoSuchElementException();
                        if (NotificationLite.isError(buf)) {
                            throw Exceptions.propagate(NotificationLite.getError(buf));
                        }
                        return NotificationLite.getValue(buf);
                    }
                    finally {
                        buf = null;
                    }
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException("Read only iterator");
                }
            };
        }
    }
}


text:
echo "Starting nginx instance..."
docker run -d -p 80:80 -p 443:443 \
    --name nginx \
    -v /etc/nginx/conf.d  \
    -v /etc/nginx/vhost.d \
    -v /usr/share/nginx/html \
    -v /home/core/certs:/etc/nginx/certs:ro \
    nginx

sleep 1
echo "Starting docker-gen instance..."
docker run -d \
  --name nginx-gen \
  --volumes-from nginx \
  -v /home/core/nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro \
  -v /var/run/docker.sock:/tmp/docker.sock:ro \
  jwilder/docker-gen \
  -notify-sighup nginx -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf

sleep 1
echo "Starting letsencrypt-nginx-proxy-companion..."
docker run -d \
  --name nginx-letsencrypt \
  -e "NGINX_DOCKER_GEN_CONTAINER=nginx-gen" \
  --volumes-from nginx \
  -v /home/core/certs:/etc/nginx/certs:rw \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  jrcs/letsencrypt-nginx-proxy-companion

sleep 1
echo "Starting sigdevops example app..."
docker run -d \
    --name sigdevops-app \
    -e "VIRTUAL_HOST=sigdevops.io" \
    -e "LETSENCRYPT_HOST=sigdevops.io" \
    -e "LETSENCRYPT_EMAIL=jb@wps.de" \
    nginx

sleep 1
echo "Starting sigdevops docker registry..."
docker run -d \
    --name sigdevops-registry \
    -e "VIRTUAL_HOST=registry.sigdevops.io" \
    -e "LETSENCRYPT_HOST=registry.sigdevops.io" \
    -e "LETSENCRYPT_EMAIL=jb@wps.de" \
    registry


text:
#region S# License

#endregion S# License
using System;
using System.Linq;
using System.Xml.Linq;

using XMLCommToHTM.DOM.Internal;
using XMLCommToHTM.DOM.Internal.DOC;

namespace XMLCommToHTM.DOM
{
	public class TypeDom
	{
		public enum TypeKindEnum
		{
			Class,
			Struct,
			Interface,
			Delegate,
			Enum
		};

		public AssemblyDom Assembly;
		public XElement DocInfo;
		public Type Type;

		public GenericParameterDom[] GenericTypeParameters;
		public MemberDom[] AllMembers;

		public ConstructorDom[] Constructors;
		public FieldDom[] Fields;
		public PropertyDom[] Properties;
		public MethodDom[] Methods;
		public MethodDom[] Operators;
		public EventDom[] Events;

		public MethodDom[] ExtentionMethods;

		public TypeDom[] NestedTypes;

		public TypeKindEnum TypeKind
		{
			get
			{
				if(Type.BaseType==typeof(MulticastDelegate))
					return TypeKindEnum.Delegate;
				if (Type.IsInterface)
					return TypeKindEnum.Interface;
				else if(Type.IsEnum)
					return TypeKindEnum.Enum;
				else if (Type.IsValueType)
					return TypeKindEnum.Struct;
				return TypeKindEnum.Class;
			}
		}

		public string FullName => Type.FullName;
		public string Namespace => Type.Namespace??"";
		public string SimpleName => TypeUtils.SimpleName(Type);
		//public string SimpleNameWithNestedGen { get { return TypeUtils.ToDisplayString(Type,false,"(",")"); } }
		public string GetDisplayName(bool includeNamespace, string brOpen="<", string brClose=">")
		{
			return TypeUtils.ToDisplayString(Type, includeNamespace, brOpen, brClose);
		}

		public Type[] BaseTypes => Type.GetBaseTypes()
			//.Select(_ => TypeUtils.ToDisplayString(_, true))
			.Reverse()
			.ToArray();

		//public string[] GetDistinctMethodsNames()
		//{
		//	return Methods.Select(_ => _.Name).Distinct().ToArray();
		//}

		public Type[] DerivedTypes => AssemblyUtils.GetAllDerivedTypes(Assembly.ReflectionAssembly, Type).ToArray();

		public static TypeDom Build(TypeDoc doc, AssemblyDom asm, Func<MemberDom, bool> filterMembers)
		{
			var ret = new TypeDom
				{
					Assembly = asm,
					DocInfo = doc.DocInfo,
					Type = doc.ReflectionType,
				};
			MemberDom[] members = doc.Members
									 .Where(_ => _.ReflectionMemberInfo != null)
									 .Select(_ => MemberDom.Build(ret, _.ReflectionMemberInfo, _.DocInfo))
									 .ToArray();

			members = members.Where(
				_ => (filterMembers==null || filterMembers(_)) && !_.IsPrivateOrInternal
				).ToArray();

			ret.AllMembers = members;
			ret.Constructors = members.OfType<ConstructorDom>().OrderBy(_ => _.ShortSignature).ToArray();
			ret.Fields = members.OfType<FieldDom>()
			                .OrderBy(_ => _.ShortSignature)
			                .ToArray();
			ret.Properties = members.OfType<PropertyDom>()
			                .OrderBy(_ => _.ShortSignature)
			                .ToArray();
			ret.Methods = members.OfType<MethodDom>()
			                .Where(_ => !_.IsOperator)
			                .OrderBy(_ => _.ShortSignature)
			                .ToArray();
			ret.Operators = members.OfType<MethodDom>()
			                .Where(_ => _.IsOperator)
			                .OrderBy(_ => _.ShortSignature)
			                .ToArray();
			ret.Events = members.OfType<EventDom>()
			                .OrderBy(_ => _.ShortSignature)
			                .ToArray();
			ret.GenericTypeParameters = GenericParameterDom.BuildTypeGenericParameters(ret.Type, ret.DocInfo);
			return ret;
		}

		public string Name => Type.Name;

		public void FillOverrideIndex()
		{
			var groups = Methods
				.GroupBy(_ => _.SimpleName)
				.Where(_=>_.Count()>1);
			foreach (var g in groups)
			{
				int index = 1;
				foreach (var methodDom in g.OrderBy(_ => _.ShortSignature))
				{
					methodDom.OverloadIndex = index;
					index++;
				}
			}
		}
	}
}


text:
/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#ifndef GUCEF_CORE_CLOGMANAGER_H
#include "CLogManager.h"
#define GUCEF_CORE_CLOGMANAGER_H
#endif /* GUCEF_CORE_CLOGMANAGER_H ? */

#ifndef GUCEF_CORE_CCOREGLOBAL_H
#include "gucefCORE_CCoreGlobal.h"
#define GUCEF_CORE_CCOREGLOBAL_H
#endif /* GUCEF_CORE_CCOREGLOBAL_H ? */

#ifndef GUCEF_CORE_CMFILEACCESS_H
#include "CMFileAccess.h"
#define GUCEF_CORE_CMFILEACCESS_H
#endif /* GUCEF_CORE_CMFILEACCESS_H ? */

#ifndef GUCEF_CORE_CDSTORECODECREGISTRY_H
#include "CDStoreCodecRegistry.h"
#define GUCEF_CORE_CDSTORECODECREGISTRY_H
#endif /* GUCEF_CORE_CDSTORECODECREGISTRY_H ? */

#ifndef GUCEF_PATCHER_CPATCHLISTENGINE_H
#include "gucefPATCHER_CPatchListEngine.h"
#define GUCEF_PATCHER_CPATCHLISTENGINE_H
#endif /* GUCEF_PATCHER_CPATCHLISTENGINE_H ? */

#include "gucefPATCHER_CPatchEngine.h"	/* definition of this class */

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

namespace GUCEF {
namespace PATCHER {

/*-------------------------------------------------------------------------//
//                                                                         //
//      GLOBAL VARS                                                        //
//                                                                         //
//-------------------------------------------------------------------------*/

const CORE::CEvent CPatchEngine::PatchProcessStartedEvent = "GUCEF::PATCHER::CPatchEngine::PatchProcessStartedEvent";
const CORE::CEvent CPatchEngine::PatchProcessCompletedEvent = "GUCEF::PATCHER::CPatchEngine::PatchProcessCompletedEvent";
const CORE::CEvent CPatchEngine::PatchProcessAbortedEvent = "GUCEF::PATCHER::CPatchEngine::PatchProcessAbortedEvent";
const CORE::CEvent CPatchEngine::PatchProcessFailedEvent = "GUCEF::PATCHER::CPatchEngine::PatchProcessFailedEvent";
const CORE::CEvent CPatchEngine::PatchListDataReceivedEvent = "GUCEF::PATCHER::CPatchEngine::PatchListDataReceivedEvent";
const CORE::CEvent CPatchEngine::PatchListRetrievalStartedEvent = "GUCEF::PATCHER::CPatchEngine::PatchListRetrievalStartedEvent";
const CORE::CEvent CPatchEngine::PatchListRetrievalCompletedEvent = "GUCEF::PATCHER::CPatchEngine::PatchListRetrievalCompletedEvent";
const CORE::CEvent CPatchEngine::PatchListRetrievalFailedEvent = "GUCEF::PATCHER::CPatchEngine::PatchListRetrievalFailedEvent";
const CORE::CEvent CPatchEngine::PatchListRetrievalAbortedEvent = "GUCEF::PATCHER::CPatchEngine::PatchListRetrievalAbortedEvent";
const CORE::CEvent CPatchEngine::PatchListDecodingFailedEvent = "GUCEF::PATCHER::CPatchEngine::PatchListDecodingFailedEvent";

/*-------------------------------------------------------------------------//
//                                                                         //
//      UTILITIES                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

CPatchEngine::CPatchEngine( const CORE::PulseGeneratorPtr& pulseGenerator )
    : CORE::CForwardingNotifier()                                 ,
      CPatchSetDirEngineEvents()                                  ,
      CPatchSetFileEngineEvents()                                 ,
      CPatchSetEngineEvents()                                     ,
      CPatchListEngineEvents()                                    ,
      m_patchListEngine( new CPatchListEngine( pulseGenerator ) ) ,
      m_url()                                                     ,
      m_listDataBuffer()                                          ,
      m_isActive( false )                                         ,
      m_stopSignalGiven( false )                                  ,
      m_config()
{GUCEF_TRACE;

    Initialize();
}

/*-------------------------------------------------------------------------*/

CPatchEngine::CPatchEngine( void )
    : CORE::CForwardingNotifier()                 ,
      CPatchSetDirEngineEvents()                  ,
      CPatchSetFileEngineEvents()                 ,
      CPatchSetEngineEvents()                     ,
      CPatchListEngineEvents()                    ,
      m_patchListEngine( new CPatchListEngine() ) ,
      m_url()                                     ,
      m_listDataBuffer()                          ,
      m_isActive( false )                         ,
      m_stopSignalGiven( false )                  ,
      m_config()

{GUCEF_TRACE;

    Initialize();
}

/*-------------------------------------------------------------------------*/

void
CPatchEngine::Initialize( void )
{GUCEF_TRACE;

    assert( m_patchListEngine != NULL );

    RegisterEvents();

    // Forward events from the list engine
    AddForwardingForEvent( PatchListProcessingStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchListProcessingProgressEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchListProcessingCompletedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchListProcessingAbortedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchListProcessingFailedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetDataRecievedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetRetrievalStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetRetrievalCompletedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetRetrievalFailedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetRetrievalAbortedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetDecodingFailedEvent, EVENTORIGINFILTER_UNMODIFIED );

    // Forward events from the set engine
    AddForwardingForEvent( PatchSetProcessingStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetProcessingProgressEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetProcessingCompletedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetProcessingAbortedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( PatchSetProcessingFailedEvent, EVENTORIGINFILTER_UNMODIFIED );

    // Forward events from the dir engines
    AddForwardingForEvent( DirProcessingStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( DirProcessingProgressEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( DirProcessingCompletedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( SubDirProcessingStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( SubDirProcessingCompletedEvent, EVENTORIGINFILTER_UNMODIFIED );

    // Forward file engine events
    AddForwardingForEvent( FileListProcessingStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( LocalFileIsOKEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( LocalFileSizeMismatchEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( LocalFileHashMismatchEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( LocalFileNotFoundEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( LocalFileReplacedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileRetrievalStartedEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileRetrievalProgressEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileRetrievalCompleteEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileRetrievalErrorEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileStorageErrorEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileListProcessingCompleteEvent, EVENTORIGINFILTER_UNMODIFIED );
    AddForwardingForEvent( FileListProcessingAbortedEvent, EVENTORIGINFILTER_UNMODIFIED );

    SubscribeTo( &m_url );

    // Subscribe to all events from the patch list engine
    // This should allow us to receive all events that we wish to forward
    SubscribeTo( m_patchListEngine );
}

/*-------------------------------------------------------------------------*/

CPatchEngine::~CPatchEngine()
{GUCEF_TRACE;

    Stop();

    delete m_patchListEngine;
    m_patchListEngine = NULL;
}

/*-------------------------------------------------------------------------*/

void
CPatchEngine::RegisterEvents( void )
{GUCEF_TRACE;

    PatchProcessStartedEvent.Initialize();
    PatchProcessCompletedEvent.Initialize();
    PatchProcessAbortedEvent.Initialize();
    PatchProcessFailedEvent.Initialize();
    PatchListDataReceivedEvent.Initialize();
    PatchListRetrievalStartedEvent.Initialize();
    PatchListRetrievalCompletedEvent.Initialize();
    PatchListRetrievalFailedEvent.Initialize();
    PatchListRetrievalAbortedEvent.Initialize();
    PatchListDecodingFailedEvent.Initialize();
}

/*-------------------------------------------------------------------------*/

CPatchConfig&
CPatchEngine::GetConfig( void )
{GUCEF_TRACE;

    return m_config;
}

/*-------------------------------------------------------------------------*/

const CPatchConfig&
CPatchEngine::GetConfig( void ) const
{GUCEF_TRACE;

    return m_config;
}

/*-------------------------------------------------------------------------*/

bool
CPatchEngine::Start( void )
{GUCEF_TRACE;

    GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Starting" );

    // The user should explicitly stop first if we are already busy
    if ( !m_isActive )
    {
        // configuration sanity check
        if ( ( m_config.GetPatchListURL().Length() > 0 )   &&
             ( m_config.GetPatchListCodec().Length() > 0 ) &&
             ( m_config.GetLocalRootDir().Length() > 0 )    )
        {
            m_isActive = true;
            m_stopSignalGiven = false;
            m_listDataBuffer.Clear();

            NotifyObservers( PatchProcessStartedEvent );

            // We must obtain the patch list before we can use it,..
            // Set the URL for the list location
            if ( m_url.SetURL( m_config.GetPatchListURL() ) )
            {
                // Now we try and obtain it
                NotifyObservers( PatchListRetrievalStartedEvent );
                if ( !m_url.Activate() )
                {
                    NotifyObservers( PatchListRetrievalFailedEvent );
                    NotifyObservers( PatchProcessFailedEvent );
                    return false;
                }

                // Now we wait
                return true;
            }
        }
    }

    NotifyObservers( PatchProcessFailedEvent );
    return false;
}

/*-------------------------------------------------------------------------*/

void
CPatchEngine::Stop( void )
{GUCEF_TRACE;

    GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Stopping" );

    if ( !m_stopSignalGiven && m_isActive )
    {
        m_stopSignalGiven = true;

        m_url.Deactivate();
        m_patchListEngine->Stop();
    }
}

/*-------------------------------------------------------------------------*/

bool
CPatchEngine::IsActive( void ) const
{GUCEF_TRACE;

    return m_isActive;
}

/*-------------------------------------------------------------------------*/

bool
CPatchEngine::ProcessRecievedPatchList( void )
{GUCEF_TRACE;

    GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Processing patch list" );

    // Now we must process the raw patch set data to turn it into something we can use
    // Get the required codec for the current raw patch set data type
    CORE::CDStoreCodecRegistry::TDStoreCodecPtr codecPtr = CORE::CCoreGlobal::Instance()->GetDStoreCodecRegistry().Lookup( m_config.GetPatchListCodec() );
    if ( codecPtr )
    {
        // Prepare vars for the decoding process
        CORE::CDataNode rootNode;
        CORE::CMFileAccess dataAccess( m_listDataBuffer.GetConstBufferPtr() ,
                                       m_listDataBuffer.GetDataSize()       );

        // decode the data in our buffer into a data tree
        if ( codecPtr->BuildDataTree( &rootNode   ,
                                      &dataAccess ) )
        {
            // Now we have to parse the data tree into something more familiar
            CPatchListParser::TPatchList patchList;
            CPatchListParser listParser;
            listParser.ParsePatchList( rootNode  ,
                                       patchList );

            // Now that the raw data has been processed into a real patch list we can commence
            // with the patching process for this patch list
            return m_patchListEngine->Start( patchList                                  ,
                                             m_config.GetLocalRootDir()                 ,
                                             m_config.GetLocalTempStorageRootDir()      ,
                                             m_config.GetStopOnFileReplacementFailure() );
        }
    }

    GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Error while processing patch list" );

    // If we get here then we failed to decode the raw data into a patch set
    NotifyObservers( PatchListDecodingFailedEvent );
    return false;
}

/*-------------------------------------------------------------------------*/

void
CPatchEngine::OnNotify( CORE::CNotifier* notifier                 ,
                        const CORE::CEvent& eventid               ,
                        CORE::CICloneable* eventdata /* = NULL */ )
{GUCEF_TRACE;

    if ( !m_stopSignalGiven && m_isActive )
    {
        // Call base-class version
        CORE::CForwardingNotifier::OnNotify( notifier  ,
                                             eventid   ,
                                             eventdata );

        if ( notifier == m_patchListEngine )
        {
            if ( eventid == PatchListProcessingCompletedEvent )
            {
                // YIHA,.. We are finished
                m_stopSignalGiven = false;
                m_isActive = false;
                NotifyObservers( PatchProcessCompletedEvent );
            }
            else
            if ( eventid == PatchListProcessingFailedEvent )
            {
                // Cascade failure
                m_stopSignalGiven = false;
                m_isActive = false;
                NotifyObservers( PatchProcessFailedEvent );
            }
        }
        else
        if ( notifier == &m_url )
        {
            if ( eventid == CORE::CURL::URLDataRecievedEvent )
            {
                GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Patch list data received" );

                // Translate event data
                const CORE::CDynamicBuffer& buffer = ( static_cast< CORE::CURL::TURLDataRecievedEventData* >( eventdata ) )->GetData();

                // Append the data to our buffer
                m_listDataBuffer.Append( buffer.GetConstBufferPtr() ,
                                         buffer.GetDataSize()       );

                NotifyObservers( PatchListDataReceivedEvent );
            }
            else
            if ( eventid == CORE::CURL::URLAllDataRecievedEvent )
            {
                // The retrieval process of the patch list has been completed
                NotifyObservers( PatchListRetrievalCompletedEvent );

                // Now we must process the received patch list
                if ( !ProcessRecievedPatchList() )
                {
                    NotifyObservers( PatchProcessFailedEvent );
                }
            }
            else
            if ( eventid == CORE::CURL::URLDeactivateEvent )
            {
                GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Aborting patch list retrieval" );

                // Someone has called Stop() while we where busy with our data retrieval
                m_stopSignalGiven = false;
                m_isActive = false;
                NotifyObservers( PatchProcessAbortedEvent );
            }
            else
            if ( eventid == CORE::CURL::URLDataRetrievalErrorEvent )
            {
                GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CPatchEngine: Patch list data retrieval error" );

                // We failed to obtain the patch list data using the URL
                 m_stopSignalGiven = false;
                 m_isActive = false;
                 NotifyObservers( PatchListRetrievalFailedEvent );
                 NotifyObservers( PatchProcessFailedEvent );
            }
        }
    }
    else
    {
        if ( m_stopSignalGiven && m_isActive )
        {
            m_stopSignalGiven = false;
            m_isActive = false;
            NotifyObservers( PatchProcessAbortedEvent );
        }
        else
        if ( ( eventid != CORE::CNotifier::DestructionEvent ) &&
             ( eventid != CORE::CNotifier::UnsubscribeEvent ) &&
             ( eventid != CORE::CNotifier::SubscribeEvent   )  )
        {
            if ( m_config.HasEngineStartTriggerEvent( eventid ) )
            {
                Start();
            }
            else
            if ( m_config.HasEngineStopTriggerEvent( eventid ) )
            {
                Stop();
            }
        }
    }
}

/*-------------------------------------------------------------------------*/

const CString&
CPatchEngine::GetClassTypeName( void ) const
{GUCEF_TRACE;

    static CString typeName = "GUCEF::PATCHER::CPatchEngine";
    return typeName;
}

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

}; /* namespace PATCHER */
}; /* namespace GUCEF */

/*-------------------------------------------------------------------------*/


text:
package com.google.samples.apps.topeka.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.TransitionInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.google.samples.apps.topeka.R;
import com.google.samples.apps.topeka.databinding.ActivityCategorySelectionBinding;
import com.google.samples.apps.topeka.fragment.CategorySelectionFragment;
import com.google.samples.apps.topeka.helper.ApiLevelHelper;
import com.google.samples.apps.topeka.helper.PreferencesHelper;
import com.google.samples.apps.topeka.model.Player;
import com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper;

public class CategorySelectionActivity extends AppCompatActivity {

    private static final String EXTRA_PLAYER = "player";

    public static void start(Activity activity, Player player, ActivityOptionsCompat options) {
        Intent starter = getStartIntent(activity, player);
        ActivityCompat.startActivity(activity, starter, options.toBundle());
    }

    public static void start(Context context, Player player) {
        Intent starter = getStartIntent(context, player);
        context.startActivity(starter);
    }

    @NonNull
    static Intent getStartIntent(Context context, Player player) {
        Intent starter = new Intent(context, CategorySelectionActivity.class);
        starter.putExtra(EXTRA_PLAYER, player);
        return starter;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCategorySelectionBinding binding = DataBindingUtil
                .setContentView(this, R.layout.activity_category_selection);
        Player player = getIntent().getParcelableExtra(EXTRA_PLAYER);
        if (!PreferencesHelper.isSignedIn(this)) {
            if (player == null) {
                player = PreferencesHelper.getPlayer(this);
            } else {
                PreferencesHelper.writeToPreferences(this, player);
            }
        }
        binding.setPlayer(player);
        setUpToolbar();
        if (savedInstanceState == null) {
            attachCategoryGridFragment();
        } else {
            setProgressBarVisibility(View.GONE);
        }
        supportPostponeEnterTransition();
    }

    @Override
    protected void onResume() {
        super.onResume();
        TextView scoreView = (TextView) findViewById(R.id.score);
        final int score = TopekaDatabaseHelper.getScore(this);
        scoreView.setText(getString(R.string.x_points, score));
    }

    private void setUpToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_player);
        setSupportActionBar(toolbar);
        //noinspection ConstantConditions
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_category, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.category_container);
        if (fragment != null) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.sign_out: {
                signOut();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("NewApi")
    private void signOut() {
        PreferencesHelper.signOut(this);
        TopekaDatabaseHelper.reset(this);
        if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
            getWindow().setExitTransition(TransitionInflater.from(this)
                    .inflateTransition(R.transition.category_enter));
        }
        SignInActivity.start(this, false);
        finish();
    }

    private void attachCategoryGridFragment() {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        Fragment fragment = supportFragmentManager.findFragmentById(R.id.category_container);
        if (!(fragment instanceof CategorySelectionFragment)) {
            fragment = CategorySelectionFragment.newInstance();
        }
        supportFragmentManager.beginTransaction()
                .replace(R.id.category_container, fragment)
                .commit();
        setProgressBarVisibility(View.GONE);
    }

    private void setProgressBarVisibility(int visibility) {
        findViewById(R.id.progress).setVisibility(visibility);
    }
}


text:
using System;
using System.Text;

namespace ClosedXML.Excel
{
    internal class XLHFText
    {
        private readonly XLHFItem _hfItem;

        public XLHFText(XLRichString richText, XLHFItem hfItem)
        {
            RichText = richText;
            _hfItem = hfItem;
        }

        public XLRichString RichText { get; private set; }

        public String GetHFText(String prevText)
        {
            var wsFont = _hfItem.HeaderFooter.Worksheet.Style.Font;

            var isRichText = RichText.FontName != null && RichText.FontName != wsFont.FontName
                             || RichText.Bold != wsFont.Bold
                             || RichText.Italic != wsFont.Italic
                             || RichText.Strikethrough != wsFont.Strikethrough
                             || RichText.FontSize > 0 && Math.Abs(RichText.FontSize - wsFont.FontSize) > XLHelper.Epsilon
                             || RichText.VerticalAlignment != wsFont.VerticalAlignment
                             || RichText.Underline != wsFont.Underline
                             || !RichText.FontColor.Equals(wsFont.FontColor);

            if (!isRichText)
                return RichText.Text;

            StringBuilder sb = new StringBuilder();

            if (RichText.FontName != null && RichText.FontName != wsFont.FontName)
                sb.Append("&\"" + RichText.FontName);
            else
                sb.Append("&\"-");

            if (RichText.Bold && RichText.Italic)
                sb.Append(",Bold Italic\"");
            else if (RichText.Bold)
                sb.Append(",Bold\"");
            else if (RichText.Italic)
                sb.Append(",Italic\"");
            else
                sb.Append(",Regular\"");

            if (RichText.FontSize > 0 && Math.Abs(RichText.FontSize - wsFont.FontSize) > XLHelper.Epsilon)
                sb.Append("&" + RichText.FontSize);

            if (RichText.Strikethrough && !wsFont.Strikethrough)
                sb.Append("&S");

            if (RichText.VerticalAlignment != wsFont.VerticalAlignment)
            {
                if (RichText.VerticalAlignment == XLFontVerticalTextAlignmentValues.Subscript)
                    sb.Append("&Y");
                else if (RichText.VerticalAlignment == XLFontVerticalTextAlignmentValues.Superscript)
                    sb.Append("&X");
            }

            if (RichText.Underline != wsFont.Underline)
            {
                if (RichText.Underline == XLFontUnderlineValues.Single)
                    sb.Append("&U");
                else if (RichText.Underline == XLFontUnderlineValues.Double)
                    sb.Append("&E");
            }

            var lastColorPosition = prevText.LastIndexOf("&K");

            if (
                (lastColorPosition >= 0 && !RichText.FontColor.Equals(XLColor.FromHtml("#" + prevText.Substring(lastColorPosition + 2, 6))))
                || (lastColorPosition == -1 && !RichText.FontColor.Equals(wsFont.FontColor))
                )
                sb.Append("&K" + RichText.FontColor.Color.ToHex().Substring(2));

            sb.Append(RichText.Text);

            if (RichText.Underline != wsFont.Underline)
            {
                if (RichText.Underline == XLFontUnderlineValues.Single)
                    sb.Append("&U");
                else if (RichText.Underline == XLFontUnderlineValues.Double)
                    sb.Append("&E");
            }

            if (RichText.VerticalAlignment != wsFont.VerticalAlignment)
            {
                if (RichText.VerticalAlignment == XLFontVerticalTextAlignmentValues.Subscript)
                    sb.Append("&Y");
                else if (RichText.VerticalAlignment == XLFontVerticalTextAlignmentValues.Superscript)
                    sb.Append("&X");
            }

            if (RichText.Strikethrough && !wsFont.Strikethrough)
                sb.Append("&S");

            return sb.ToString();
        }
    }
}


text:
using namespace arangodb;
using namespace arangodb::graph;
using namespace arangodb::traverser;
using namespace arangodb::graph::CacheFactory;

TraverserCache* CacheFactory::CreateCache(arangodb::aql::QueryContext& query,
                                          bool activateDocumentCache,
                                          std::unordered_map<ServerID, aql::EngineId> const* engines,
                                          BaseOptions* opts) {
  if (ServerState::instance()->isCoordinator()) {
    return new ClusterTraverserCache(query, engines, opts);
  }
  if (activateDocumentCache) {
    auto cacheManager =
        query.vocbase().server().getFeature<CacheManagerFeature>().manager();
    if (cacheManager != nullptr) {
      std::shared_ptr<arangodb::cache::Cache> cache =
          cacheManager->createCache(cache::CacheType::Plain);
      if (cache != nullptr) {
        return new TraverserDocumentCache(query, std::move(cache), opts);
      }
    }
    // fallthrough intentional
  }
  return new TraverserCache(query, opts);
}


text:
require 'spec_helper'

describe "notifications/show" do
  before(:each) do
    @notification = assign(:notification, stub_model(Notification,
      :playground_id => 1,
      :name => "Name",
      :description => "MyText",
      :created_by => "Created By",
      :updated_by => "Updated By",
      :owner_id => 2,
      :severity_id => 3,
      :scope_id => 4,
      :business_object_id => 5,
      :odq_unique_id => 6,
      :odq_object_id => 7,
      :closed_at => "",
      :responsible_i => 8
    ))
  end

  it "renders attributes in <p>" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    rendered.should match(/1/)
    rendered.should match(/Name/)
    rendered.should match(/MyText/)
    rendered.should match(/Created By/)
    rendered.should match(/Updated By/)
    rendered.should match(/2/)
    rendered.should match(/3/)
    rendered.should match(/4/)
    rendered.should match(/5/)
    rendered.should match(/6/)
    rendered.should match(/7/)
    rendered.should match(//)
    rendered.should match(/8/)
  end
end


text:
import os
import site
import sys

site.addsitedir('/home/pysg/Envs/pysg/lib/python2.7/site-packages')
activate_this = os.path.expanduser("~/Envs/pysg/bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))
project = '/home/pysg/webapps/pysg_django/myproject/'
workspace = os.path.dirname(project)
sys.path.append(workspace)

from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
application = WSGIHandler()


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.Maps.Routing.Models
{
    public partial class RouteSection
    {
        internal static RouteSection DeserializeRouteSection(JsonElement element)
        {
            Optional<int> startPointIndex = default;
            Optional<int> endPointIndex = default;
            Optional<ResponseSectionType> sectionType = default;
            Optional<ResponseTravelMode> travelMode = default;
            Optional<TrafficIncidentCategory> simpleCategory = default;
            Optional<int> effectiveSpeedInKmh = default;
            Optional<int> delayInSeconds = default;
            Optional<DelayMagnitude> magnitudeOfDelay = default;
            Optional<RouteSectionTec> tec = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("startPointIndex"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    startPointIndex = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("endPointIndex"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    endPointIndex = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("sectionType"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sectionType = new ResponseSectionType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("travelMode"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    travelMode = new ResponseTravelMode(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("simpleCategory"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    simpleCategory = new TrafficIncidentCategory(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("effectiveSpeedInKmh"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    effectiveSpeedInKmh = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("delayInSeconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    delayInSeconds = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("magnitudeOfDelay"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    magnitudeOfDelay = new DelayMagnitude(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("tec"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    tec = RouteSectionTec.DeserializeRouteSectionTec(property.Value);
                    continue;
                }
            }
            return new RouteSection(Optional.ToNullable(startPointIndex), Optional.ToNullable(endPointIndex), Optional.ToNullable(sectionType), Optional.ToNullable(travelMode), Optional.ToNullable(simpleCategory), Optional.ToNullable(effectiveSpeedInKmh), Optional.ToNullable(delayInSeconds), Optional.ToNullable(magnitudeOfDelay), tec.Value);
        }
    }
}


text:
/**
 *
 */
package org.apache.maven.continuum.web.action.notifier;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.model.project.ProjectNotifier;
import org.apache.maven.continuum.web.action.ContinuumActionSupport;
import org.apache.maven.continuum.web.exception.AuthorizationRequiredException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.util.StringUtils;

/**
 * WW action that sets up a new {@link ProjectNotifier} instance for
 * the specified {@link ProjectGroup}.
 *
 * @author Rahul Thakur
 * @since 1.1
 */
@Component( role = com.opensymphony.xwork2.Action.class, hint = "addGroupNotifier", instantiationStrategy = "per-lookup" )
public class AddGroupNotifierAction
    extends ContinuumActionSupport
{
    /**
     * Target {@link ProjectGroup} instance to add the Notifier for.
     */
    private int projectGroupId;

    /**
     * String based type identifier for the {@link ProjectNotifier}.
     */
    private String notifierType;

    private String projectGroupName = "";

    /**
     * Default action method executed in case no method is specified
     * for invocation.
     *
     * @return a String result that determines the control flow.
     */
    public String execute()
        throws ContinuumException
    {
        try
        {
            checkAddProjectGroupNotifierAuthorization( getProjectGroupName() );
        }
        catch ( AuthorizationRequiredException authzE )
        {
            addActionError( authzE.getMessage() );
            return REQUIRES_AUTHORIZATION;
        }

        return notifierType + "_" + INPUT;
    }

    // TODO: Remove this method because a default method return SUCCESS instead of INPUT
    public String doDefault()
        throws ContinuumException
    {
        return input();
    }

    public String input()
        throws ContinuumException
    {
        try
        {
            checkAddProjectGroupNotifierAuthorization( getProjectGroupName() );
        }
        catch ( AuthorizationRequiredException authzE )
        {
            addActionError( authzE.getMessage() );
            return REQUIRES_AUTHORIZATION;
        }

        return INPUT;
    }

    /**
     * Returns the type identifier for the {@link ProjectNotifier} being
     * edited as String.
     *
     * @return notifier type as String.
     */
    public String getNotifierType()
    {
        return notifierType;
    }

    /**
     * Sets the notifier type for the {@link ProjectNotifier} instance
     * being edited.
     *
     * @param notifierType notifier type to set.
     */
    public void setNotifierType( String notifierType )
    {
        this.notifierType = notifierType;
    }

    /**
     * Returns the current {@link ProjectGroup} Identifier.
     *
     * @return the projectGroupId
     */
    public int getProjectGroupId()
    {
        return projectGroupId;
    }

    /**
     * Sets the Id for the target {@link ProjectGroup}.
     *
     * @param projectGroupId the projectGroupId to set
     */
    public void setProjectGroupId( int projectGroupId )
    {
        this.projectGroupId = projectGroupId;
    }

    public String getProjectGroupName()
        throws ContinuumException
    {
        if ( StringUtils.isEmpty( projectGroupName ) )
        {
            projectGroupName = getContinuum().getProjectGroup( projectGroupId ).getName();
        }

        return projectGroupName;
    }
}


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2019 Ryo Suzuki
//	Copyright (c) 2016-2019 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3DEngine.hpp>
# include <Renderer2D/IRenderer2D.hpp>
# include <Siv3D/Texture.hpp>
# include <Siv3D/TexturedQuad.hpp>
# include <Siv3D/FloatQuad.hpp>

namespace s3d
{
	TexturedQuad::TexturedQuad()
	{

	}

	TexturedQuad::TexturedQuad(
		const Texture& _texture,
		float l,
		float t,
		float r,
		float b,
		const Quad& _quad,
		const Float2& _center)
		: quad(_quad)
		, texture(_texture)
		, uvRect(l, t, r, b)
		, center(_center)
	{

	}

	TexturedQuad::TexturedQuad(
		const Texture& _texture,
		const FloatRect& _uvRect,
		const Quad& _quad,
		const Float2& _center)
		: quad(_quad)
		, texture(_texture)
		, uvRect(_uvRect)
		, center(_center)
	{

	}

	const Quad& TexturedQuad::draw(const ColorF& diffuse) const
	{
		Siv3DEngine::Get<ISiv3DRenderer2D>()->addTexturedQuad(texture, quad, uvRect, diffuse.toFloat4());

		return quad;
	}

	Quad TexturedQuad::draw(const double x, const double y, const ColorF& diffuse) const
	{
		const Quad q = quad.movedBy(x, y);

		Siv3DEngine::Get<ISiv3DRenderer2D>()->addTexturedQuad(texture, q, uvRect, diffuse.toFloat4());

		return q;
	}

	Quad TexturedQuad::draw(const Vec2& pos, const ColorF& diffuse) const
	{
		return draw(pos.x, pos.y, diffuse);
	}

	Quad TexturedQuad::drawAt(const double x, const double y, const ColorF& diffuse) const
	{
		const Quad q = quad.movedBy(x - center.x, y - center.y);

		Siv3DEngine::Get<ISiv3DRenderer2D>()->addTexturedQuad(texture, q, uvRect, diffuse.toFloat4());

		return q;
	}

	Quad TexturedQuad::drawAt(const Vec2& pos, const ColorF& diffuse) const
	{
		return drawAt(pos.x, pos.y, diffuse);
	}
}


text:
=============
Configuration
=============

Mezzanine provides a central system for defining settings within
your project and applications that can then be edited by admin users.
The package ``mezzanine.conf`` contains the models for storing
editable settings in the database as well as the functions for
registering and loading these settings throughout your project.

Registering Settings
====================

Settings are defined by creating a module named ``defaults.py`` inside
one or more of the applications defined in your project's
``settings.INSTALLED_APPS`` setting. Inside your ``defaults.py`` module
you then call the function ``mezzanine.conf.register_setting`` for
each setting you want to define which takes four keyword arguments:

  * ``name``: The name of the setting.
  * ``description``: The description of the setting.
  * ``editable``: If ``True``, the setting will be editable via the admin.
  * ``default``: The default value of the setting.
  * ``choices``: A list of choices the user can select from when the
    setting is editable.
  * ``append``: If registering an existing setting, the default value
    given will be appended to the current.

.. note::

    For settings registered with ``editable`` as ``True``, currently only
    strings, integers/floats and boolean values are supported for the
    ``default`` value.

For example suppose we had a ``authors`` application and we wanted to
create a setting that controls the number of books displayed per author
page, we would define the following in ``authors.defaults``::

    from mezzanine.conf import register_setting

    register_setting(
        name="AUTHORS_BOOKS_PER_PAGE",
        description="The number of books to show per author page.",
        editable=True,
        default=10,
    )

Reading Settings
================

Mezzanine provides a settings object via ``mezzanine.conf.settings`` in a
similar way to Django's ``django.conf.settings``. This settings object
contains each of the settings registered above using their names as
attributes. The settings object also contains the method ``use_editable``
which when called will cause the settings object to reload editable settings
from the database the next time an editable setting is accessed. Continuing
on from our previous example, suppose we have a view for photos::

    from django.shortcuts import render
    from mezzanine.conf import settings
    from .models import Book

    def books_view(request):
        settings.use_editable()
        books = Book.objects.all()[:settings.AUTHORS_BOOKS_PER_PAGE]
        return render(request, "books.html", {"books": books})

When defining editable settings, care should be taken when considering
where in your project the setting will be used. For example if a setting
is used in a ``urlpattern`` or the creation of a ``model`` class it would
only be read when your site is first loaded, and therefore having it
change at a later point by an admin user would not have any effect without
reloading your entire project. In the snippet above by calling
``settings.use_editable()`` within the view, the value of the setting being
accessed is loaded each time the view is run. This ensures that if the value
of the setting has been changed by an admin user it will be reflected on the
website.

Django Settings
===============

Mezzanine's settings object integrates with Django's settings object in a
couple of ways.

Firstly it's possible to override the default value for any setting defined
using ``mezzanine.conf.register_setting`` by adding its name and value as
a regular setting to your project's settings module. This is especially useful
when any of your project's ``INSTALLED_APPS`` (including Mezzanine
itself) register settings that aren't editable and you want to override
these settings without modifying the application that registered them.

Secondly it's possible to access any of the settings defined by Django or
your project's settings module via Mezzanine's settings object in the same
way you would use Django's settings object. This allows for a single access
point for all settings regardless of how they are defined.

Default Settings
================

Mezzanine defines the following settings:

.. include:: settings.rst


text:
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;

namespace HETSAPI.Migrations
{
    public partial class HETS4951 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "HET_GROUP_MEMBERSHIP");

            migrationBuilder.DropTable(
                name: "HET_LOOKUP_LIST");

            migrationBuilder.DropTable(
                name: "HET_GROUP");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "HET_GROUP",
                columns: table => new
                {
                    GROUP_ID = table.Column<int>(nullable: false)
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
                    APP_CREATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    APP_CREATE_USER_DIRECTORY = table.Column<string>(maxLength: 50, nullable: true),
                    APP_CREATE_USER_GUID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_CREATE_USERID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_LAST_UPDATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    APP_LAST_UPDATE_USER_DIRECTORY = table.Column<string>(maxLength: 50, nullable: true),
                    APP_LAST_UPDATE_USER_GUID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_LAST_UPDATE_USERID = table.Column<string>(maxLength: 255, nullable: true),
                    DB_CREATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    DB_CREATE_USER_ID = table.Column<string>(maxLength: 63, nullable: true),
                    DB_LAST_UPDATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    DB_LAST_UPDATE_USER_ID = table.Column<string>(maxLength: 63, nullable: true),
                    DESCRIPTION = table.Column<string>(maxLength: 2048, nullable: true),
                    NAME = table.Column<string>(maxLength: 150, nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_HET_GROUP", x => x.GROUP_ID);
                });

            migrationBuilder.CreateTable(
                name: "HET_LOOKUP_LIST",
                columns: table => new
                {
                    LOOKUP_LIST_ID = table.Column<int>(nullable: false)
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
                    APP_CREATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    APP_CREATE_USER_DIRECTORY = table.Column<string>(maxLength: 50, nullable: true),
                    APP_CREATE_USER_GUID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_CREATE_USERID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_LAST_UPDATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    APP_LAST_UPDATE_USER_DIRECTORY = table.Column<string>(maxLength: 50, nullable: true),
                    APP_LAST_UPDATE_USER_GUID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_LAST_UPDATE_USERID = table.Column<string>(maxLength: 255, nullable: true),
                    CODE_NAME = table.Column<string>(maxLength: 30, nullable: true),
                    CONTEXT_NAME = table.Column<string>(maxLength: 100, nullable: true),
                    DB_CREATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    DB_CREATE_USER_ID = table.Column<string>(maxLength: 63, nullable: true),
                    DB_LAST_UPDATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    DB_LAST_UPDATE_USER_ID = table.Column<string>(maxLength: 63, nullable: true),
                    DISPLAY_SORT_ORDER = table.Column<int>(nullable: true),
                    IS_DEFAULT = table.Column<bool>(nullable: false),
                    VALUE = table.Column<string>(maxLength: 100, nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_HET_LOOKUP_LIST", x => x.LOOKUP_LIST_ID);
                });

            migrationBuilder.CreateTable(
                name: "HET_GROUP_MEMBERSHIP",
                columns: table => new
                {
                    GROUP_MEMBERSHIP_ID = table.Column<int>(nullable: false)
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
                    ACTIVE = table.Column<bool>(nullable: false),
                    APP_CREATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    APP_CREATE_USER_DIRECTORY = table.Column<string>(maxLength: 50, nullable: true),
                    APP_CREATE_USER_GUID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_CREATE_USERID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_LAST_UPDATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    APP_LAST_UPDATE_USER_DIRECTORY = table.Column<string>(maxLength: 50, nullable: true),
                    APP_LAST_UPDATE_USER_GUID = table.Column<string>(maxLength: 255, nullable: true),
                    APP_LAST_UPDATE_USERID = table.Column<string>(maxLength: 255, nullable: true),
                    DB_CREATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    DB_CREATE_USER_ID = table.Column<string>(maxLength: 63, nullable: true),
                    DB_LAST_UPDATE_TIMESTAMP = table.Column<DateTime>(nullable: false),
                    DB_LAST_UPDATE_USER_ID = table.Column<string>(maxLength: 63, nullable: true),
                    GROUP_ID = table.Column<int>(nullable: true),
                    USER_ID = table.Column<int>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_HET_GROUP_MEMBERSHIP", x => x.GROUP_MEMBERSHIP_ID);
                    table.ForeignKey(
                        name: "FK_HET_GROUP_MEMBERSHIP_HET_GROUP_GROUP_ID",
                        column: x => x.GROUP_ID,
                        principalTable: "HET_GROUP",
                        principalColumn: "GROUP_ID",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_HET_GROUP_MEMBERSHIP_HET_USER_USER_ID",
                        column: x => x.USER_ID,
                        principalTable: "HET_USER",
                        principalColumn: "USER_ID",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "IX_HET_GROUP_MEMBERSHIP_GROUP_ID",
                table: "HET_GROUP_MEMBERSHIP",
                column: "GROUP_ID");

            migrationBuilder.CreateIndex(
                name: "IX_HET_GROUP_MEMBERSHIP_USER_ID",
                table: "HET_GROUP_MEMBERSHIP",
                column: "USER_ID");
        }
    }
}


text:
'use strict';
const common = require('../common');
const assert = require('assert');
const httpCommon = require('_http_common');
const { HTTPParser } = require('_http_common');
const net = require('net');

const COUNT = httpCommon.parsers.max + 1;

const parsers = new Array(COUNT);
for (let i = 0; i < parsers.length; i++)
  parsers[i] = httpCommon.parsers.alloc();

let gotRequests = 0;
let gotResponses = 0;

function execAndClose() {
  if (parsers.length === 0)
    return;
  process.stdout.write('.');

  const parser = parsers.pop();
  parser.initialize(HTTPParser.RESPONSE, {});

  const socket = net.connect(common.PORT);
  socket.on('error', (e) => {
    // If SmartOS and ECONNREFUSED, then retry. See
    // https://github.com/nodejs/node/issues/2663.
    if (common.isSunOS && e.code === 'ECONNREFUSED') {
      parsers.push(parser);
      parser.reused = true;
      socket.destroy();
      setImmediate(execAndClose);
      return;
    }
    throw e;
  });

  parser.consume(socket._handle);

  parser.onIncoming = function onIncoming() {
    process.stdout.write('+');
    gotResponses++;
    parser.unconsume();
    httpCommon.freeParser(parser);
    socket.destroy();
    setImmediate(execAndClose);
  };
}

const server = net.createServer(function(c) {
  if (++gotRequests === COUNT)
    server.close();
  c.end('HTTP/1.1 200 OK\r\n\r\n', function() {
    c.destroySoon();
  });
}).listen(common.PORT, execAndClose);

process.on('exit', function() {
  assert.strictEqual(gotResponses, COUNT);
});


text:
package no.nextgentel.oss.akkatools.persistence.jdbcjournal

import java.time.{OffsetDateTime, ZoneId}
import java.util.Date
import javax.sql.DataSource

import no.nextgentel.oss.akkatools.cluster.ClusterNodeRepo
import org.slf4j.LoggerFactory
import org.sql2o.data.{Row, Table}
import org.sql2o._
import org.sql2o.quirks.OracleQuirks

import scala.concurrent.duration.FiniteDuration

case class JournalEntryDto(typePath:String, uniqueId:String, sequenceNr:Long, persistentRepr:Array[Byte], payloadWriteOnly:String, timestamp:OffsetDateTime)
case class SnapshotEntry(persistenceId:String, sequenceNr:Long, timestamp:Long, snapshot:Array[Byte], manifest:String, serializerId:Option[Int])

trait StorageRepo {
  def insertPersistentReprList(dtoList: Seq[JournalEntryDto])

  def deleteJournalEntryTo(persistenceId: PersistenceIdSingle, toSequenceNr: Long)

  def loadJournalEntries(persistenceId: PersistenceId, fromSequenceNr: Long, toSequenceNr: Long, max: Long): List[JournalEntryDto]

  def findHighestSequenceNr(persistenceId: PersistenceId, fromSequenceNr: Long): Long

  def writeSnapshot(snapshotEntry: SnapshotEntry)

  def findSnapshotEntry(persistenceId: String, maxSequenceNr: Long, maxTimestamp: Long): Option[SnapshotEntry]

  def deleteSnapshot(persistenceId: String, sequenceNr: Long, timestamp: Long)

  def deleteSnapshotsMatching(persistenceId: String, maxSequenceNr: Long, maxTimestamp: Long)
}

trait StorageRepoWithClusterNodeRepo extends StorageRepo with ClusterNodeRepo

trait JdbcJournalErrorHandler {
  def onError(e:Exception)
}

class JdbcJournalDetectFatalOracleErrorHandler(fatalErrorHandler:JdbcJournalErrorHandler) extends JdbcJournalErrorHandler {
  override def onError(e: Exception): Unit = {
    if (e.getMessage != null && e.getMessage.contains("ORA-00001: unique constraint")) {
      fatalErrorHandler.onError(e)
    }
  }
}

case class StorageRepoConfig
(
  schemaName: Option[String] = None,
  tableName_journal:String = "t_journal",
  sequenceName_journalIndex:String = "s_journalIndex_seq",
  tableName_snapshot:String = "t_snapshot"

)