text:
"""Bitcoin test framework primitive and message structures

CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....:
    data structures that should map to corresponding structures in
    bitcoin/primitives

msg_block, msg_tx, msg_headers, etc.:
    data structures that represent network messages

ser_*, deser_*: functions that handle serialization/deserialization.

Classes use __slots__ to ensure extraneous attributes aren't accidentally added
by tests, compromising their intended effect.
"""
from base64 import b32decode, b32encode
import copy
import hashlib
from io import BytesIO
import math
import random
import socket
import struct
import time

from test_framework.siphash import siphash256
from test_framework.util import assert_equal

MAX_LOCATOR_SZ = 101
MAX_BLOCK_WEIGHT = 4000000
MAX_BLOOM_FILTER_SIZE = 36000
MAX_BLOOM_HASH_FUNCS = 50

COIN = 100000000  # 1 btc in satoshis
MAX_MONEY = 21000000 * COIN

BIP125_SEQUENCE_NUMBER = 0xfffffffd  # Sequence number that is rbf-opt-in (BIP 125) and csv-opt-out (BIP 68)

MAX_PROTOCOL_MESSAGE_LENGTH = 4000000  # Maximum length of incoming protocol messages
MAX_HEADERS_RESULTS = 2000  # Number of headers sent in one getheaders result
MAX_INV_SIZE = 50000  # Maximum number of entries in an 'inv' protocol message

NODE_NETWORK = (1 << 0)
NODE_BLOOM = (1 << 2)
NODE_WITNESS = (1 << 3)
NODE_COMPACT_FILTERS = (1 << 6)
NODE_NETWORK_LIMITED = (1 << 10)

MSG_TX = 1
MSG_BLOCK = 2
MSG_FILTERED_BLOCK = 3
MSG_CMPCT_BLOCK = 4
MSG_WTX = 5
MSG_WITNESS_FLAG = 1 << 30
MSG_TYPE_MASK = 0xffffffff >> 2
MSG_WITNESS_TX = MSG_TX | MSG_WITNESS_FLAG

FILTER_TYPE_BASIC = 0

WITNESS_SCALE_FACTOR = 4

# Serialization/deserialization tools
def sha256(s):
    return hashlib.new('sha256', s).digest()

def hash256(s):
    return sha256(sha256(s))

def ser_compact_size(l):
    r = b""
    if l < 253:
        r = struct.pack("B", l)
    elif l < 0x10000:
        r = struct.pack("<BH", 253, l)
    elif l < 0x100000000:
        r = struct.pack("<BI", 254, l)
    else:
        r = struct.pack("<BQ", 255, l)
    return r

def deser_compact_size(f):
    nit = struct.unpack("<B", f.read(1))[0]
    if nit == 253:
        nit = struct.unpack("<H", f.read(2))[0]
    elif nit == 254:
        nit = struct.unpack("<I", f.read(4))[0]
    elif nit == 255:
        nit = struct.unpack("<Q", f.read(8))[0]
    return nit

def deser_string(f):
    nit = deser_compact_size(f)
    return f.read(nit)

def ser_string(s):
    return ser_compact_size(len(s)) + s

def deser_uint256(f):
    r = 0
    for i in range(8):
        t = struct.unpack("<I", f.read(4))[0]
        r += t << (i * 32)
    return r

def ser_uint256(u):
    rs = b""
    for _ in range(8):
        rs += struct.pack("<I", u & 0xFFFFFFFF)
        u >>= 32
    return rs

def uint256_from_str(s):
    r = 0
    t = struct.unpack("<IIIIIIII", s[:32])
    for i in range(8):
        r += t[i] << (i * 32)
    return r

def uint256_from_compact(c):
    nbytes = (c >> 24) & 0xFF
    v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
    return v

# deser_function_name: Allow for an alternate deserialization function on the
# entries in the vector.
def deser_vector(f, c, deser_function_name=None):
    nit = deser_compact_size(f)
    r = []
    for _ in range(nit):
        t = c()
        if deser_function_name:
            getattr(t, deser_function_name)(f)
        else:
            t.deserialize(f)
        r.append(t)
    return r

# ser_function_name: Allow for an alternate serialization function on the
# entries in the vector (we use this for serializing the vector of transactions
# for a witness block).
def ser_vector(l, ser_function_name=None):
    r = ser_compact_size(len(l))
    for i in l:
        if ser_function_name:
            r += getattr(i, ser_function_name)()
        else:
            r += i.serialize()
    return r

def deser_uint256_vector(f):
    nit = deser_compact_size(f)
    r = []
    for _ in range(nit):
        t = deser_uint256(f)
        r.append(t)
    return r

def ser_uint256_vector(l):
    r = ser_compact_size(len(l))
    for i in l:
        r += ser_uint256(i)
    return r

def deser_string_vector(f):
    nit = deser_compact_size(f)
    r = []
    for _ in range(nit):
        t = deser_string(f)
        r.append(t)
    return r

def ser_string_vector(l):
    r = ser_compact_size(len(l))
    for sv in l:
        r += ser_string(sv)
    return r

def from_hex(obj, hex_string):
    """Deserialize from a hex string representation (e.g. from RPC)

    Note that there is no complementary helper like e.g. `to_hex` for the
    inverse operation. To serialize a message object to a hex string, simply
    use obj.serialize().hex()"""
    obj.deserialize(BytesIO(bytes.fromhex(hex_string)))
    return obj

def tx_from_hex(hex_string):
    """Deserialize from hex string to a transaction object"""
    return from_hex(CTransaction(), hex_string)

# Objects that map to bitcoind objects, which can be serialized/deserialized

class CAddress:
    __slots__ = ("net", "ip", "nServices", "port", "time")

    # see https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki
    NET_IPV4 = 1
    NET_I2P = 5

    ADDRV2_NET_NAME = {
        NET_IPV4: "IPv4",
        NET_I2P: "I2P"
    }

    ADDRV2_ADDRESS_LENGTH = {
        NET_IPV4: 4,
        NET_I2P: 32
    }

    I2P_PAD = "===="

    def __init__(self):
        self.time = 0
        self.nServices = 1
        self.net = self.NET_IPV4
        self.ip = "0.0.0.0"
        self.port = 0

    def __eq__(self, other):
        return self.net == other.net and self.ip == other.ip and self.nServices == other.nServices and self.port == other.port and self.time == other.time

    def deserialize(self, f, *, with_time=True):
        """Deserialize from addrv1 format (pre-BIP155)"""
        if with_time:
            # VERSION messages serialize CAddress objects without time
            self.time = struct.unpack("<I", f.read(4))[0]
        self.nServices = struct.unpack("<Q", f.read(8))[0]
        # We only support IPv4 which means skip 12 bytes and read the next 4 as IPv4 address.
        f.read(12)
        self.net = self.NET_IPV4
        self.ip = socket.inet_ntoa(f.read(4))
        self.port = struct.unpack(">H", f.read(2))[0]

    def serialize(self, *, with_time=True):
        """Serialize in addrv1 format (pre-BIP155)"""
        assert self.net == self.NET_IPV4
        r = b""
        if with_time:
            # VERSION messages serialize CAddress objects without time
            r += struct.pack("<I", self.time)
        r += struct.pack("<Q", self.nServices)
        r += b"\x00" * 10 + b"\xff" * 2
        r += socket.inet_aton(self.ip)
        r += struct.pack(">H", self.port)
        return r

    def deserialize_v2(self, f):
        """Deserialize from addrv2 format (BIP155)"""
        self.time = struct.unpack("<I", f.read(4))[0]

        self.nServices = deser_compact_size(f)

        self.net = struct.unpack("B", f.read(1))[0]
        assert self.net in (self.NET_IPV4, self.NET_I2P)

        address_length = deser_compact_size(f)
        assert address_length == self.ADDRV2_ADDRESS_LENGTH[self.net]

        addr_bytes = f.read(address_length)
        if self.net == self.NET_IPV4:
            self.ip = socket.inet_ntoa(addr_bytes)
        else:
            self.ip = b32encode(addr_bytes)[0:-len(self.I2P_PAD)].decode("ascii").lower() + ".b32.i2p"

        self.port = struct.unpack(">H", f.read(2))[0]

    def serialize_v2(self):
        """Serialize in addrv2 format (BIP155)"""
        assert self.net in (self.NET_IPV4, self.NET_I2P)
        r = b""
        r += struct.pack("<I", self.time)
        r += ser_compact_size(self.nServices)
        r += struct.pack("B", self.net)
        r += ser_compact_size(self.ADDRV2_ADDRESS_LENGTH[self.net])
        if self.net == self.NET_IPV4:
            r += socket.inet_aton(self.ip)
        else:
            sfx = ".b32.i2p"
            assert self.ip.endswith(sfx)
            r += b32decode(self.ip[0:-len(sfx)] + self.I2P_PAD, True)
        r += struct.pack(">H", self.port)
        return r

    def __repr__(self):
        return ("CAddress(nServices=%i net=%s addr=%s port=%i)"
                % (self.nServices, self.ADDRV2_NET_NAME[self.net], self.ip, self.port))

class CInv:
    __slots__ = ("hash", "type")

    typemap = {
        0: "Error",
        MSG_TX: "TX",
        MSG_BLOCK: "Block",
        MSG_TX | MSG_WITNESS_FLAG: "WitnessTx",
        MSG_BLOCK | MSG_WITNESS_FLAG: "WitnessBlock",
        MSG_FILTERED_BLOCK: "filtered Block",
        MSG_CMPCT_BLOCK: "CompactBlock",
        MSG_WTX: "WTX",
    }

    def __init__(self, t=0, h=0):
        self.type = t
        self.hash = h

    def deserialize(self, f):
        self.type = struct.unpack("<I", f.read(4))[0]
        self.hash = deser_uint256(f)

    def serialize(self):
        r = b""
        r += struct.pack("<I", self.type)
        r += ser_uint256(self.hash)
        return r

    def __repr__(self):
        return "CInv(type=%s hash=%064x)" \
            % (self.typemap[self.type], self.hash)

    def __eq__(self, other):
        return isinstance(other, CInv) and self.hash == other.hash and self.type == other.type

class CBlockLocator:
    __slots__ = ("nVersion", "vHave")

    def __init__(self):
        self.vHave = []

    def deserialize(self, f):
        struct.unpack("<i", f.read(4))[0]  # Ignore version field.
        self.vHave = deser_uint256_vector(f)

    def serialize(self):
        r = b""
        r += struct.pack("<i", 0)  # Bitcoin Core ignores version field. Set it to 0.
        r += ser_uint256_vector(self.vHave)
        return r

    def __repr__(self):
        return "CBlockLocator(vHave=%s)" % (repr(self.vHave))

class COutPoint:
    __slots__ = ("hash", "n")

    def __init__(self, hash=0, n=0):
        self.hash = hash
        self.n = n

    def deserialize(self, f):
        self.hash = deser_uint256(f)
        self.n = struct.unpack("<I", f.read(4))[0]

    def serialize(self):
        r = b""
        r += ser_uint256(self.hash)
        r += struct.pack("<I", self.n)
        return r

    def __repr__(self):
        return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n)

class CTxIn:
    __slots__ = ("nSequence", "prevout", "scriptSig")

    def __init__(self, outpoint=None, scriptSig=b"", nSequence=0):
        if outpoint is None:
            self.prevout = COutPoint()
        else:
            self.prevout = outpoint
        self.scriptSig = scriptSig
        self.nSequence = nSequence

    def deserialize(self, f):
        self.prevout = COutPoint()
        self.prevout.deserialize(f)
        self.scriptSig = deser_string(f)
        self.nSequence = struct.unpack("<I", f.read(4))[0]

    def serialize(self):
        r = b""
        r += self.prevout.serialize()
        r += ser_string(self.scriptSig)
        r += struct.pack("<I", self.nSequence)
        return r

    def __repr__(self):
        return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \
            % (repr(self.prevout), self.scriptSig.hex(),
               self.nSequence)

class CTxOut:
    __slots__ = ("nValue", "scriptPubKey")

    def __init__(self, nValue=0, scriptPubKey=b""):
        self.nValue = nValue
        self.scriptPubKey = scriptPubKey

    def deserialize(self, f):
        self.nValue = struct.unpack("<q", f.read(8))[0]
        self.scriptPubKey = deser_string(f)

    def serialize(self):
        r = b""
        r += struct.pack("<q", self.nValue)
        r += ser_string(self.scriptPubKey)
        return r

    def __repr__(self):
        return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \
            % (self.nValue // COIN, self.nValue % COIN,
               self.scriptPubKey.hex())

class CScriptWitness:
    __slots__ = ("stack",)

    def __init__(self):
        # stack is a vector of strings
        self.stack = []

    def __repr__(self):
        return "CScriptWitness(%s)" % \
               (",".join([x.hex() for x in self.stack]))

    def is_null(self):
        if self.stack:
            return False
        return True

class CTxInWitness:
    __slots__ = ("scriptWitness",)

    def __init__(self):
        self.scriptWitness = CScriptWitness()

    def deserialize(self, f):
        self.scriptWitness.stack = deser_string_vector(f)

    def serialize(self):
        return ser_string_vector(self.scriptWitness.stack)

    def __repr__(self):
        return repr(self.scriptWitness)

    def is_null(self):
        return self.scriptWitness.is_null()

class CTxWitness:
    __slots__ = ("vtxinwit",)

    def __init__(self):
        self.vtxinwit = []

    def deserialize(self, f):
        for i in range(len(self.vtxinwit)):
            self.vtxinwit[i].deserialize(f)

    def serialize(self):
        r = b""
        # This is different than the usual vector serialization --
        # we omit the length of the vector, which is required to be
        # the same length as the transaction's vin vector.
        for x in self.vtxinwit:
            r += x.serialize()
        return r

    def __repr__(self):
        return "CTxWitness(%s)" % \
               (';'.join([repr(x) for x in self.vtxinwit]))

    def is_null(self):
        for x in self.vtxinwit:
            if not x.is_null():
                return False
        return True

class CTransaction:
    __slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout",
                 "wit")

    def __init__(self, tx=None):
        if tx is None:
            self.nVersion = 1
            self.vin = []
            self.vout = []
            self.wit = CTxWitness()
            self.nLockTime = 0
            self.sha256 = None
            self.hash = None
        else:
            self.nVersion = tx.nVersion
            self.vin = copy.deepcopy(tx.vin)
            self.vout = copy.deepcopy(tx.vout)
            self.nLockTime = tx.nLockTime
            self.sha256 = tx.sha256
            self.hash = tx.hash
            self.wit = copy.deepcopy(tx.wit)

    def deserialize(self, f):
        self.nVersion = struct.unpack("<i", f.read(4))[0]
        self.vin = deser_vector(f, CTxIn)
        flags = 0
        if len(self.vin) == 0:
            flags = struct.unpack("<B", f.read(1))[0]
            # Not sure why flags can't be zero, but this
            # matches the implementation in bitcoind
            if (flags != 0):
                self.vin = deser_vector(f, CTxIn)
                self.vout = deser_vector(f, CTxOut)
        else:
            self.vout = deser_vector(f, CTxOut)
        if flags != 0:
            self.wit.vtxinwit = [CTxInWitness() for _ in range(len(self.vin))]
            self.wit.deserialize(f)
        else:
            self.wit = CTxWitness()
        self.nLockTime = struct.unpack("<I", f.read(4))[0]
        self.sha256 = None
        self.hash = None

    def serialize_without_witness(self):
        r = b""
        r += struct.pack("<i", self.nVersion)
        r += ser_vector(self.vin)
        r += ser_vector(self.vout)
        r += struct.pack("<I", self.nLockTime)
        return r

    # Only serialize with witness when explicitly called for
    def serialize_with_witness(self):
        flags = 0
        if not self.wit.is_null():
            flags |= 1
        r = b""
        r += struct.pack("<i", self.nVersion)
        if flags:
            dummy = []
            r += ser_vector(dummy)
            r += struct.pack("<B", flags)
        r += ser_vector(self.vin)
        r += ser_vector(self.vout)
        if flags & 1:
            if (len(self.wit.vtxinwit) != len(self.vin)):
                # vtxinwit must have the same length as vin
                self.wit.vtxinwit = self.wit.vtxinwit[:len(self.vin)]
                for _ in range(len(self.wit.vtxinwit), len(self.vin)):
                    self.wit.vtxinwit.append(CTxInWitness())
            r += self.wit.serialize()
        r += struct.pack("<I", self.nLockTime)
        return r

    # Regular serialization is with witness -- must explicitly
    # call serialize_without_witness to exclude witness data.
    def serialize(self):
        return self.serialize_with_witness()

    def getwtxid(self):
        return hash256(self.serialize())[::-1].hex()

    # Recalculate the txid (transaction hash without witness)
    def rehash(self):
        self.sha256 = None
        self.calc_sha256()
        return self.hash

    # We will only cache the serialization without witness in
    # self.sha256 and self.hash -- those are expected to be the txid.
    def calc_sha256(self, with_witness=False):
        if with_witness:
            # Don't cache the result, just return it
            return uint256_from_str(hash256(self.serialize_with_witness()))

        if self.sha256 is None:
            self.sha256 = uint256_from_str(hash256(self.serialize_without_witness()))
        self.hash = hash256(self.serialize_without_witness())[::-1].hex()

    def is_valid(self):
        self.calc_sha256()
        for tout in self.vout:
            if tout.nValue < 0 or tout.nValue > 21000000 * COIN:
                return False
        return True

    # Calculate the transaction weight using witness and non-witness
    # serialization size (does NOT use sigops).
    def get_weight(self):
        with_witness_size = len(self.serialize_with_witness())
        without_witness_size = len(self.serialize_without_witness())
        return (WITNESS_SCALE_FACTOR - 1) * without_witness_size + with_witness_size

    def get_vsize(self):
        return math.ceil(self.get_weight() / WITNESS_SCALE_FACTOR)

    def __repr__(self):
        return "CTransaction(nVersion=%i vin=%s vout=%s wit=%s nLockTime=%i)" \
            % (self.nVersion, repr(self.vin), repr(self.vout), repr(self.wit), self.nLockTime)

class CBlockHeader:
    __slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce",
                 "nTime", "nVersion", "sha256")

    def __init__(self, header=None):
        if header is None:
            self.set_null()
        else:
            self.nVersion = header.nVersion
            self.hashPrevBlock = header.hashPrevBlock
            self.hashMerkleRoot = header.hashMerkleRoot
            self.nTime = header.nTime
            self.nBits = header.nBits
            self.nNonce = header.nNonce
            self.sha256 = header.sha256
            self.hash = header.hash
            self.calc_sha256()

    def set_null(self):
        self.nVersion = 4
        self.hashPrevBlock = 0
        self.hashMerkleRoot = 0
        self.nTime = 0
        self.nBits = 0
        self.nNonce = 0
        self.sha256 = None
        self.hash = None

    def deserialize(self, f):
        self.nVersion = struct.unpack("<i", f.read(4))[0]
        self.hashPrevBlock = deser_uint256(f)
        self.hashMerkleRoot = deser_uint256(f)
        self.nTime = struct.unpack("<I", f.read(4))[0]
        self.nBits = struct.unpack("<I", f.read(4))[0]
        self.nNonce = struct.unpack("<I", f.read(4))[0]
        self.sha256 = None
        self.hash = None

    def serialize(self):
        r = b""
        r += struct.pack("<i", self.nVersion)
        r += ser_uint256(self.hashPrevBlock)
        r += ser_uint256(self.hashMerkleRoot)
        r += struct.pack("<I", self.nTime)
        r += struct.pack("<I", self.nBits)
        r += struct.pack("<I", self.nNonce)
        return r

    def calc_sha256(self):
        if self.sha256 is None:
            r = b""
            r += struct.pack("<i", self.nVersion)
            r += ser_uint256(self.hashPrevBlock)
            r += ser_uint256(self.hashMerkleRoot)
            r += struct.pack("<I", self.nTime)
            r += struct.pack("<I", self.nBits)
            r += struct.pack("<I", self.nNonce)
            self.sha256 = uint256_from_str(hash256(r))
            self.hash = hash256(r)[::-1].hex()

    def rehash(self):
        self.sha256 = None
        self.calc_sha256()
        return self.sha256

    def __repr__(self):
        return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x)" \
            % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
               time.ctime(self.nTime), self.nBits, self.nNonce)

BLOCK_HEADER_SIZE = len(CBlockHeader().serialize())
assert_equal(BLOCK_HEADER_SIZE, 80)

class CBlock(CBlockHeader):
    __slots__ = ("vtx",)

    def __init__(self, header=None):
        super().__init__(header)
        self.vtx = []

    def deserialize(self, f):
        super().deserialize(f)
        self.vtx = deser_vector(f, CTransaction)

    def serialize(self, with_witness=True):
        r = b""
        r += super().serialize()
        if with_witness:
            r += ser_vector(self.vtx, "serialize_with_witness")
        else:
            r += ser_vector(self.vtx, "serialize_without_witness")
        return r

    # Calculate the merkle root given a vector of transaction hashes
    @classmethod
    def get_merkle_root(cls, hashes):
        while len(hashes) > 1:
            newhashes = []
            for i in range(0, len(hashes), 2):
                i2 = min(i+1, len(hashes)-1)
                newhashes.append(hash256(hashes[i] + hashes[i2]))
            hashes = newhashes
        return uint256_from_str(hashes[0])

    def calc_merkle_root(self):
        hashes = []
        for tx in self.vtx:
            tx.calc_sha256()
            hashes.append(ser_uint256(tx.sha256))
        return self.get_merkle_root(hashes)

    def calc_witness_merkle_root(self):
        # For witness root purposes, the hash of the
        # coinbase, with witness, is defined to be 0...0
        hashes = [ser_uint256(0)]

        for tx in self.vtx[1:]:
            # Calculate the hashes with witness data
            hashes.append(ser_uint256(tx.calc_sha256(True)))

        return self.get_merkle_root(hashes)

    def is_valid(self):
        self.calc_sha256()
        target = uint256_from_compact(self.nBits)
        if self.sha256 > target:
            return False
        for tx in self.vtx:
            if not tx.is_valid():
                return False
        if self.calc_merkle_root() != self.hashMerkleRoot:
            return False
        return True

    def solve(self):
        self.rehash()
        target = uint256_from_compact(self.nBits)
        while self.sha256 > target:
            self.nNonce += 1
            self.rehash()

    # Calculate the block weight using witness and non-witness
    # serialization size (does NOT use sigops).
    def get_weight(self):
        with_witness_size = len(self.serialize(with_witness=True))
        without_witness_size = len(self.serialize(with_witness=False))
        return (WITNESS_SCALE_FACTOR - 1) * without_witness_size + with_witness_size

    def __repr__(self):
        return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \
            % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
               time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))

class PrefilledTransaction:
    __slots__ = ("index", "tx")

    def __init__(self, index=0, tx = None):
        self.index = index
        self.tx = tx

    def deserialize(self, f):
        self.index = deser_compact_size(f)
        self.tx = CTransaction()
        self.tx.deserialize(f)

    def serialize(self, with_witness=True):
        r = b""
        r += ser_compact_size(self.index)
        if with_witness:
            r += self.tx.serialize_with_witness()
        else:
            r += self.tx.serialize_without_witness()
        return r

    def serialize_without_witness(self):
        return self.serialize(with_witness=False)

    def serialize_with_witness(self):
        return self.serialize(with_witness=True)

    def __repr__(self):
        return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx))

# This is what we send on the wire, in a cmpctblock message.
class P2PHeaderAndShortIDs:
    __slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length",
                 "shortids", "shortids_length")

    def __init__(self):
        self.header = CBlockHeader()
        self.nonce = 0
        self.shortids_length = 0
        self.shortids = []
        self.prefilled_txn_length = 0
        self.prefilled_txn = []

    def deserialize(self, f):
        self.header.deserialize(f)
        self.nonce = struct.unpack("<Q", f.read(8))[0]
        self.shortids_length = deser_compact_size(f)
        for _ in range(self.shortids_length):
            # shortids are defined to be 6 bytes in the spec, so append
            # two zero bytes and read it in as an 8-byte number
            self.shortids.append(struct.unpack("<Q", f.read(6) + b'\x00\x00')[0])
        self.prefilled_txn = deser_vector(f, PrefilledTransaction)
        self.prefilled_txn_length = len(self.prefilled_txn)

    # When using version 2 compact blocks, we must serialize with_witness.
    def serialize(self, with_witness=False):
        r = b""
        r += self.header.serialize()
        r += struct.pack("<Q", self.nonce)
        r += ser_compact_size(self.shortids_length)
        for x in self.shortids:
            # We only want the first 6 bytes
            r += struct.pack("<Q", x)[0:6]
        if with_witness:
            r += ser_vector(self.prefilled_txn, "serialize_with_witness")
        else:
            r += ser_vector(self.prefilled_txn, "serialize_without_witness")
        return r

    def __repr__(self):
        return "P2PHeaderAndShortIDs(header=%s, nonce=%d, shortids_length=%d, shortids=%s, prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self.header), self.nonce, self.shortids_length, repr(self.shortids), self.prefilled_txn_length, repr(self.prefilled_txn))

# P2P version of the above that will use witness serialization (for compact
# block version 2)
class P2PHeaderAndShortWitnessIDs(P2PHeaderAndShortIDs):
    __slots__ = ()
    def serialize(self):
        return super().serialize(with_witness=True)

# Calculate the BIP 152-compact blocks shortid for a given transaction hash
def calculate_shortid(k0, k1, tx_hash):
    expected_shortid = siphash256(k0, k1, tx_hash)
    expected_shortid &= 0x0000ffffffffffff
    return expected_shortid

# This version gets rid of the array lengths, and reinterprets the differential
# encoding into indices that can be used for lookup.
class HeaderAndShortIDs:
    __slots__ = ("header", "nonce", "prefilled_txn", "shortids", "use_witness")

    def __init__(self, p2pheaders_and_shortids = None):
        self.header = CBlockHeader()
        self.nonce = 0
        self.shortids = []
        self.prefilled_txn = []
        self.use_witness = False

        if p2pheaders_and_shortids is not None:
            self.header = p2pheaders_and_shortids.header
            self.nonce = p2pheaders_and_shortids.nonce
            self.shortids = p2pheaders_and_shortids.shortids
            last_index = -1
            for x in p2pheaders_and_shortids.prefilled_txn:
                self.prefilled_txn.append(PrefilledTransaction(x.index + last_index + 1, x.tx))
                last_index = self.prefilled_txn[-1].index

    def to_p2p(self):
        if self.use_witness:
            ret = P2PHeaderAndShortWitnessIDs()
        else:
            ret = P2PHeaderAndShortIDs()
        ret.header = self.header
        ret.nonce = self.nonce
        ret.shortids_length = len(self.shortids)
        ret.shortids = self.shortids
        ret.prefilled_txn_length = len(self.prefilled_txn)
        ret.prefilled_txn = []
        last_index = -1
        for x in self.prefilled_txn:
            ret.prefilled_txn.append(PrefilledTransaction(x.index - last_index - 1, x.tx))
            last_index = x.index
        return ret

    def get_siphash_keys(self):
        header_nonce = self.header.serialize()
        header_nonce += struct.pack("<Q", self.nonce)
        hash_header_nonce_as_str = sha256(header_nonce)
        key0 = struct.unpack("<Q", hash_header_nonce_as_str[0:8])[0]
        key1 = struct.unpack("<Q", hash_header_nonce_as_str[8:16])[0]
        return [ key0, key1 ]

    # Version 2 compact blocks use wtxid in shortids (rather than txid)
    def initialize_from_block(self, block, nonce=0, prefill_list=None, use_witness=False):
        if prefill_list is None:
            prefill_list = [0]
        self.header = CBlockHeader(block)
        self.nonce = nonce
        self.prefilled_txn = [ PrefilledTransaction(i, block.vtx[i]) for i in prefill_list ]
        self.shortids = []
        self.use_witness = use_witness
        [k0, k1] = self.get_siphash_keys()
        for i in range(len(block.vtx)):
            if i not in prefill_list:
                tx_hash = block.vtx[i].sha256
                if use_witness:
                    tx_hash = block.vtx[i].calc_sha256(with_witness=True)
                self.shortids.append(calculate_shortid(k0, k1, tx_hash))

    def __repr__(self):
        return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self.header), self.nonce, repr(self.shortids), repr(self.prefilled_txn))

class BlockTransactionsRequest:
    __slots__ = ("blockhash", "indexes")

    def __init__(self, blockhash=0, indexes = None):
        self.blockhash = blockhash
        self.indexes = indexes if indexes is not None else []

    def deserialize(self, f):
        self.blockhash = deser_uint256(f)
        indexes_length = deser_compact_size(f)
        for _ in range(indexes_length):
            self.indexes.append(deser_compact_size(f))

    def serialize(self):
        r = b""
        r += ser_uint256(self.blockhash)
        r += ser_compact_size(len(self.indexes))
        for x in self.indexes:
            r += ser_compact_size(x)
        return r

    # helper to set the differentially encoded indexes from absolute ones
    def from_absolute(self, absolute_indexes):
        self.indexes = []
        last_index = -1
        for x in absolute_indexes:
            self.indexes.append(x-last_index-1)
            last_index = x

    def to_absolute(self):
        absolute_indexes = []
        last_index = -1
        for x in self.indexes:
            absolute_indexes.append(x+last_index+1)
            last_index = absolute_indexes[-1]
        return absolute_indexes

    def __repr__(self):
        return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes))

class BlockTransactions:
    __slots__ = ("blockhash", "transactions")

    def __init__(self, blockhash=0, transactions = None):
        self.blockhash = blockhash
        self.transactions = transactions if transactions is not None else []

    def deserialize(self, f):
        self.blockhash = deser_uint256(f)
        self.transactions = deser_vector(f, CTransaction)

    def serialize(self, with_witness=True):
        r = b""
        r += ser_uint256(self.blockhash)
        if with_witness:
            r += ser_vector(self.transactions, "serialize_with_witness")
        else:
            r += ser_vector(self.transactions, "serialize_without_witness")
        return r

    def __repr__(self):
        return "BlockTransactions(hash=%064x transactions=%s)" % (self.blockhash, repr(self.transactions))

class CPartialMerkleTree:
    __slots__ = ("nTransactions", "vBits", "vHash")

    def __init__(self):
        self.nTransactions = 0
        self.vHash = []
        self.vBits = []

    def deserialize(self, f):
        self.nTransactions = struct.unpack("<i", f.read(4))[0]
        self.vHash = deser_uint256_vector(f)
        vBytes = deser_string(f)
        self.vBits = []
        for i in range(len(vBytes) * 8):
            self.vBits.append(vBytes[i//8] & (1 << (i % 8)) != 0)

    def serialize(self):
        r = b""
        r += struct.pack("<i", self.nTransactions)
        r += ser_uint256_vector(self.vHash)
        vBytesArray = bytearray([0x00] * ((len(self.vBits) + 7)//8))
        for i in range(len(self.vBits)):
            vBytesArray[i // 8] |= self.vBits[i] << (i % 8)
        r += ser_string(bytes(vBytesArray))
        return r

    def __repr__(self):
        return "CPartialMerkleTree(nTransactions=%d, vHash=%s, vBits=%s)" % (self.nTransactions, repr(self.vHash), repr(self.vBits))

class CMerkleBlock:
    __slots__ = ("header", "txn")

    def __init__(self):
        self.header = CBlockHeader()
        self.txn = CPartialMerkleTree()

    def deserialize(self, f):
        self.header.deserialize(f)
        self.txn.deserialize(f)

    def serialize(self):
        r = b""
        r += self.header.serialize()
        r += self.txn.serialize()
        return r

    def __repr__(self):
        return "CMerkleBlock(header=%s, txn=%s)" % (repr(self.header), repr(self.txn))

# Objects that correspond to messages on the wire
class msg_version:
    __slots__ = ("addrFrom", "addrTo", "nNonce", "relay", "nServices",
                 "nStartingHeight", "nTime", "nVersion", "strSubVer")
    msgtype = b"version"

    def __init__(self):
        self.nVersion = 0
        self.nServices = 0
        self.nTime = int(time.time())
        self.addrTo = CAddress()
        self.addrFrom = CAddress()
        self.nNonce = random.getrandbits(64)
        self.strSubVer = ''
        self.nStartingHeight = -1
        self.relay = 0

    def deserialize(self, f):
        self.nVersion = struct.unpack("<i", f.read(4))[0]
        self.nServices = struct.unpack("<Q", f.read(8))[0]
        self.nTime = struct.unpack("<q", f.read(8))[0]
        self.addrTo = CAddress()
        self.addrTo.deserialize(f, with_time=False)

        self.addrFrom = CAddress()
        self.addrFrom.deserialize(f, with_time=False)
        self.nNonce = struct.unpack("<Q", f.read(8))[0]
        self.strSubVer = deser_string(f).decode('utf-8')

        self.nStartingHeight = struct.unpack("<i", f.read(4))[0]

        # Relay field is optional for version 70001 onwards
        # But, unconditionally check it to match behaviour in bitcoind
        try:
            self.relay = struct.unpack("<b", f.read(1))[0]
        except struct.error:
            self.relay = 0

    def serialize(self):
        r = b""
        r += struct.pack("<i", self.nVersion)
        r += struct.pack("<Q", self.nServices)
        r += struct.pack("<q", self.nTime)
        r += self.addrTo.serialize(with_time=False)
        r += self.addrFrom.serialize(with_time=False)
        r += struct.pack("<Q", self.nNonce)
        r += ser_string(self.strSubVer.encode('utf-8'))
        r += struct.pack("<i", self.nStartingHeight)
        r += struct.pack("<b", self.relay)
        return r

    def __repr__(self):
        return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i relay=%i)' \
            % (self.nVersion, self.nServices, time.ctime(self.nTime),
               repr(self.addrTo), repr(self.addrFrom), self.nNonce,
               self.strSubVer, self.nStartingHeight, self.relay)

class msg_verack:
    __slots__ = ()
    msgtype = b"verack"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_verack()"

class msg_addr:
    __slots__ = ("addrs",)
    msgtype = b"addr"

    def __init__(self):
        self.addrs = []

    def deserialize(self, f):
        self.addrs = deser_vector(f, CAddress)

    def serialize(self):
        return ser_vector(self.addrs)

    def __repr__(self):
        return "msg_addr(addrs=%s)" % (repr(self.addrs))

class msg_addrv2:
    __slots__ = ("addrs",)
    msgtype = b"addrv2"

    def __init__(self):
        self.addrs = []

    def deserialize(self, f):
        self.addrs = deser_vector(f, CAddress, "deserialize_v2")

    def serialize(self):
        return ser_vector(self.addrs, "serialize_v2")

    def __repr__(self):
        return "msg_addrv2(addrs=%s)" % (repr(self.addrs))

class msg_sendaddrv2:
    __slots__ = ()
    msgtype = b"sendaddrv2"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_sendaddrv2()"

class msg_inv:
    __slots__ = ("inv",)
    msgtype = b"inv"

    def __init__(self, inv=None):
        if inv is None:
            self.inv = []
        else:
            self.inv = inv

    def deserialize(self, f):
        self.inv = deser_vector(f, CInv)

    def serialize(self):
        return ser_vector(self.inv)

    def __repr__(self):
        return "msg_inv(inv=%s)" % (repr(self.inv))

class msg_getdata:
    __slots__ = ("inv",)
    msgtype = b"getdata"

    def __init__(self, inv=None):
        self.inv = inv if inv is not None else []

    def deserialize(self, f):
        self.inv = deser_vector(f, CInv)

    def serialize(self):
        return ser_vector(self.inv)

    def __repr__(self):
        return "msg_getdata(inv=%s)" % (repr(self.inv))

class msg_getblocks:
    __slots__ = ("locator", "hashstop")
    msgtype = b"getblocks"

    def __init__(self):
        self.locator = CBlockLocator()
        self.hashstop = 0

    def deserialize(self, f):
        self.locator = CBlockLocator()
        self.locator.deserialize(f)
        self.hashstop = deser_uint256(f)

    def serialize(self):
        r = b""
        r += self.locator.serialize()
        r += ser_uint256(self.hashstop)
        return r

    def __repr__(self):
        return "msg_getblocks(locator=%s hashstop=%064x)" \
            % (repr(self.locator), self.hashstop)

class msg_tx:
    __slots__ = ("tx",)
    msgtype = b"tx"

    def __init__(self, tx=CTransaction()):
        self.tx = tx

    def deserialize(self, f):
        self.tx.deserialize(f)

    def serialize(self):
        return self.tx.serialize_with_witness()

    def __repr__(self):
        return "msg_tx(tx=%s)" % (repr(self.tx))

class msg_wtxidrelay:
    __slots__ = ()
    msgtype = b"wtxidrelay"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_wtxidrelay()"

class msg_no_witness_tx(msg_tx):
    __slots__ = ()

    def serialize(self):
        return self.tx.serialize_without_witness()

class msg_block:
    __slots__ = ("block",)
    msgtype = b"block"

    def __init__(self, block=None):
        if block is None:
            self.block = CBlock()
        else:
            self.block = block

    def deserialize(self, f):
        self.block.deserialize(f)

    def serialize(self):
        return self.block.serialize()

    def __repr__(self):
        return "msg_block(block=%s)" % (repr(self.block))

# for cases where a user needs tighter control over what is sent over the wire
# note that the user must supply the name of the msgtype, and the data
class msg_generic:
    __slots__ = ("data")

    def __init__(self, msgtype, data=None):
        self.msgtype = msgtype
        self.data = data

    def serialize(self):
        return self.data

    def __repr__(self):
        return "msg_generic()"

class msg_no_witness_block(msg_block):
    __slots__ = ()
    def serialize(self):
        return self.block.serialize(with_witness=False)

class msg_getaddr:
    __slots__ = ()
    msgtype = b"getaddr"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_getaddr()"

class msg_ping:
    __slots__ = ("nonce",)
    msgtype = b"ping"

    def __init__(self, nonce=0):
        self.nonce = nonce

    def deserialize(self, f):
        self.nonce = struct.unpack("<Q", f.read(8))[0]

    def serialize(self):
        r = b""
        r += struct.pack("<Q", self.nonce)
        return r

    def __repr__(self):
        return "msg_ping(nonce=%08x)" % self.nonce

class msg_pong:
    __slots__ = ("nonce",)
    msgtype = b"pong"

    def __init__(self, nonce=0):
        self.nonce = nonce

    def deserialize(self, f):
        self.nonce = struct.unpack("<Q", f.read(8))[0]

    def serialize(self):
        r = b""
        r += struct.pack("<Q", self.nonce)
        return r

    def __repr__(self):
        return "msg_pong(nonce=%08x)" % self.nonce

class msg_mempool:
    __slots__ = ()
    msgtype = b"mempool"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_mempool()"

class msg_notfound:
    __slots__ = ("vec", )
    msgtype = b"notfound"

    def __init__(self, vec=None):
        self.vec = vec or []

    def deserialize(self, f):
        self.vec = deser_vector(f, CInv)

    def serialize(self):
        return ser_vector(self.vec)

    def __repr__(self):
        return "msg_notfound(vec=%s)" % (repr(self.vec))

class msg_sendheaders:
    __slots__ = ()
    msgtype = b"sendheaders"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_sendheaders()"

# getheaders message has
# number of entries
# vector of hashes
# hash_stop (hash of last desired block header, 0 to get as many as possible)
class msg_getheaders:
    __slots__ = ("hashstop", "locator",)
    msgtype = b"getheaders"

    def __init__(self):
        self.locator = CBlockLocator()
        self.hashstop = 0

    def deserialize(self, f):
        self.locator = CBlockLocator()
        self.locator.deserialize(f)
        self.hashstop = deser_uint256(f)

    def serialize(self):
        r = b""
        r += self.locator.serialize()
        r += ser_uint256(self.hashstop)
        return r

    def __repr__(self):
        return "msg_getheaders(locator=%s, stop=%064x)" \
            % (repr(self.locator), self.hashstop)

# headers message has
# <count> <vector of block headers>
class msg_headers:
    __slots__ = ("headers",)
    msgtype = b"headers"

    def __init__(self, headers=None):
        self.headers = headers if headers is not None else []

    def deserialize(self, f):
        # comment in bitcoind indicates these should be deserialized as blocks
        blocks = deser_vector(f, CBlock)
        for x in blocks:
            self.headers.append(CBlockHeader(x))

    def serialize(self):
        blocks = [CBlock(x) for x in self.headers]
        return ser_vector(blocks)

    def __repr__(self):
        return "msg_headers(headers=%s)" % repr(self.headers)

class msg_merkleblock:
    __slots__ = ("merkleblock",)
    msgtype = b"merkleblock"

    def __init__(self, merkleblock=None):
        if merkleblock is None:
            self.merkleblock = CMerkleBlock()
        else:
            self.merkleblock = merkleblock

    def deserialize(self, f):
        self.merkleblock.deserialize(f)

    def serialize(self):
        return self.merkleblock.serialize()

    def __repr__(self):
        return "msg_merkleblock(merkleblock=%s)" % (repr(self.merkleblock))

class msg_filterload:
    __slots__ = ("data", "nHashFuncs", "nTweak", "nFlags")
    msgtype = b"filterload"

    def __init__(self, data=b'00', nHashFuncs=0, nTweak=0, nFlags=0):
        self.data = data
        self.nHashFuncs = nHashFuncs
        self.nTweak = nTweak
        self.nFlags = nFlags

    def deserialize(self, f):
        self.data = deser_string(f)
        self.nHashFuncs = struct.unpack("<I", f.read(4))[0]
        self.nTweak = struct.unpack("<I", f.read(4))[0]
        self.nFlags = struct.unpack("<B", f.read(1))[0]

    def serialize(self):
        r = b""
        r += ser_string(self.data)
        r += struct.pack("<I", self.nHashFuncs)
        r += struct.pack("<I", self.nTweak)
        r += struct.pack("<B", self.nFlags)
        return r

    def __repr__(self):
        return "msg_filterload(data={}, nHashFuncs={}, nTweak={}, nFlags={})".format(
            self.data, self.nHashFuncs, self.nTweak, self.nFlags)

class msg_filteradd:
    __slots__ = ("data")
    msgtype = b"filteradd"

    def __init__(self, data):
        self.data = data

    def deserialize(self, f):
        self.data = deser_string(f)

    def serialize(self):
        r = b""
        r += ser_string(self.data)
        return r

    def __repr__(self):
        return "msg_filteradd(data={})".format(self.data)

class msg_filterclear:
    __slots__ = ()
    msgtype = b"filterclear"

    def __init__(self):
        pass

    def deserialize(self, f):
        pass

    def serialize(self):
        return b""

    def __repr__(self):
        return "msg_filterclear()"

class msg_feefilter:
    __slots__ = ("feerate",)
    msgtype = b"feefilter"

    def __init__(self, feerate=0):
        self.feerate = feerate

    def deserialize(self, f):
        self.feerate = struct.unpack("<Q", f.read(8))[0]

    def serialize(self):
        r = b""
        r += struct.pack("<Q", self.feerate)
        return r

    def __repr__(self):
        return "msg_feefilter(feerate=%08x)" % self.feerate

class msg_sendcmpct:
    __slots__ = ("announce", "version")
    msgtype = b"sendcmpct"

    def __init__(self, announce=False, version=1):
        self.announce = announce
        self.version = version

    def deserialize(self, f):
        self.announce = struct.unpack("<?", f.read(1))[0]
        self.version = struct.unpack("<Q", f.read(8))[0]

    def serialize(self):
        r = b""
        r += struct.pack("<?", self.announce)
        r += struct.pack("<Q", self.version)
        return r

    def __repr__(self):
        return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version)

class msg_cmpctblock:
    __slots__ = ("header_and_shortids",)
    msgtype = b"cmpctblock"

    def __init__(self, header_and_shortids = None):
        self.header_and_shortids = header_and_shortids

    def deserialize(self, f):
        self.header_and_shortids = P2PHeaderAndShortIDs()
        self.header_and_shortids.deserialize(f)

    def serialize(self):
        r = b""
        r += self.header_and_shortids.serialize()
        return r

    def __repr__(self):
        return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids)

class msg_getblocktxn:
    __slots__ = ("block_txn_request",)
    msgtype = b"getblocktxn"

    def __init__(self):
        self.block_txn_request = None

    def deserialize(self, f):
        self.block_txn_request = BlockTransactionsRequest()
        self.block_txn_request.deserialize(f)

    def serialize(self):
        r = b""
        r += self.block_txn_request.serialize()
        return r

    def __repr__(self):
        return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request))

class msg_blocktxn:
    __slots__ = ("block_transactions",)
    msgtype = b"blocktxn"

    def __init__(self):
        self.block_transactions = BlockTransactions()

    def deserialize(self, f):
        self.block_transactions.deserialize(f)

    def serialize(self):
        r = b""
        r += self.block_transactions.serialize()
        return r

    def __repr__(self):
        return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions))

class msg_no_witness_blocktxn(msg_blocktxn):
    __slots__ = ()

    def serialize(self):
        return self.block_transactions.serialize(with_witness=False)

class msg_getcfilters:
    __slots__ = ("filter_type", "start_height", "stop_hash")
    msgtype =  b"getcfilters"

    def __init__(self, filter_type, start_height, stop_hash):
        self.filter_type = filter_type
        self.start_height = start_height
        self.stop_hash = stop_hash

    def deserialize(self, f):
        self.filter_type = struct.unpack("<B", f.read(1))[0]
        self.start_height = struct.unpack("<I", f.read(4))[0]
        self.stop_hash = deser_uint256(f)

    def serialize(self):
        r = b""
        r += struct.pack("<B", self.filter_type)
        r += struct.pack("<I", self.start_height)
        r += ser_uint256(self.stop_hash)
        return r

    def __repr__(self):
        return "msg_getcfilters(filter_type={:#x}, start_height={}, stop_hash={:x})".format(
            self.filter_type, self.start_height, self.stop_hash)

class msg_cfilter:
    __slots__ = ("filter_type", "block_hash", "filter_data")
    msgtype =  b"cfilter"

    def __init__(self, filter_type=None, block_hash=None, filter_data=None):
        self.filter_type = filter_type
        self.block_hash = block_hash
        self.filter_data = filter_data

    def deserialize(self, f):
        self.filter_type = struct.unpack("<B", f.read(1))[0]
        self.block_hash = deser_uint256(f)
        self.filter_data = deser_string(f)

    def serialize(self):
        r = b""
        r += struct.pack("<B", self.filter_type)
        r += ser_uint256(self.block_hash)
        r += ser_string(self.filter_data)
        return r

    def __repr__(self):
        return "msg_cfilter(filter_type={:#x}, block_hash={:x})".format(
            self.filter_type, self.block_hash)

class msg_getcfheaders:
    __slots__ = ("filter_type", "start_height", "stop_hash")
    msgtype =  b"getcfheaders"

    def __init__(self, filter_type, start_height, stop_hash):
        self.filter_type = filter_type
        self.start_height = start_height
        self.stop_hash = stop_hash

    def deserialize(self, f):
        self.filter_type = struct.unpack("<B", f.read(1))[0]
        self.start_height = struct.unpack("<I", f.read(4))[0]
        self.stop_hash = deser_uint256(f)

    def serialize(self):
        r = b""
        r += struct.pack("<B", self.filter_type)
        r += struct.pack("<I", self.start_height)
        r += ser_uint256(self.stop_hash)
        return r

    def __repr__(self):
        return "msg_getcfheaders(filter_type={:#x}, start_height={}, stop_hash={:x})".format(
            self.filter_type, self.start_height, self.stop_hash)

class msg_cfheaders:
    __slots__ = ("filter_type", "stop_hash", "prev_header", "hashes")
    msgtype =  b"cfheaders"

    def __init__(self, filter_type=None, stop_hash=None, prev_header=None, hashes=None):
        self.filter_type = filter_type
        self.stop_hash = stop_hash
        self.prev_header = prev_header
        self.hashes = hashes

    def deserialize(self, f):
        self.filter_type = struct.unpack("<B", f.read(1))[0]
        self.stop_hash = deser_uint256(f)
        self.prev_header = deser_uint256(f)
        self.hashes = deser_uint256_vector(f)

    def serialize(self):
        r = b""
        r += struct.pack("<B", self.filter_type)
        r += ser_uint256(self.stop_hash)
        r += ser_uint256(self.prev_header)
        r += ser_uint256_vector(self.hashes)
        return r

    def __repr__(self):
        return "msg_cfheaders(filter_type={:#x}, stop_hash={:x})".format(
            self.filter_type, self.stop_hash)

class msg_getcfcheckpt:
    __slots__ = ("filter_type", "stop_hash")
    msgtype =  b"getcfcheckpt"

    def __init__(self, filter_type, stop_hash):
        self.filter_type = filter_type
        self.stop_hash = stop_hash

    def deserialize(self, f):
        self.filter_type = struct.unpack("<B", f.read(1))[0]
        self.stop_hash = deser_uint256(f)

    def serialize(self):
        r = b""
        r += struct.pack("<B", self.filter_type)
        r += ser_uint256(self.stop_hash)
        return r

    def __repr__(self):
        return "msg_getcfcheckpt(filter_type={:#x}, stop_hash={:x})".format(
            self.filter_type, self.stop_hash)

class msg_cfcheckpt:
    __slots__ = ("filter_type", "stop_hash", "headers")
    msgtype =  b"cfcheckpt"

    def __init__(self, filter_type=None, stop_hash=None, headers=None):
        self.filter_type = filter_type
        self.stop_hash = stop_hash
        self.headers = headers

    def deserialize(self, f):
        self.filter_type = struct.unpack("<B", f.read(1))[0]
        self.stop_hash = deser_uint256(f)
        self.headers = deser_uint256_vector(f)

    def serialize(self):
        r = b""
        r += struct.pack("<B", self.filter_type)
        r += ser_uint256(self.stop_hash)
        r += ser_uint256_vector(self.headers)
        return r

    def __repr__(self):
        return "msg_cfcheckpt(filter_type={:#x}, stop_hash={:x})".format(
            self.filter_type, self.stop_hash)


text:
class Oscats < Formula
  desc "Computerized adaptive testing system"
  homepage "https://code.google.com/p/oscats/"
  url "https://oscats.googlecode.com/files/oscats-0.6.tar.gz"
  sha256 "2f7c88cdab6a2106085f7a3e5b1073c74f7d633728c76bd73efba5dc5657a604"

  depends_on "pkg-config" => :build
  depends_on :python => :optional
  depends_on "gsl"
  depends_on "glib"
  depends_on "pygobject" if build.with? "python"

  def install
    args = ["--disable-dependency-tracking", "--prefix=#{prefix}"]
    args << "--enable-python-bindings" if build.with? "python"
    system "./configure", *args
    system "make", "install"
  end
end

redpajama_set_name: RedPajamaGithub


text:
Now that we know how to show dynamic list of tweets, we are now going to go to the next level of storing the tweets in a local file & showing tweets from it.

## Why do we need to store

In a mobile app, use of local storage is important for a better user experience. In a real app, when the Tweet List screen comes up, the tweets are read from the file & shown instantaneously while another process starts & runs asynchronously to update the file with latest tweets.

For now, we are simply going to write the dummy tweets that we created in the previous lesson into a local cache file, read from it & show it to the user when the Tweet List screen loads. In subsequent lesson, we are going to move the writing tweets part to an asynchronous process using AsyncTask.


text:
from UserDict import DictMixin

class odict(DictMixin):
    def __init__(self, init=None):
        self._keys = []
        self._data = {}
        if init is not None:
            for key, value in init:
                self[key] = value

    def __setitem__(self, key, value):
        if key not in self._data:
            self._keys.append(key)
        self._data[key] = value

    def __getitem__(self, key):
        return self._data[key]

    def __delitem__(self, key):
        del self._data[key]
        self._keys.remove(key)

    def keys(self):
        return list(self._keys)

    def copy(self):
        copyDict = odict()
        copyDict._data = self._data.copy()
        copyDict._keys = self._keys[:]
        return copyDict


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Composition
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LanguageServices
    <ExportLanguageServiceFactory(GetType(ISymbolDisplayService), LanguageNames.VisualBasic), [Shared]>
    Friend Class VisualBasicSymbolDisplayServiceFactory
        Implements ILanguageServiceFactory

        <ImportingConstructor>
        <Obsolete(MefConstruction.ImportingConstructorMessage, True)>
        Public Sub New()
        End Sub

        Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
            Return New VisualBasicSymbolDisplayService(provider)
        End Function
    End Class
End Namespace


text:
<?php

namespace Saklient\Tests;

require_once "Common.php";
use Saklient\Cloud\API;
use Saklient\Cloud\Enums\EServerInstanceStatus;
use Saklient\Cloud\Resources\LbServer;
use Saklient\Errors\SaklientException;
use Saklient\Errors\HttpConflictException;
use Saklient\Cloud\Resources\LoadBalancer;

class LoadBalancerTest extends \PHPUnit_Framework_TestCase
{
	use \Saklient\Tests\Common;

	const TESTS_CONFIG_READYMADE_LB_ID = null;

	public function testAuthorize()
	{
		return $this->authorize();
	}

	/**
	 * @depends testAuthorize
	 */
	public function testCrud(API $api)
	{

		$name = "!phpunit-" . date("Ymd_His") . "-" . substr(uniqid(),0,6);
		$description = "This instance was created by Saklient PHPUnit Test";
		$tag = "saklient-test";

		// create a LB

		if (!self::TESTS_CONFIG_READYMADE_LB_ID) {

			//
			fprintf(\STDERR, '作成済みのスイッチを検索しています...'."\n");
			$swytches = $api->swytch->withNameLike('saklient-lb-attached')->limit(1)->find();
			if (0 < count($swytches)) {
				$swytch = $swytches[0];
			}
			else {
				fprintf(\STDERR, 'ルータ+スイッチを作成しています...'."\n");
				$router = $api->router->create();
				$router->name = 'saklient-lb-attached';
				$router->bandWidthMbps = 100;
				$router->networkMaskLen = 28;
				$router->save();

				fprintf(\STDERR, 'ルータ+スイッチの作成完了を待機しています...'."\n");
				if (!$router->sleepWhileCreating()) $this->fail('ルータが正常に作成されません');
				$swytch = $router->getSwytch();
			}
			$this->assertInstanceOf("Saklient\\Cloud\\Resources\\Swytch", $swytch);
			$this->assertGreaterThan(0, count($swytch->ipv4Nets));
			$net = $swytch->ipv4Nets[0];
			fprintf(\STDERR, "%s/%d -> %s\n", $net->address, $net->maskLen, $net->defaultRoute);

			// create a loadbalancer
			fprintf(\STDERR, 'ロードバランサを作成しています...'."\n");
			$vrid = 123;
			$realIp1 = long2ip(ip2long($net->defaultRoute) + 3);
			$realIp2 = long2ip(ip2long($net->defaultRoute) + 4);
			$lb = $api->appliance->createLoadBalancer($swytch, $vrid, [$realIp1, $realIp2], true);

			$ok = false;
			try {
				$lb->save();
			}
			catch (SaklientException $ex) {
				$ok = true;
			}
			if (!$ok) $this->fail('Requiredフィールドが未set時は SaklientException がスローされなければなりません');
			$lb->name = $name;
			$lb->description = "";
			$lb->tags = [$tag];
			$lb->save();

			$lb->reload();
			$this->assertEquals($net->defaultRoute, $lb->defaultRoute);
			$this->assertEquals($net->maskLen, $lb->maskLen);
			$this->assertEquals($vrid, $lb->vrid);
			$this->assertEquals($swytch->id, $lb->swytchId);

			// wait the LB becomes up
			fprintf(\STDERR, 'ロードバランサの起動を待機しています...'."\n");
			if (!$lb->sleepUntilUp()) $this->fail("ロードバランサが正常に起動しません");

		}
		else {

			$lb = $api->appliance->getById(self::TESTS_CONFIG_READYMADE_LB_ID);
			$this->assertInstanceOf("Saklient\\Cloud\\Resources\\LoadBalancer", $lb);
			$swytch = $lb->getSwytch();
			$this->assertInstanceOf("Saklient\\Cloud\\Resources\\Swytch", $swytch);
			$net = $swytch->ipv4Nets[0];
			$this->assertInstanceOf("Saklient\\Cloud\\Resources\\Ipv4Net", $net);
			fprintf(\STDERR, "%s/%d -> %s\n", $net->address, $net->maskLen, $net->defaultRoute);

		}

		// clear virtual ips

		$lb->clearVirtualIps();
		$lb->save();
		$lb->reload();
		$this->assertEquals($lb->virtualIps->count(), 0);

		// setting virtual ips test 1

		$vip1Ip     = long2ip(ip2long($net->defaultRoute) + 5);
		$vip1SrvIp1 = long2ip(ip2long($net->defaultRoute) + 6);
		$vip1SrvIp2 = long2ip(ip2long($net->defaultRoute) + 7);
		$vip1SrvIp3 = long2ip(ip2long($net->defaultRoute) + 8);
		$vip1SrvIp4 = long2ip(ip2long($net->defaultRoute) + 9);

		$lb->addVirtualIp([
			"vip" => $vip1Ip,
			"port" => 80,
			"delay" => 15,
			"servers" => [
				[ "ip"=>$vip1SrvIp1, "port"=>80, "protocol"=>"http", "pathToCheck"=>"/index.html", "responseExpected"=>200 ],
				[ "ip"=>$vip1SrvIp2, "port"=>80, "protocol"=>"https", "pathToCheck"=>"/", "responseExpected"=>200 ],
				[ "ip"=>$vip1SrvIp3, "port"=>80, "protocol"=>"tcp" ]
			]
		]);

		$vip2Ip     = long2ip(ip2long($net->defaultRoute) + 10);
		$vip2SrvIp1 = long2ip(ip2long($net->defaultRoute) + 11);
		$vip2SrvIp2 = long2ip(ip2long($net->defaultRoute) + 12);

		$vip2 = $lb->addVirtualIp();
		$vip2->virtualIpAddress = $vip2Ip;
		$vip2->port = 80;
		$vip2->delayLoop = 15;
		$vip2Srv1 = $vip2->addServer();
		$vip2Srv1->ipAddress = $vip2SrvIp1;
		$vip2Srv1->port = 80;
		$vip2Srv1->protocol = "http";
		$vip2Srv1->pathToCheck = "/index.html";
		$vip2Srv1->responseExpected = 200;
		$vip2SrvD = $vip2->addServer();
		$vip2SrvD->ipAddress = "10.0.0.1";
		$vip2SrvD->port = 80;
		$vip2SrvD->protocol = "tcp";
		$vip2Srv2 = $vip2->addServer();
		$vip2Srv2->ipAddress = $vip2SrvIp2;
		$vip2Srv2->port = 80;
		$vip2Srv2->protocol = "tcp";
		$vip2->removeServerByAddress("10.0.0.1");
		$lb->save();
		$lb->reload();

		$this->assertEquals(2,             $lb->virtualIps->count());
		$this->assertEquals($vip1Ip,       $lb->virtualIps[0]->virtualIpAddress);
		$this->assertEquals(3,             $lb->virtualIps[0]->servers->count());
		$this->assertEquals($vip1SrvIp1,   $lb->virtualIps[0]->servers[0]->ipAddress);
		$this->assertEquals(80,            $lb->virtualIps[0]->servers[0]->port);
		$this->assertEquals("http",        $lb->virtualIps[0]->servers[0]->protocol);
		$this->assertEquals("/index.html", $lb->virtualIps[0]->servers[0]->pathToCheck);
		$this->assertEquals(200,           $lb->virtualIps[0]->servers[0]->responseExpected);
		$this->assertEquals($vip1SrvIp2,   $lb->virtualIps[0]->servers[1]->ipAddress);
		$this->assertEquals(80,            $lb->virtualIps[0]->servers[1]->port);
		$this->assertEquals("https",       $lb->virtualIps[0]->servers[1]->protocol);
		$this->assertEquals("/",           $lb->virtualIps[0]->servers[1]->pathToCheck);
		$this->assertEquals(200,           $lb->virtualIps[0]->servers[1]->responseExpected);
		$this->assertEquals($vip1SrvIp3,   $lb->virtualIps[0]->servers[2]->ipAddress);
		$this->assertEquals(80,            $lb->virtualIps[0]->servers[2]->port);
		$this->assertEquals("tcp",         $lb->virtualIps[0]->servers[2]->protocol);
		$this->assertEquals($vip2Ip,       $lb->virtualIps[1]->virtualIpAddress);
		$this->assertEquals(2,             $lb->virtualIps[1]->servers->count());
		$this->assertEquals($vip2SrvIp1,   $lb->virtualIps[1]->servers[0]->ipAddress);
		$this->assertEquals(80,            $lb->virtualIps[1]->servers[0]->port);
		$this->assertEquals("http",        $lb->virtualIps[1]->servers[0]->protocol);
		$this->assertEquals("/index.html", $lb->virtualIps[1]->servers[0]->pathToCheck);
		$this->assertEquals(200,           $lb->virtualIps[1]->servers[0]->responseExpected);
		$this->assertEquals($vip2SrvIp2,   $lb->virtualIps[1]->servers[1]->ipAddress);
		$this->assertEquals(80,            $lb->virtualIps[1]->servers[1]->port);
		$this->assertEquals("tcp",         $lb->virtualIps[1]->servers[1]->protocol);

		// setting virtual ips test 2

		$lb->getVirtualIpByAddress($vip1Ip)->addServer([
			"ip" => $vip1SrvIp4,
			"port" => 80,
			"protocol" => "ping"
		]);
		$lb->save();
		$lb->reload();

		$this->assertEquals(2,           $lb->virtualIps->count());
		$this->assertEquals(4,           $lb->virtualIps[0]->servers->count());
		$this->assertEquals($vip1SrvIp4, $lb->virtualIps[0]->servers[3]->ipAddress);
		$this->assertEquals(80,          $lb->virtualIps[0]->servers[3]->port);
		$this->assertEquals("ping",      $lb->virtualIps[0]->servers[3]->protocol);
		$this->assertEquals(2,           $lb->virtualIps[1]->servers->count());

		// checking status

		$lb->reloadStatus();
		foreach ($lb->virtualIps as $vip) {
			printf("  vip %s:%s every %ssec(s)\n", $vip->virtualIpAddress, $vip->port, $vip->delayLoop);
			foreach ($vip->servers as $server) {
				printf("    [%s(%s)]", $server->status, $server->activeConnections);
				printf(" server %s://%s", $server->protocol, $server->ipAddress);
				if ($server->port) printf(":%d", $server->port);
				if ($server->pathToCheck) fprintf(\STDERR, $server->pathToCheck);
				fprintf(\STDERR, " answers");
				if ($server->responseExpected) printf(" %d", $server->responseExpected);
				fprintf(\STDERR, "\n");
				$this->assertTrue($server->status==null || $server->status=="down");
			}
		}

		// delete the LB

		if (!self::TESTS_CONFIG_READYMADE_LB_ID) {
			// stop the LB
			sleep(1);
			fprintf(\STDERR, "stopping the LB...\n");
			if (!$lb->stop()->sleepUntilDown()) $this->fail('ロードバランサが正常に停止しません');

			// delete the LB
			fprintf(\STDERR, "deleting the LB...\n");
			$lb->destroy();
		}

	}

}


text:
function output_filenames = remove_sferics_and_hum(output_dir, input_dir, input_filenames, station_name, cal_datenum, fs_dec, channel)
% Scripts to use Dan's sferic removal and Morris and Ryan's hum removal
% on a bunch of files and resave them
%
% output_filenames = remove_sferics_and_hum(output_dir, input_dir, input_filenames, station_name, cal_datenum, fs_dec, channel)
%
% input_filenames is a cell array of filenames

% By Daniel Golden (dgolden1 at stanford dot edu) June 2009
% $Id$

%% Setup
% addpath(fullfile(danmatlabroot, 'vlf', 'jeremie_sferic_removal'));
addpath(fullfile(danmatlabroot, 'vlf', 'sferic_removal'));
addpath(fullfile(danmatlabroot, 'vlf', 'humblaster'));

% Input and output directories
[stat, hostname] = unix('hostname');
switch hostname(1:end-1) % Get rid of newline
  case 'quadcoredan.stanford.edu'
    default_output_dir = '/home/dgolden/temp';
    default_input_dir = '/media/polarbear/input/palmer_2003_02_02_uncleaned/20sec_awesome';
  case 'polarbear'
    default_output_dir = '/home/dgolden1/output/palmer_2003_02_02_cleaned';
    default_input_dir = '/home/dgolden1/input/palmer_2003_02_02_uncleaned/20sec_awesome';
  otherwise
    default_output_dir = nan;
    default_input_dir = nan;
    % error('Unknown hostname %s', hostname(1:end-1));
end

if ~exist('output_dir', 'var') || isempty(output_dir)
  output_dir = default_output_dir;
end
if ~exist('input_dir', 'var') || isempty(output_dir)
  input_dir = default_input_dir;
end
if ~exist('fs_dec', 'var') || isempty(fs_dec)
  fs_dec = 20e3;
end

% Figure handles
s = [];

%% Parallel
% PARALLEL = true;
% poolsize = matlabpool('size');
% if PARALLEL && poolsize == 0
%   matlabpool('open');
% end
% if ~PARALLEL && poolsize ~= 0
%   matlabpool('close');
% end
% if ~PARALLEL
%   disp('Warning: PARALLEL is false');
% end

output_filenames = {};

%% Cycle through files
if ~exist('input_filenames', 'var') || isempty(input_filenames)
  fprintf('Processing all files in %s\n', input_dir);
  d = [dir(fullfile(input_dir, '*.mat')); dir(fullfile(input_dir, '*.MAT'))];
  input_filenames = {d.name};
end

% Decimation parameters
f_max = fs_dec/2; % Hz

% Sferic removal parameters can be different for different stations
switch station_name
  case 'southpole'
    sf_rem_thresh = 0.1;
  otherwise
    sf_rem_thresh = 0.01;
end
sf_rem_b_slowtail_filter = true;

% Spectrogram parameters
window = 1024;
noverlap = 512;
nfft = 1024;

for kk = 1:length(input_filenames)
  t_file_start = now;
  % disp(sprintf('Processing file %s', input_filenames{kk}));

  %% Load data
  file_struct = load(fullfile(input_dir, input_filenames{kk}));
  file_struct.data = file_struct.data - mean(file_struct.data );

  %% Massage the data before cleaning if it needs it
  data_massaged = massage_data(file_struct.data, file_struct.Fs, station_name, cal_datenum);

  HB = get_humblaster_parameters(station_name, cal_datenum);
  if HB.b_humblast
    num_subplots = 3;
  else
    num_subplots = 2;
  end

  %% Decimate
  bb_dec_factor = file_struct.Fs/fs_dec;
  if fpart(bb_dec_factor) ~= 0
    error('decimated sampling frequency (%0.2f Hz) must be a factor of original sampling frequency (%0.2f Hz)', ...
      fs_dec, file_struct.Fs);
  end
  data_dec = decimate(data_massaged, bb_dec_factor);
  fs_dec = file_struct.Fs/bb_dec_factor;

  % Spectrogram of original
  h = sfigure(1); clf; figure_grow(1);
  s(end+1) = subplot(num_subplots, 1, 1);
  spectrogram_cal(data_dec, window, noverlap, nfft, fs_dec, station_name, cal_datenum); xlabel('');
  title(sprintf('%s original', strrep(input_filenames{kk}, '_', '\_')));

  %% Sferic removal
  t_sferic_start = now;

  % Don't remove sferics unless the periodogram is a certain amount above
  % the mediogram (i.e., the signal has significant impulsive noise)
  % between 5 and 15 kHz
  window_imp = 2^nextpow2(fs_dec*0.002); % Make the window at least 2 ms
  [~, F, ~, P] = spectrogram_dan(data_dec, window_imp, window_imp/2, window_imp, fs_dec);
  s_periodogram = 10*log10(mean(P, 2));
  s_mediogram = 10*log10(median(P, 2));
  medio_perio_diff = s_periodogram(F > 5e3 & F < 15e3) - s_mediogram(F > 5e3 & F < 15e3);

  if mean(medio_perio_diff) >= 3 % threshold on "impulsiveness"
    if file_struct.Fs ~= 1e5
      error('Data fs (%0.0f) must be 100 kHz for sferic removal', file_struct.Fs/1e3);
    end

    % Find sferics in original (100 kHz sampled) data
    [t_imp_start, t_imp_end] = find_sferics(data_massaged, file_struct.Fs, sf_rem_thresh);

    % If we find impulses which are more than 100 ms long, or the median
    % distance between impulses is less than 10 ms, our threshold must
    % be too low.  Iteratively double it until we don't have that problem.
    find_sferics_count = 1;
    while ~isempty(t_imp_start) && (max(t_imp_end - t_imp_start) > 0.1 || median(diff(t_imp_start)) < 0.01)
      sf_rem_thresh = sf_rem_thresh*2;
      [t_imp_start, t_imp_end, det_sig, det_fs, det_thresh] = find_sferics(data_massaged, file_struct.Fs, sf_rem_thresh);
      find_sferics_count = find_sferics_count + 1;
    end

    % Remove sferics
    data_sf_cleaned = remove_sferics(data_dec, fs_dec, t_imp_start, t_imp_end, sf_rem_b_slowtail_filter);
  else
    data_sf_cleaned = remove_sferics(data_dec, fs_dec, [], [], sf_rem_b_slowtail_filter);
  end

%   fprintf('Cleaned sferics in %s\n', time_elapsed(t_sferic_start, now));

  % Spectrogram of sferic cleaned
  s(end+1) = subplot(num_subplots, 1, 2);
  spectrogram_cal(data_sf_cleaned, window, noverlap, nfft, fs_dec, station_name, cal_datenum); xlabel('');
  title(sprintf('%s sferic cleaned', strrep(input_filenames{kk}, '_', '\_')));

  %% Humstraction
%   t_start = now;
%  data_hum_cleaned = humstractor(data_sf_cleaned, fs_dec, 60, a, b, 0, 0);
%   t_total = now - t_start;
%   disp(sprintf('Pass 3: cleaned hum in %0.0f sec', t_total*86400));

  %% Humblasting
  t_humblast_start = now;

  if HB.b_humblast
    [data_hum_cleaned, UpsampledHumEstimate, HumFrequencies, HumMeanSquaredError] = ...
      HumBlaster(data_sf_cleaned, fs_dec, HB.EstimationHarmonicNumbers, HB.OptimizationHarmonicNumbers, HB.SubtractionHarmonicNumbers, HB.NominalHumFrequency, HB.EstimationSegmentLength, HB.LeastSquaresSegmentLength, HB.UseEstimation);
  else
    data_hum_cleaned = data_sf_cleaned;
  end

%   fprintf('Cleaned hum in %s\n', time_elapsed(t_humblast_start, now));

  % Spectrogram of hum cleaned
  if HB.b_humblast
    s(end+1) = subplot(num_subplots, 1, 3);
    spectrogram_cal(data_hum_cleaned, window, noverlap, nfft, fs_dec, station_name, cal_datenum);
    title(sprintf('%s hum cleaned', strrep(input_filenames{kk}, '_', '\_')));
  end

  linkaxes(s); s = [];
  increase_font;
  ylim([0 fs_dec/2]);

  %% Save output file
  % Increase figure size if we're plotting with -nodisplay
  if strcmp(get(gcf, 'XDisplay'), 'nodisplay')
    figure_grow(gcf, 1.4)
  end

  output_file_struct = file_struct;
  output_file_struct.Fs = fs_dec;

  % Save
  switch station_name
    case 'palmer'
      station_id = 'PA';
    case 'southpole'
      station_id = 'SP';
    otherwise
      station_id = input_filenames{kk}(1:2);
  end

  switch lower(channel)
    case 'n/s'
      channel_num = 0;
    case 'e/w'
      channel_num = 1;
    otherwise
      error('Invalid channel: %s', channel);
  end

  name = sprintf('%s_%04d_%02d_%02dT%02d%02d_%02d_%03d', station_id, file_struct.start_year, ...
    file_struct.start_month, file_struct.start_day, file_struct.start_hour, ...
    file_struct.start_minute, file_struct.start_second, channel_num);

  ext = '.mat';

  output_filenames{end+1} = fullfile(output_dir, [name '_cleaned' ext]);
  write_twochannel_data(output_filenames{end}, output_file_struct, data_hum_cleaned);
  t_file_end = now;
  % disp(sprintf('Wrote %s; cleaning took %s', just_filename(output_filenames{end}), time_elapsed(t_file_start, t_file_end)));

  %% Save output png
  print(h, '-dpng', fullfile(output_dir, [name '_cleaned_diff.png']));
end

function data_filtered = massage_data(raw_data, fs, station_name, data_datenum)
%% Function: massage_data
% Some data needs some additional preprocessing because it's so freaking noisy

switch station_name
  case 'southpole'
    if data_datenum >= datenum([2001 01 01 0 0 0]) && data_datenum < datenum([2002 01 01 0 0 0])
      % Create a mess of notch filters for the multitude of narrowband
      % interference in the south pole data
      fc = [9100, 13.15e3, 18.5e3, 20e3, 20.6e3, 21.6e3, 22.425e3, 22.625e3];
      bw = [200, 150, 200, 300, 200, 300, 100, 150];
      Astops = [5 5 5 5 5 5 5 5]; % Minimum attenuation in dB; this may be overridden if the bandwidth is tight

      filters = {};
      for kk = 1:length(fc)
        bw_pass = bw(kk)*1.5;
        Fpass1 = fc(kk) - bw_pass/2;
        Fstop1 = fc(kk) - bw(kk)/2;
        Fstop2 = fc(kk) + bw(kk)/2;
        Fpass2 = fc(kk) + bw_pass/2;
        Astop = Astops(kk);
        Apass = 1;

        h = fdesign.bandstop('fp1,fst1,fst2,fp2,ap1,ast,ap2', Fpass1, Fstop1, ...
                             Fstop2, Fpass2, Apass, Astop, Apass, fs);
        Hd = design(h, 'butter', 'MatchExactly', 'stopband', 'SOSScaleNorm', 'Linf');

        filters{kk} = Hd;
      end

      % Construct a single cascaded filter
      Hd = dfilt.cascade(filters{:});

      data_filtered = filter(Hd, raw_data);
    else
      data_filtered = raw_data;
    end
  otherwise
    data_filtered = raw_data;
end

function HB = get_humblaster_parameters(station_name, data_datenum)

switch station_name
  case 'palmer'
    HB.b_humblast = true;
    HB.NominalHumFrequency = 60; % Hz
    HB.EstimationHarmonicNumbers = 7:2:31; % Harmonics to fix onto to estimate hum frequency if using Estimation method (not used)
    HB.OptimizationHarmonicNumbers = 7:2:31; % Harmonics to fix onto to estimate hum frequency if using Optimization method
    HB.SubtractionHarmonicNumbers = 7:2:83; % Up to ~5 kHz
    HB.EstimationSegmentLength = 0.2; % Segment length if using estimation method (not used)
    HB.LeastSquaresSegmentLength = 0.2; % Segment length if using optimization method (I think)
    HB.UseEstimation = 1;
  case 'southpole'
    % I used to not humblast for data before 2003, but this was a mistake;
    % I was looking at the N/S spectrograms instead of the E/W
    % spectrograms, which are pretty much equally noise for all years... I
    % think
    % HB.b_humblast = true;
    HB.b_humblast = false;
    HB.NominalHumFrequency = 60; % Hz
    HB.EstimationHarmonicNumbers = 7:2:15;
    HB.OptimizationHarmonicNumbers = 7:2:15;
    HB.SubtractionHarmonicNumbers = 7:2:55;
    HB.EstimationSegmentLength = 0.2;
    HB.LeastSquaresSegmentLength = 0.2;
    HB.UseEstimation = 1;
end


text:
var pkgcloud = require('pkgcloud'),
  logging = require('../../../common/logging'),
  config = require('../../../common/config'),
  _ = require('underscore');

var log = logging.getLogger(process.env.PKGCLOUD_LOG_LEVEL || 'debug');

var client = pkgcloud.providers.azure.storage.createClient(config.getConfig('azure'));

client.on('log::*', logging.logFunction);

client.getContainers(function (err, containers) {
  if (err) {
    log.error(err);
    return;
  }

  containers.forEach(function(container) {
    log.info(container.name);
  });
});


text:
<!DOCTYPE html>

    <title>Announce by ThatGuyHughesy</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Announce - Growl-inspired alerts and messages.</title>
    <meta name="description" content="Growl-inspired alerts and message.">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,900" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/normalize.css" media="screen">
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="css/github-light.css" media="screen">
    <link rel="stylesheet" href="css/welcome.css"/>

Announce

Growl-inspired alerts and messages

    View on GitHub
    Download .zip
    Download .tar.gz

        Demo

        Require

- JQuery

        Including

Javscript

        <script src="announce.min.js"></script>

CSS

        <link rel="stylesheet" href="announce.min.css"/>

        Usage

        var announce = new Announce({
    position: 'bottom-right',
    timeout: true,
    timeoutDelay: 3000
});

announce.post({
    message: 'This is an announcement!',
    type: 'notice'
});

announce.post({
    message: 'This is a warning!',
    type: 'warning',
    dismiss: true
});

        Configuration

Configuration can be both global and post specific, post configuration options override global.

        var announce = new Announce({
    position: 'bottom-right',
    timeout: true,
    timeoutDelay: 3000
});

announce.post({
    message: 'This will timeout in 3 seconds!',
    type: 'notice',
});

announce.post({
    message: 'This will timeout in 6 seconds not 3!',
    type: 'notice',
    timeoutDelay: 6000
});

Global configuration options:

        position: Where the alerts appear on screen (top-left, bottom-left, top-right, bottom-right, top-center, bottom-center)
theme: Alert styling (default-theme)
timeout: Alert can timeout (boolean)
timeoutDelay: How long the alert stays on screen (1 to 60 seconds)
dismiss: Alert can be dismissed (boolean)

Post configuration options:

message: Text of the alert
type: Alert type (notice, success, warning, danger)

        Authors and Contributors

Conor Hughes (@thatguyhughesy).

            Announce is maintained by
            ThatGuyHughesy.

            This page was generated by GitHub Pages using the
            Cayman theme by
            Jason Long.


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>WebGL GLSL conformance test: build_129_to_136.html</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css" />
<link rel="stylesheet" href="../../../../resources/ogles-tests.css" />

<canvas id="example" width="500" height="500" style="width: 16px; height: 16px;"></canvas>


text:
<!DOCTYPE html>
<meta name="color-scheme" content="light dark">

<select multiple autofocus size=5>
  <optgroup label="unstyled">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected selected id="hoverTarget">2nd selected (hovered)</option>
  </optgroup>
</select>

<select multiple disabled size=5>
  <optgroup label="disabled select">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple disabled size=5>
  <optgroup label="disabled select black-bg">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple>
  <optgroup label="disabled option">
    <option selected>first selected option</option>
    <option disabled>disabled unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple>
    <optgroup label="disabled selected option">
      <option disabled selected>disabled first selected option</option>
      <option>unselected option</option>
      <option selected>second selected option</option>
    </optgroup>
  </select>

<select multiple style="border: 3px solid lime;">
  <optgroup label="thick lime border">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>
<select multiple style="border-radius: 6px;">
  <optgroup label="border-radius: 6px">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select dir="rtl" multiple>
  <optgroup label="right-to-left">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple style="background: linear-gradient(to bottom, #dea 0%,#9c7 44%,#494 100%);">
  <optgroup label="gradient background">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple style="background-color: blue;">
  <optgroup label="background-color: blue">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple style="background-color: blue;">
  <option selected>selected option</option>
  <option>unselected option</option>
  <option>unselected option</option>
</select>

<select multiple style="box-shadow: 4px 4px 10px rgba(255,0,0,0.5), inset 4px 4px 4px rgba(0,255,0,0.5);">
  <optgroup label="box-shadow">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple style="width: 8px; height: 8px;">
  <optgroup label="size: 8px">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>
<select multiple style="width: 16px; height: 16px;">
  <optgroup label="size: 16px">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup></select>
<select multiple style="width: 24px; height: 24px;">
  <optgroup label="size: 24px">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>
<select multiple style="width: 26px; height: 20px;">
  <optgroup label="width: 26px; height: 20px">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>
<select multiple style="width: 60px; height: 60px;">
  <optgroup label="size: 60px">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>

<select multiple style="zoom: 1.5;">
  <optgroup label="zoom: 1.5">
    <option selected>first selected option</option>
    <option>unselected option</option>
    <option selected>second selected option</option>
  </optgroup>
</select>


text:
using Mango.Dependencies.StructureMap;
using StructureMap;

namespace Mango.Dependencies
{
    public static class IoC
    {
        private static IContainer _container;

        public static IContainer Container => _container ?? (_container = Initialize());

        public static IContainer Initialize()
        {
            _container = new Container(c => c.AddRegistry<IocRegistry>());
            IocRegistry.RegisterMappings(_container);
            return _container;
        }
    }
}


text:
from Module import AbstractModule

class Module(AbstractModule):
    def __init__(self):
        AbstractModule.__init__(self)

    def run(
        self, network, in_data, out_attributes, user_options, num_cores,
        out_path):
        from genomicode import config
        from genomicode import filelib
        from genomicode import parallel
        from genomicode import alignlib

        samtools = filelib.which_assert(config.samtools)
        ref = alignlib.standardize_reference_genome(
            in_data.identifier, out_path, use_symlinks=True)

        ## fa_filenames = module_utils.find_fasta_files(out_path)
        ## # Filter out the FASTA files created by RSEM indexing.
        ## # <assembly>.idx.fa
        ## # <assembly>.n2g.idx.fa
        ## # <assembly>.transcripts.fa
        ## # Could these end with ".fasta"?
        ## x = fa_filenames
        ## x = [x for x in x if not x.endswith(".idx.fa")]
        ## x = [x for x in x if not x.endswith(".n2g.idx.fa")]
        ## x = [x for x in x if not x.endswith(".transcripts.fa")]
        ## fa_filenames = x
        ## assert fa_filenames, "Could not find reference genome."
        ## assert len(fa_filenames) == 1, "Found multiple reference genomes."
        ## reference_filename = fa_filenames[0]

        # samtools faidx <ref>.fa
        # Makes files:
        # <ref>.fa.fai

        sq = parallel.quote
        cmd = [
            sq(samtools),
            "faidx",
            sq(ref.fasta_file_full),
            ]
        parallel.sshell(cmd, path=out_path)

        # Check to make sure index was created successfully.
        f = "%s.fai" % ref.fasta_file_full
        assert filelib.exists_nz(f)

    def name_outfile(self, antecedents, user_options):
        # Should name outfile based on the assembly.
        return "reference.samtools"


text:
package org.apache.causeway.testdomain.model.interaction;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import lombok.Value;
import lombok.experimental.Accessors;

final class ParameterSamples {

    // -- SCALAR PARAMS

    @Value @Accessors(fluent = true)
    public static class BiInt {
        int a;
        int b;
    }

    @Value @Accessors(fluent = true)
    public static class TriInt {
        int a;
        int b;
        int c;
    }

    @Value @Accessors(fluent = true)
    public static class TriEnum {
        DemoEnum a;
        DemoEnum b;
        DemoEnum c;
    }

    // -- NON SCALAR PARAMS

    @Value @Accessors(fluent = true)
    public static class BiListOfString {
        List<String> a;
        List<String> b;
    }

    @Value @Accessors(fluent = true)
    public static class BiSetOfString {
        Set<String> a;
        Set<String> b;
    }

    @Value @Accessors(fluent = true)
    public static class BiArrayOfInt {
        int[] a;
        int[] b;
    }

    @Value @Accessors(fluent = true)
    public static class BiArrayOfEnum {
        DemoEnum[] a;
        DemoEnum[] b;
    }

    @Value @Accessors(fluent = true)
    public static class BiCollectionOfEnum {
        Collection<DemoEnum> a;
        Collection<DemoEnum> b;
    }

}


text:
A simple Lacinia tutorial

# Installation

* Clone the repo and run `python createdb.py` to create database as `test.db`
* Rename `test.db` as `dev.db`
* Download the jar from [releases](https://github.com/tirkarthi/lacinia-tutorial/releases).
* Unzip the file with `gunzip <release.gz>`
* Run the jar using `java -jar <jar_file>`
* IGraphQL is present at `localhost:8888`

# Demo

![IGraphQL](https://github.com/tirkarthi/lacinia-tutorial/raw/master/demo.gif)

# License

Copyright © 2017 Karthikeyan S

Distributed under the MIT License


text:
package se.cygni.snake.apiconversion;

import se.cygni.game.WorldState;
import se.cygni.snake.api.event.GameEndedEvent;
import se.cygni.snake.api.event.GameStartingEvent;
import se.cygni.snake.api.event.MapUpdateEvent;
import se.cygni.snake.api.event.SnakeDeadEvent;
import se.cygni.snake.api.model.DeathReason;

public class GameMessageConverter {

    public static MapUpdateEvent onWorldUpdate(WorldState worldState, String gameId, long gameTick) {

        MapUpdateEvent mue = new MapUpdateEvent(
                gameTick,
                gameId,
                WorldStateConverter.convertWorldState(worldState, gameTick));

        return mue;
    }

    public static SnakeDeadEvent onPlayerDied(DeathReason reason, String playerId, int x, int y, String gameId, long gameTick) {

        SnakeDeadEvent sde = new SnakeDeadEvent(reason, playerId, x, y, gameId, gameTick);

        return sde;
    }

    public static GameEndedEvent onGameEnded(String playerWinnerId, String gameId, long gameTick, WorldState worldState) {

        GameEndedEvent gee = new GameEndedEvent(
                playerWinnerId, gameId, gameTick,
                WorldStateConverter.convertWorldState(worldState, gameTick)
        );

        return gee;
    }

    public static GameStartingEvent onGameStart(String gameId, int noofPlayers, int width, int height) {

        GameStartingEvent gse = new GameStartingEvent(gameId, noofPlayers, width, height);

        return gse;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="fos_user_group_list" path="/list" methods="GET">
        <default key="_controller">FOSUserBundle:Group:list</default>
    </route>

    <route id="fos_user_group_new" path="/new" methods="GET POST">
        <default key="_controller">FOSUserBundle:Group:new</default>
    </route>

    <route id="fos_user_group_show" path="/{groupname}" methods="GET">
        <default key="_controller">FOSUserBundle:Group:show</default>
    </route>

    <route id="fos_user_group_edit" path="/{groupname}/edit" methods="GET POST">
        <default key="_controller">FOSUserBundle:Group:edit</default>
    </route>

    <route id="fos_user_group_delete" path="/{groupname}/delete" methods="GET">
        <default key="_controller">FOSUserBundle:Group:delete</default>
    </route>

    <route id="sonata_user_group_list" path="/list" methods="GET">
        <default key="_controller">FOSUserBundle:Group:list</default>
    </route>

    <route id="sonata_user_group_new" path="/new" methods="GET POST">
        <default key="_controller">FOSUserBundle:Group:new</default>
    </route>

    <route id="sonata_user_group_show" path="/{groupname}" methods="GET">
        <default key="_controller">FOSUserBundle:Group:show</default>
    </route>

    <route id="sonata_user_group_edit" path="/{groupname}/edit" methods="GET POST">
        <default key="_controller">FOSUserBundle:Group:edit</default>
    </route>

    <route id="sonata_user_group_delete" path="/{groupname}/delete" methods="GET">
        <default key="_controller">FOSUserBundle:Group:delete</default>
    </route>

</routes>


text:
UX Aspects 2.1.1 is now available! Check out the documentation at [uxaspects.github.io/UXAspects](https://uxaspects.github.io/UXAspects).

#### Installation
```bash
npm install @ux-aspects/ux-aspects@2.1.1
```

#### Bug Fixes and Improvements
* (EL-4014) [Column Picker](https://uxaspects.github.io/UXAspects/#/components/tables#column-picker) - the `deselected` binding is once again updated after selecting columns.
* (EL-4014) [Column Picker](https://uxaspects.github.io/UXAspects/#/components/tables#column-picker) - the type of the `selected` binding has changed to `ReadonlyArray<string | ColumnPickerGroupItem>`, so that it is compatible with the data provided to the `deselected` binding.
* (EL-4014) [Column Picker](https://uxaspects.github.io/UXAspects/#/components/tables#column-picker) - the list of deselected columns is no longer sorted by default; the `sort` input is now available to restore that functionality if needed.
* (EL-4023) [Tree Grid](https://uxaspects.github.io/UXAspects/#/components/tree-view#tree-grid) - resolved another performance issue.
* (EL-4023) [Tree Grid](https://uxaspects.github.io/UXAspects/#/components/tree-view#tree-grid) - deprecated the unused `rows` input; see example code for the new recommended way to bind the tree grid rows.

Any questions or feedback? Feel free to open an issue on [GitHub](https://github.com/UXAspects/UXAspects/issues)!


text:
/**
 * @ngdoc object
 * @name ng.$cacheFactory
 *
 * @description
 * Factory that constructs cache objects.
 *
 *
 * @param {string} cacheId Name or id of the newly created cache.
 * @param {object=} options Options object that specifies the cache behavior. Properties:
 *
 *   - `{number=}` `capacity` — turns the cache into LRU cache.
 *
 * @returns {object} Newly created cache object with the following set of methods:
 *
 * - `{object}` `info()` — Returns id, size, and options of cache.
 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it.
 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
 * - `{void}` `removeAll()` — Removes all cached values.
 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
 *
 */
function $CacheFactoryProvider() {

  this.$get = function() {
    var caches = {};

    function cacheFactory(cacheId, options) {
      if (cacheId in caches) {
        throw Error('cacheId ' + cacheId + ' taken');
      }

      var size = 0,
          stats = extend({}, options, {id: cacheId}),
          data = {},
          capacity = (options && options.capacity) || Number.MAX_VALUE,
          lruHash = {},
          freshEnd = null,
          staleEnd = null;

      return caches[cacheId] = {

        put: function(key, value) {
          var lruEntry = lruHash[key] || (lruHash[key] = {key: key});

          refresh(lruEntry);

          if (isUndefined(value)) return;
          if (!(key in data)) size++;
          data[key] = value;

          if (size > capacity) {
            this.remove(staleEnd.key);
          }

          return value;
        },

        get: function(key) {
          var lruEntry = lruHash[key];

          if (!lruEntry) return;

          refresh(lruEntry);

          return data[key];
        },

        remove: function(key) {
          var lruEntry = lruHash[key];

          if (!lruEntry) return;

          if (lruEntry == freshEnd) freshEnd = lruEntry.p;
          if (lruEntry == staleEnd) staleEnd = lruEntry.n;
          link(lruEntry.n,lruEntry.p);

          delete lruHash[key];
          delete data[key];
          size--;
        },

        removeAll: function() {
          data = {};
          size = 0;
          lruHash = {};
          freshEnd = staleEnd = null;
        },

        destroy: function() {
          data = null;
          stats = null;
          lruHash = null;
          delete caches[cacheId];
        },

        info: function() {
          return extend({}, stats, {size: size});
        }
      };

      /**
       * makes the `entry` the freshEnd of the LRU linked list
       */
      function refresh(entry) {
        if (entry != freshEnd) {
          if (!staleEnd) {
            staleEnd = entry;
          } else if (staleEnd == entry) {
            staleEnd = entry.n;
          }

          link(entry.n, entry.p);
          link(entry, freshEnd);
          freshEnd = entry;
          freshEnd.n = null;
        }
      }

      /**
       * bidirectionally links two entries of the LRU linked list
       */
      function link(nextEntry, prevEntry) {
        if (nextEntry != prevEntry) {
          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
        }
      }
    }

    cacheFactory.info = function() {
      var info = {};
      forEach(caches, function(cache, cacheId) {
        info[cacheId] = cache.info();
      });
      return info;
    };

    cacheFactory.get = function(cacheId) {
      return caches[cacheId];
    };

    return cacheFactory;
  };
}

/**
 * @ngdoc object
 * @name ng.$templateCache
 *
 * @description
 * Cache used for storing html templates.
 *
 * See {@link ng.$cacheFactory $cacheFactory}.
 *
 */
function $TemplateCacheProvider() {
  this.$get = ['$cacheFactory', function($cacheFactory) {
    return $cacheFactory('templates');
  }];
}


text:
using System.ComponentModel;
using bytePassion.Lib.FrameworkExtensions;
using OQF.Bot.Contracts.Coordination;

namespace OQF.PlayerVsBot.Visualization.ViewModels.ActionBar.Helper
{
	public class StartOptionsDisplayData : INotifyPropertyChanged
	{
		private string displayCaption;

		public StartOptionsDisplayData(PlayerType playerStartingType, string displayCaption)
		{
			PlayerStartingType = playerStartingType;
			DisplayCaption = displayCaption;
		}

		public string DisplayCaption
		{
			get { return displayCaption; }
			set { PropertyChanged.ChangeAndNotify(this, ref displayCaption, value); }
		}

		public PlayerType PlayerStartingType { get; }

		public event PropertyChangedEventHandler PropertyChanged;
	}
}


text:
CREATE DEFINER=`root`@`localhost` PROCEDURE `total_countries`()
BEGIN
	select
		'Total Countries', count(*),
		'World Population', sum(Population),
		'World Surface Area', sum(SurfaceArea),
        'Avg Life Expectancy', avg(LifeExpectancy)
    from
		country;
END


text:
"""
Demonstrate what basic_usage's unihan=True (default Cihai) does under
the hood.
"""
from __future__ import print_function, unicode_literals

from cihai.core import Cihai

def run(unihan_options={}):
    c = Cihai(unihan=False)
    c.add_dataset('cihai.data.unihan.dataset.Unihan', namespace='unihan')

    if not c.unihan.is_bootstrapped:  # download and install Unihan to db
        c.unihan.bootstrap(unihan_options)

    query = c.unihan.lookup_char('好')
    glyph = query.first()
    print("lookup for 好: %s" % glyph.kDefinition)

    query = c.unihan.reverse_char('good')
    print('matches for "good": %s ' % ', '.join([glph.char for glph in query]))

if __name__ == '__main__':
    run()


text:
				<?php
				if (has_nav_menu('language_navigation')) :
					wp_nav_menu(array('theme_location' => 'language_navigation', 'menu_class' => 'navbar__nav navbar--languages__ul--top'));
				endif;
				?>

				<?php
				if (has_nav_menu('contact_navigation--top')) :
					wp_nav_menu(array('theme_location' => 'contact_navigation--top', 'menu_class' => 'navbar--contact--top__ul'));
				endif;
				?>

			<a class="navbar-brand js-site-nav" href="<?php echo esc_url(home_url('/')); ?>">

					<?php bloginfo('name'); ?>
					<?php dynamic_sidebar('sidebar-subtitle'); ?>


text:
require 'spec_helper'

describe Github::Client::Users::Followers, '#unfollow' do
  let(:request_path) { "/user/following/#{user}" }
  let(:user)   { 'peter-murach' }
  let(:body) { '[]' }
  let(:status) { 204 }

  before {
    subject.oauth_token = OAUTH_TOKEN
    stub_delete(request_path).with(:query => {:access_token => OAUTH_TOKEN}).
    to_return(:body => body, :status => status,
      :headers => {:content_type => "application/json; charset=utf-8"})
  }

  after { reset_authentication_for(subject) }

  it "should raise error if gist id not present" do
    expect { subject.unfollow }.to raise_error(ArgumentError)
  end

  it 'successfully unfollows a user' do
    subject.unfollow(user)
    a_delete(request_path).with(:query => { :access_token => OAUTH_TOKEN}).
      should have_been_made
  end

  it "should return 204 with a message 'Not Found'" do
    subject.unfollow(user).status.should be 204
  end
end # unfollow