repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
chaintope/bitcoinrb
lib/bitcoin/mnemonic.rb
Bitcoin.Mnemonic.checksum
def checksum(entropy) b = Bitcoin.sha256([entropy].pack('B*')).unpack('B*').first b.slice(0, (entropy.length/32)) end
ruby
def checksum(entropy) b = Bitcoin.sha256([entropy].pack('B*')).unpack('B*').first b.slice(0, (entropy.length/32)) end
[ "def", "checksum", "(", "entropy", ")", "b", "=", "Bitcoin", ".", "sha256", "(", "[", "entropy", "]", ".", "pack", "(", "'B*'", ")", ")", ".", "unpack", "(", "'B*'", ")", ".", "first", "b", ".", "slice", "(", "0", ",", "(", "entropy", ".", "length", "/", "32", ")", ")", "end" ]
calculate entropy checksum @param [String] entropy an entropy with bit string format @return [String] an entropy checksum with bit string format
[ "calculate", "entropy", "checksum" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L63-L66
train
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.to_wif
def to_wif version = Bitcoin.chain_params.privkey_version hex = version + priv_key hex += '01' if compressed? hex += Bitcoin.calc_checksum(hex) Base58.encode(hex) end
ruby
def to_wif version = Bitcoin.chain_params.privkey_version hex = version + priv_key hex += '01' if compressed? hex += Bitcoin.calc_checksum(hex) Base58.encode(hex) end
[ "def", "to_wif", "version", "=", "Bitcoin", ".", "chain_params", ".", "privkey_version", "hex", "=", "version", "+", "priv_key", "hex", "+=", "'01'", "if", "compressed?", "hex", "+=", "Bitcoin", ".", "calc_checksum", "(", "hex", ")", "Base58", ".", "encode", "(", "hex", ")", "end" ]
export private key with wif format
[ "export", "private", "key", "with", "wif", "format" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L80-L86
train
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.sign
def sign(data, low_r = true, extra_entropy = nil) sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) if low_r && !sig_has_low_r?(sig) counter = 1 until sig_has_low_r?(sig) extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) counter += 1 end end sig end
ruby
def sign(data, low_r = true, extra_entropy = nil) sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) if low_r && !sig_has_low_r?(sig) counter = 1 until sig_has_low_r?(sig) extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) counter += 1 end end sig end
[ "def", "sign", "(", "data", ",", "low_r", "=", "true", ",", "extra_entropy", "=", "nil", ")", "sig", "=", "secp256k1_module", ".", "sign_data", "(", "data", ",", "priv_key", ",", "extra_entropy", ")", "if", "low_r", "&&", "!", "sig_has_low_r?", "(", "sig", ")", "counter", "=", "1", "until", "sig_has_low_r?", "(", "sig", ")", "extra_entropy", "=", "[", "counter", "]", ".", "pack", "(", "'I*'", ")", ".", "bth", ".", "ljust", "(", "64", ",", "'0'", ")", ".", "htb", "sig", "=", "secp256k1_module", ".", "sign_data", "(", "data", ",", "priv_key", ",", "extra_entropy", ")", "counter", "+=", "1", "end", "end", "sig", "end" ]
sign +data+ with private key @param [String] data a data to be signed with binary format @param [Boolean] low_r flag to apply low-R. @param [String] extra_entropy the extra entropy for rfc6979. @return [String] signature data with binary format
[ "sign", "+", "data", "+", "with", "private", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L93-L104
train
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.verify
def verify(sig, origin) return false unless valid_pubkey? begin sig = ecdsa_signature_parse_der_lax(sig) secp256k1_module.verify_sig(origin, sig, pubkey) rescue Exception false end end
ruby
def verify(sig, origin) return false unless valid_pubkey? begin sig = ecdsa_signature_parse_der_lax(sig) secp256k1_module.verify_sig(origin, sig, pubkey) rescue Exception false end end
[ "def", "verify", "(", "sig", ",", "origin", ")", "return", "false", "unless", "valid_pubkey?", "begin", "sig", "=", "ecdsa_signature_parse_der_lax", "(", "sig", ")", "secp256k1_module", ".", "verify_sig", "(", "origin", ",", "sig", ",", "pubkey", ")", "rescue", "Exception", "false", "end", "end" ]
verify signature using public key @param [String] sig signature data with binary format @param [String] origin original message @return [Boolean] verify result
[ "verify", "signature", "using", "public", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L110-L118
train
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.to_point
def to_point p = pubkey p ||= generate_pubkey(priv_key, compressed: compressed) ECDSA::Format::PointOctetString.decode(p.htb, Bitcoin::Secp256k1::GROUP) end
ruby
def to_point p = pubkey p ||= generate_pubkey(priv_key, compressed: compressed) ECDSA::Format::PointOctetString.decode(p.htb, Bitcoin::Secp256k1::GROUP) end
[ "def", "to_point", "p", "=", "pubkey", "p", "||=", "generate_pubkey", "(", "priv_key", ",", "compressed", ":", "compressed", ")", "ECDSA", "::", "Format", "::", "PointOctetString", ".", "decode", "(", "p", ".", "htb", ",", "Bitcoin", "::", "Secp256k1", "::", "GROUP", ")", "end" ]
generate pubkey ec point @return [ECDSA::Point]
[ "generate", "pubkey", "ec", "point" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L149-L153
train
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.ecdsa_signature_parse_der_lax
def ecdsa_signature_parse_der_lax(sig) sig_array = sig.unpack('C*') len_r = sig_array[3] r = sig_array[4...(len_r+4)].pack('C*').bth len_s = sig_array[len_r + 5] s = sig_array[(len_r + 6)...(len_r + 6 + len_s)].pack('C*').bth ECDSA::Signature.new(r.to_i(16), s.to_i(16)).to_der end
ruby
def ecdsa_signature_parse_der_lax(sig) sig_array = sig.unpack('C*') len_r = sig_array[3] r = sig_array[4...(len_r+4)].pack('C*').bth len_s = sig_array[len_r + 5] s = sig_array[(len_r + 6)...(len_r + 6 + len_s)].pack('C*').bth ECDSA::Signature.new(r.to_i(16), s.to_i(16)).to_der end
[ "def", "ecdsa_signature_parse_der_lax", "(", "sig", ")", "sig_array", "=", "sig", ".", "unpack", "(", "'C*'", ")", "len_r", "=", "sig_array", "[", "3", "]", "r", "=", "sig_array", "[", "4", "...", "(", "len_r", "+", "4", ")", "]", ".", "pack", "(", "'C*'", ")", ".", "bth", "len_s", "=", "sig_array", "[", "len_r", "+", "5", "]", "s", "=", "sig_array", "[", "(", "len_r", "+", "6", ")", "...", "(", "len_r", "+", "6", "+", "len_s", ")", "]", ".", "pack", "(", "'C*'", ")", ".", "bth", "ECDSA", "::", "Signature", ".", "new", "(", "r", ".", "to_i", "(", "16", ")", ",", "s", ".", "to_i", "(", "16", ")", ")", ".", "to_der", "end" ]
Supported violations include negative integers, excessive padding, garbage at the end, and overly long length descriptors. This is safe to use in Bitcoin because since the activation of BIP66, signatures are verified to be strict DER before being passed to this module, and we know it supports all violations present in the blockchain before that point.
[ "Supported", "violations", "include", "negative", "integers", "excessive", "padding", "garbage", "at", "the", "end", "and", "overly", "long", "length", "descriptors", ".", "This", "is", "safe", "to", "use", "in", "Bitcoin", "because", "since", "the", "activation", "of", "BIP66", "signatures", "are", "verified", "to", "be", "strict", "DER", "before", "being", "passed", "to", "this", "module", "and", "we", "know", "it", "supports", "all", "violations", "present", "in", "the", "blockchain", "before", "that", "point", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L270-L277
train
chaintope/bitcoinrb
lib/bitcoin/base58.rb
Bitcoin.Base58.encode
def encode(hex) leading_zero_bytes = (hex.match(/^([0]+)/) ? $1 : '').size / 2 int_val = hex.to_i(16) base58_val = '' while int_val > 0 int_val, remainder = int_val.divmod(SIZE) base58_val = ALPHABET[remainder] + base58_val end ('1' * leading_zero_bytes) + base58_val end
ruby
def encode(hex) leading_zero_bytes = (hex.match(/^([0]+)/) ? $1 : '').size / 2 int_val = hex.to_i(16) base58_val = '' while int_val > 0 int_val, remainder = int_val.divmod(SIZE) base58_val = ALPHABET[remainder] + base58_val end ('1' * leading_zero_bytes) + base58_val end
[ "def", "encode", "(", "hex", ")", "leading_zero_bytes", "=", "(", "hex", ".", "match", "(", "/", "/", ")", "?", "$1", ":", "''", ")", ".", "size", "/", "2", "int_val", "=", "hex", ".", "to_i", "(", "16", ")", "base58_val", "=", "''", "while", "int_val", ">", "0", "int_val", ",", "remainder", "=", "int_val", ".", "divmod", "(", "SIZE", ")", "base58_val", "=", "ALPHABET", "[", "remainder", "]", "+", "base58_val", "end", "(", "'1'", "*", "leading_zero_bytes", ")", "+", "base58_val", "end" ]
encode hex value to base58 string.
[ "encode", "hex", "value", "to", "base58", "string", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/base58.rb#L12-L21
train
chaintope/bitcoinrb
lib/bitcoin/base58.rb
Bitcoin.Base58.decode
def decode(base58_val) int_val = 0 base58_val.reverse.split(//).each_with_index do |char,index| raise ArgumentError, 'Value passed not a valid Base58 String.' if (char_index = ALPHABET.index(char)).nil? int_val += char_index * (SIZE ** index) end s = int_val.to_even_length_hex s = '' if s == '00' leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size s = ('00' * leading_zero_bytes) + s if leading_zero_bytes > 0 s end
ruby
def decode(base58_val) int_val = 0 base58_val.reverse.split(//).each_with_index do |char,index| raise ArgumentError, 'Value passed not a valid Base58 String.' if (char_index = ALPHABET.index(char)).nil? int_val += char_index * (SIZE ** index) end s = int_val.to_even_length_hex s = '' if s == '00' leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size s = ('00' * leading_zero_bytes) + s if leading_zero_bytes > 0 s end
[ "def", "decode", "(", "base58_val", ")", "int_val", "=", "0", "base58_val", ".", "reverse", ".", "split", "(", "/", "/", ")", ".", "each_with_index", "do", "|", "char", ",", "index", "|", "raise", "ArgumentError", ",", "'Value passed not a valid Base58 String.'", "if", "(", "char_index", "=", "ALPHABET", ".", "index", "(", "char", ")", ")", ".", "nil?", "int_val", "+=", "char_index", "*", "(", "SIZE", "**", "index", ")", "end", "s", "=", "int_val", ".", "to_even_length_hex", "s", "=", "''", "if", "s", "==", "'00'", "leading_zero_bytes", "=", "(", "base58_val", ".", "match", "(", "/", "/", ")", "?", "$1", ":", "''", ")", ".", "size", "s", "=", "(", "'00'", "*", "leading_zero_bytes", ")", "+", "s", "if", "leading_zero_bytes", ">", "0", "s", "end" ]
decode base58 string to hex value.
[ "decode", "base58", "string", "to", "hex", "value", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/base58.rb#L24-L35
train
chaintope/bitcoinrb
lib/bitcoin/block.rb
Bitcoin.Block.calculate_witness_commitment
def calculate_witness_commitment witness_hashes = [COINBASE_WTXID] witness_hashes += (transactions[1..-1].map(&:witness_hash)) reserved_value = transactions[0].inputs[0].script_witness.stack.map(&:bth).join root_hash = Bitcoin::MerkleTree.build_from_leaf(witness_hashes).merkle_root Bitcoin.double_sha256([root_hash + reserved_value].pack('H*')).bth end
ruby
def calculate_witness_commitment witness_hashes = [COINBASE_WTXID] witness_hashes += (transactions[1..-1].map(&:witness_hash)) reserved_value = transactions[0].inputs[0].script_witness.stack.map(&:bth).join root_hash = Bitcoin::MerkleTree.build_from_leaf(witness_hashes).merkle_root Bitcoin.double_sha256([root_hash + reserved_value].pack('H*')).bth end
[ "def", "calculate_witness_commitment", "witness_hashes", "=", "[", "COINBASE_WTXID", "]", "witness_hashes", "+=", "(", "transactions", "[", "1", "..", "-", "1", "]", ".", "map", "(", ":witness_hash", ")", ")", "reserved_value", "=", "transactions", "[", "0", "]", ".", "inputs", "[", "0", "]", ".", "script_witness", ".", "stack", ".", "map", "(", ":bth", ")", ".", "join", "root_hash", "=", "Bitcoin", "::", "MerkleTree", ".", "build_from_leaf", "(", "witness_hashes", ")", ".", "merkle_root", "Bitcoin", ".", "double_sha256", "(", "[", "root_hash", "+", "reserved_value", "]", ".", "pack", "(", "'H*'", ")", ")", ".", "bth", "end" ]
calculate witness commitment from tx list.
[ "calculate", "witness", "commitment", "from", "tx", "list", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/block.rb#L57-L63
train
chaintope/bitcoinrb
lib/bitcoin/block.rb
Bitcoin.Block.height
def height return nil if header.version < 2 coinbase_tx = transactions[0] return nil unless coinbase_tx.coinbase_tx? buf = StringIO.new(coinbase_tx.inputs[0].script_sig.to_payload) len = Bitcoin.unpack_var_int_from_io(buf) buf.read(len).reverse.bth.to_i(16) end
ruby
def height return nil if header.version < 2 coinbase_tx = transactions[0] return nil unless coinbase_tx.coinbase_tx? buf = StringIO.new(coinbase_tx.inputs[0].script_sig.to_payload) len = Bitcoin.unpack_var_int_from_io(buf) buf.read(len).reverse.bth.to_i(16) end
[ "def", "height", "return", "nil", "if", "header", ".", "version", "<", "2", "coinbase_tx", "=", "transactions", "[", "0", "]", "return", "nil", "unless", "coinbase_tx", ".", "coinbase_tx?", "buf", "=", "StringIO", ".", "new", "(", "coinbase_tx", ".", "inputs", "[", "0", "]", ".", "script_sig", ".", "to_payload", ")", "len", "=", "Bitcoin", ".", "unpack_var_int_from_io", "(", "buf", ")", "buf", ".", "read", "(", "len", ")", ".", "reverse", ".", "bth", ".", "to_i", "(", "16", ")", "end" ]
return this block height. block height is included in coinbase. if block version under 1, height does not include in coinbase, so return nil.
[ "return", "this", "block", "height", ".", "block", "height", "is", "included", "in", "coinbase", ".", "if", "block", "version", "under", "1", "height", "does", "not", "include", "in", "coinbase", "so", "return", "nil", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/block.rb#L67-L74
train
chaintope/bitcoinrb
lib/openassets/payload.rb
OpenAssets.Payload.to_payload
def to_payload payload = String.new payload << MARKER payload << VERSION payload << Bitcoin.pack_var_int(quantities.size) << quantities.map{|q| LEB128.encode_unsigned(q).read }.join payload << Bitcoin.pack_var_int(metadata.length) << metadata.bytes.map{|b| sprintf("%02x", b)}.join.htb payload end
ruby
def to_payload payload = String.new payload << MARKER payload << VERSION payload << Bitcoin.pack_var_int(quantities.size) << quantities.map{|q| LEB128.encode_unsigned(q).read }.join payload << Bitcoin.pack_var_int(metadata.length) << metadata.bytes.map{|b| sprintf("%02x", b)}.join.htb payload end
[ "def", "to_payload", "payload", "=", "String", ".", "new", "payload", "<<", "MARKER", "payload", "<<", "VERSION", "payload", "<<", "Bitcoin", ".", "pack_var_int", "(", "quantities", ".", "size", ")", "<<", "quantities", ".", "map", "{", "|", "q", "|", "LEB128", ".", "encode_unsigned", "(", "q", ")", ".", "read", "}", ".", "join", "payload", "<<", "Bitcoin", ".", "pack_var_int", "(", "metadata", ".", "length", ")", "<<", "metadata", ".", "bytes", ".", "map", "{", "|", "b", "|", "sprintf", "(", "\"%02x\"", ",", "b", ")", "}", ".", "join", ".", "htb", "payload", "end" ]
generate binary payload
[ "generate", "binary", "payload" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/openassets/payload.rb#L43-L50
train
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.hash160
def hash160(hex) Digest::RMD160.hexdigest(Digest::SHA256.digest(hex.htb)) end
ruby
def hash160(hex) Digest::RMD160.hexdigest(Digest::SHA256.digest(hex.htb)) end
[ "def", "hash160", "(", "hex", ")", "Digest", "::", "RMD160", ".", "hexdigest", "(", "Digest", "::", "SHA256", ".", "digest", "(", "hex", ".", "htb", ")", ")", "end" ]
generate sha256-ripemd160 hash for value
[ "generate", "sha256", "-", "ripemd160", "hash", "for", "value" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L86-L88
train
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.encode_base58_address
def encode_base58_address(hex, addr_version) base = addr_version + hex Base58.encode(base + calc_checksum(base)) end
ruby
def encode_base58_address(hex, addr_version) base = addr_version + hex Base58.encode(base + calc_checksum(base)) end
[ "def", "encode_base58_address", "(", "hex", ",", "addr_version", ")", "base", "=", "addr_version", "+", "hex", "Base58", ".", "encode", "(", "base", "+", "calc_checksum", "(", "base", ")", ")", "end" ]
encode Base58 check address. @param [String] hex the address payload. @param [String] addr_version the address version for P2PKH and P2SH. @return [String] Base58 check encoding address.
[ "encode", "Base58", "check", "address", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L94-L97
train
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.decode_base58_address
def decode_base58_address(addr) hex = Base58.decode(addr) if hex.size == 50 && calc_checksum(hex[0...-8]) == hex[-8..-1] raise 'Invalid version bytes.' unless [Bitcoin.chain_params.address_version, Bitcoin.chain_params.p2sh_version].include?(hex[0..1]) [hex[2...-8], hex[0..1]] else raise 'Invalid address.' end end
ruby
def decode_base58_address(addr) hex = Base58.decode(addr) if hex.size == 50 && calc_checksum(hex[0...-8]) == hex[-8..-1] raise 'Invalid version bytes.' unless [Bitcoin.chain_params.address_version, Bitcoin.chain_params.p2sh_version].include?(hex[0..1]) [hex[2...-8], hex[0..1]] else raise 'Invalid address.' end end
[ "def", "decode_base58_address", "(", "addr", ")", "hex", "=", "Base58", ".", "decode", "(", "addr", ")", "if", "hex", ".", "size", "==", "50", "&&", "calc_checksum", "(", "hex", "[", "0", "...", "-", "8", "]", ")", "==", "hex", "[", "-", "8", "..", "-", "1", "]", "raise", "'Invalid version bytes.'", "unless", "[", "Bitcoin", ".", "chain_params", ".", "address_version", ",", "Bitcoin", ".", "chain_params", ".", "p2sh_version", "]", ".", "include?", "(", "hex", "[", "0", "..", "1", "]", ")", "[", "hex", "[", "2", "...", "-", "8", "]", ",", "hex", "[", "0", "..", "1", "]", "]", "else", "raise", "'Invalid address.'", "end", "end" ]
decode Base58 check encoding address. @param [String] addr address. @return [Array] hex and address version
[ "decode", "Base58", "check", "encoding", "address", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L102-L110
train
chaintope/bitcoinrb
lib/bitcoin/validation.rb
Bitcoin.Validation.check_tx
def check_tx(tx, state) # Basic checks that don't depend on any context if tx.inputs.empty? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vin-empty') end if tx.outputs.empty? return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-empty') end # Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability) if tx.serialize_old_format.bytesize * Bitcoin::WITNESS_SCALE_FACTOR > Bitcoin::MAX_BLOCK_WEIGHT return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-oversize') end # Check for negative or overflow output values amount = 0 tx.outputs.each do |o| return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-negative') if o.value < 0 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < o.value amount += o.value return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < amount end # Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock out_points = tx.inputs.map{|i|i.out_point.to_payload} unless out_points.size == out_points.uniq.size return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-inputs-duplicate') end if tx.coinbase_tx? if tx.inputs[0].script_sig.size < 2 || tx.inputs[0].script_sig.size > 100 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-cb-length') end else tx.inputs.each do |i| if i.out_point.nil? || !i.out_point.valid? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-prevout-null') end end end true end
ruby
def check_tx(tx, state) # Basic checks that don't depend on any context if tx.inputs.empty? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vin-empty') end if tx.outputs.empty? return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-empty') end # Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability) if tx.serialize_old_format.bytesize * Bitcoin::WITNESS_SCALE_FACTOR > Bitcoin::MAX_BLOCK_WEIGHT return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-oversize') end # Check for negative or overflow output values amount = 0 tx.outputs.each do |o| return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-negative') if o.value < 0 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < o.value amount += o.value return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < amount end # Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock out_points = tx.inputs.map{|i|i.out_point.to_payload} unless out_points.size == out_points.uniq.size return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-inputs-duplicate') end if tx.coinbase_tx? if tx.inputs[0].script_sig.size < 2 || tx.inputs[0].script_sig.size > 100 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-cb-length') end else tx.inputs.each do |i| if i.out_point.nil? || !i.out_point.valid? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-prevout-null') end end end true end
[ "def", "check_tx", "(", "tx", ",", "state", ")", "# Basic checks that don't depend on any context", "if", "tx", ".", "inputs", ".", "empty?", "return", "state", ".", "DoS", "(", "10", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vin-empty'", ")", "end", "if", "tx", ".", "outputs", ".", "empty?", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-empty'", ")", "end", "# Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)", "if", "tx", ".", "serialize_old_format", ".", "bytesize", "*", "Bitcoin", "::", "WITNESS_SCALE_FACTOR", ">", "Bitcoin", "::", "MAX_BLOCK_WEIGHT", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-oversize'", ")", "end", "# Check for negative or overflow output values", "amount", "=", "0", "tx", ".", "outputs", ".", "each", "do", "|", "o", "|", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-negative'", ")", "if", "o", ".", "value", "<", "0", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-toolarge'", ")", "if", "MAX_MONEY", "<", "o", ".", "value", "amount", "+=", "o", ".", "value", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-toolarge'", ")", "if", "MAX_MONEY", "<", "amount", "end", "# Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock", "out_points", "=", "tx", ".", "inputs", ".", "map", "{", "|", "i", "|", "i", ".", "out_point", ".", "to_payload", "}", "unless", "out_points", ".", "size", "==", "out_points", ".", "uniq", ".", "size", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-inputs-duplicate'", ")", "end", "if", "tx", ".", "coinbase_tx?", "if", "tx", ".", "inputs", "[", "0", "]", ".", "script_sig", ".", "size", "<", "2", "||", "tx", ".", "inputs", "[", "0", "]", ".", "script_sig", ".", "size", ">", "100", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-cb-length'", ")", "end", "else", "tx", ".", "inputs", ".", "each", "do", "|", "i", "|", "if", "i", ".", "out_point", ".", "nil?", "||", "!", "i", ".", "out_point", ".", "valid?", "return", "state", ".", "DoS", "(", "10", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-prevout-null'", ")", "end", "end", "end", "true", "end" ]
check transaction validation
[ "check", "transaction", "validation" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/validation.rb#L6-L48
train
chaintope/bitcoinrb
lib/bitcoin/script/script_interpreter.rb
Bitcoin.ScriptInterpreter.verify_script
def verify_script(script_sig, script_pubkey, witness = ScriptWitness.new) return set_error(SCRIPT_ERR_SIG_PUSHONLY) if flag?(SCRIPT_VERIFY_SIGPUSHONLY) && !script_sig.push_only? stack_copy = nil had_witness = false return false unless eval_script(script_sig, :base) stack_copy = stack.dup if flag?(SCRIPT_VERIFY_P2SH) return false unless eval_script(script_pubkey, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last.htb) # Bare witness programs if flag?(SCRIPT_VERIFY_WITNESS) && script_pubkey.witness_program? had_witness = true return set_error(SCRIPT_ERR_WITNESS_MALLEATED) unless script_sig.size == 0 version, program = script_pubkey.witness_data stack_copy = stack.dup return false unless verify_witness_program(witness, version, program) end # Additional validation for spend-to-script-hash transactions if flag?(SCRIPT_VERIFY_P2SH) && script_pubkey.p2sh? return set_error(SCRIPT_ERR_SIG_PUSHONLY) unless script_sig.push_only? tmp = stack @stack = stack_copy raise 'stack cannot be empty.' if stack.empty? begin redeem_script = Bitcoin::Script.parse_from_payload(stack.pop.htb) rescue Exception => e return set_error(SCRIPT_ERR_BAD_OPCODE, "Failed to parse serialized redeem script for P2SH. #{e.message}") end return false unless eval_script(redeem_script, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last) # P2SH witness program if flag?(SCRIPT_VERIFY_WITNESS) && redeem_script.witness_program? had_witness = true # The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we reintroduce malleability. return set_error(SCRIPT_ERR_WITNESS_MALLEATED_P2SH) unless script_sig == (Bitcoin::Script.new << redeem_script.to_payload.bth) version, program = redeem_script.witness_data return false unless verify_witness_program(witness, version, program) end end # The CLEANSTACK check is only performed after potential P2SH evaluation, # as the non-P2SH evaluation of a P2SH script will obviously not result in a clean stack (the P2SH inputs remain). # The same holds for witness evaluation. if flag?(SCRIPT_VERIFY_CLEANSTACK) # Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK would be possible, # which is not a softfork (and P2SH should be one). raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_CLEANSTACK) unless stack.size == 1 end if flag?(SCRIPT_VERIFY_WITNESS) raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_WITNESS_UNEXPECTED) if !had_witness && !witness.empty? end true end
ruby
def verify_script(script_sig, script_pubkey, witness = ScriptWitness.new) return set_error(SCRIPT_ERR_SIG_PUSHONLY) if flag?(SCRIPT_VERIFY_SIGPUSHONLY) && !script_sig.push_only? stack_copy = nil had_witness = false return false unless eval_script(script_sig, :base) stack_copy = stack.dup if flag?(SCRIPT_VERIFY_P2SH) return false unless eval_script(script_pubkey, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last.htb) # Bare witness programs if flag?(SCRIPT_VERIFY_WITNESS) && script_pubkey.witness_program? had_witness = true return set_error(SCRIPT_ERR_WITNESS_MALLEATED) unless script_sig.size == 0 version, program = script_pubkey.witness_data stack_copy = stack.dup return false unless verify_witness_program(witness, version, program) end # Additional validation for spend-to-script-hash transactions if flag?(SCRIPT_VERIFY_P2SH) && script_pubkey.p2sh? return set_error(SCRIPT_ERR_SIG_PUSHONLY) unless script_sig.push_only? tmp = stack @stack = stack_copy raise 'stack cannot be empty.' if stack.empty? begin redeem_script = Bitcoin::Script.parse_from_payload(stack.pop.htb) rescue Exception => e return set_error(SCRIPT_ERR_BAD_OPCODE, "Failed to parse serialized redeem script for P2SH. #{e.message}") end return false unless eval_script(redeem_script, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last) # P2SH witness program if flag?(SCRIPT_VERIFY_WITNESS) && redeem_script.witness_program? had_witness = true # The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we reintroduce malleability. return set_error(SCRIPT_ERR_WITNESS_MALLEATED_P2SH) unless script_sig == (Bitcoin::Script.new << redeem_script.to_payload.bth) version, program = redeem_script.witness_data return false unless verify_witness_program(witness, version, program) end end # The CLEANSTACK check is only performed after potential P2SH evaluation, # as the non-P2SH evaluation of a P2SH script will obviously not result in a clean stack (the P2SH inputs remain). # The same holds for witness evaluation. if flag?(SCRIPT_VERIFY_CLEANSTACK) # Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK would be possible, # which is not a softfork (and P2SH should be one). raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_CLEANSTACK) unless stack.size == 1 end if flag?(SCRIPT_VERIFY_WITNESS) raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_WITNESS_UNEXPECTED) if !had_witness && !witness.empty? end true end
[ "def", "verify_script", "(", "script_sig", ",", "script_pubkey", ",", "witness", "=", "ScriptWitness", ".", "new", ")", "return", "set_error", "(", "SCRIPT_ERR_SIG_PUSHONLY", ")", "if", "flag?", "(", "SCRIPT_VERIFY_SIGPUSHONLY", ")", "&&", "!", "script_sig", ".", "push_only?", "stack_copy", "=", "nil", "had_witness", "=", "false", "return", "false", "unless", "eval_script", "(", "script_sig", ",", ":base", ")", "stack_copy", "=", "stack", ".", "dup", "if", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "return", "false", "unless", "eval_script", "(", "script_pubkey", ",", ":base", ")", "return", "set_error", "(", "SCRIPT_ERR_EVAL_FALSE", ")", "if", "stack", ".", "empty?", "||", "!", "cast_to_bool", "(", "stack", ".", "last", ".", "htb", ")", "# Bare witness programs", "if", "flag?", "(", "SCRIPT_VERIFY_WITNESS", ")", "&&", "script_pubkey", ".", "witness_program?", "had_witness", "=", "true", "return", "set_error", "(", "SCRIPT_ERR_WITNESS_MALLEATED", ")", "unless", "script_sig", ".", "size", "==", "0", "version", ",", "program", "=", "script_pubkey", ".", "witness_data", "stack_copy", "=", "stack", ".", "dup", "return", "false", "unless", "verify_witness_program", "(", "witness", ",", "version", ",", "program", ")", "end", "# Additional validation for spend-to-script-hash transactions", "if", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "&&", "script_pubkey", ".", "p2sh?", "return", "set_error", "(", "SCRIPT_ERR_SIG_PUSHONLY", ")", "unless", "script_sig", ".", "push_only?", "tmp", "=", "stack", "@stack", "=", "stack_copy", "raise", "'stack cannot be empty.'", "if", "stack", ".", "empty?", "begin", "redeem_script", "=", "Bitcoin", "::", "Script", ".", "parse_from_payload", "(", "stack", ".", "pop", ".", "htb", ")", "rescue", "Exception", "=>", "e", "return", "set_error", "(", "SCRIPT_ERR_BAD_OPCODE", ",", "\"Failed to parse serialized redeem script for P2SH. #{e.message}\"", ")", "end", "return", "false", "unless", "eval_script", "(", "redeem_script", ",", ":base", ")", "return", "set_error", "(", "SCRIPT_ERR_EVAL_FALSE", ")", "if", "stack", ".", "empty?", "||", "!", "cast_to_bool", "(", "stack", ".", "last", ")", "# P2SH witness program", "if", "flag?", "(", "SCRIPT_VERIFY_WITNESS", ")", "&&", "redeem_script", ".", "witness_program?", "had_witness", "=", "true", "# The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we reintroduce malleability.", "return", "set_error", "(", "SCRIPT_ERR_WITNESS_MALLEATED_P2SH", ")", "unless", "script_sig", "==", "(", "Bitcoin", "::", "Script", ".", "new", "<<", "redeem_script", ".", "to_payload", ".", "bth", ")", "version", ",", "program", "=", "redeem_script", ".", "witness_data", "return", "false", "unless", "verify_witness_program", "(", "witness", ",", "version", ",", "program", ")", "end", "end", "# The CLEANSTACK check is only performed after potential P2SH evaluation,", "# as the non-P2SH evaluation of a P2SH script will obviously not result in a clean stack (the P2SH inputs remain).", "# The same holds for witness evaluation.", "if", "flag?", "(", "SCRIPT_VERIFY_CLEANSTACK", ")", "# Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK would be possible,", "# which is not a softfork (and P2SH should be one).", "raise", "'assert'", "unless", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "return", "set_error", "(", "SCRIPT_ERR_CLEANSTACK", ")", "unless", "stack", ".", "size", "==", "1", "end", "if", "flag?", "(", "SCRIPT_VERIFY_WITNESS", ")", "raise", "'assert'", "unless", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "return", "set_error", "(", "SCRIPT_ERR_WITNESS_UNEXPECTED", ")", "if", "!", "had_witness", "&&", "!", "witness", ".", "empty?", "end", "true", "end" ]
initialize runner eval script @param [Bitcoin::Script] script_sig a signature script (unlock script which data push only) @param [Bitcoin::Script] script_pubkey a script pubkey (locking script) @param [Bitcoin::ScriptWitness] witness a witness script @return [Boolean] result
[ "initialize", "runner", "eval", "script" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script_interpreter.rb#L37-L102
train
chaintope/bitcoinrb
lib/bitcoin/script/script_interpreter.rb
Bitcoin.ScriptInterpreter.pop_int
def pop_int(count = 1) i = stack.pop(count).map{ |s| cast_to_int(s) } count == 1 ? i.first : i end
ruby
def pop_int(count = 1) i = stack.pop(count).map{ |s| cast_to_int(s) } count == 1 ? i.first : i end
[ "def", "pop_int", "(", "count", "=", "1", ")", "i", "=", "stack", ".", "pop", "(", "count", ")", ".", "map", "{", "|", "s", "|", "cast_to_int", "(", "s", ")", "}", "count", "==", "1", "?", "i", ".", "first", ":", "i", "end" ]
pop the item with the int value for the number specified by +count+ from the stack.
[ "pop", "the", "item", "with", "the", "int", "value", "for", "the", "number", "specified", "by", "+", "count", "+", "from", "the", "stack", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script_interpreter.rb#L534-L537
train
chaintope/bitcoinrb
lib/bitcoin/script/script_interpreter.rb
Bitcoin.ScriptInterpreter.cast_to_int
def cast_to_int(s, max_num_size = DEFAULT_MAX_NUM_SIZE) data = s.htb raise '"script number overflow"' if data.bytesize > max_num_size if require_minimal && data.bytesize > 0 if data.bytes[-1] & 0x7f == 0 && (data.bytesize <= 1 || data.bytes[data.bytesize - 2] & 0x80 == 0) raise 'non-minimally encoded script number' end end Script.decode_number(s) end
ruby
def cast_to_int(s, max_num_size = DEFAULT_MAX_NUM_SIZE) data = s.htb raise '"script number overflow"' if data.bytesize > max_num_size if require_minimal && data.bytesize > 0 if data.bytes[-1] & 0x7f == 0 && (data.bytesize <= 1 || data.bytes[data.bytesize - 2] & 0x80 == 0) raise 'non-minimally encoded script number' end end Script.decode_number(s) end
[ "def", "cast_to_int", "(", "s", ",", "max_num_size", "=", "DEFAULT_MAX_NUM_SIZE", ")", "data", "=", "s", ".", "htb", "raise", "'\"script number overflow\"'", "if", "data", ".", "bytesize", ">", "max_num_size", "if", "require_minimal", "&&", "data", ".", "bytesize", ">", "0", "if", "data", ".", "bytes", "[", "-", "1", "]", "&", "0x7f", "==", "0", "&&", "(", "data", ".", "bytesize", "<=", "1", "||", "data", ".", "bytes", "[", "data", ".", "bytesize", "-", "2", "]", "&", "0x80", "==", "0", ")", "raise", "'non-minimally encoded script number'", "end", "end", "Script", ".", "decode_number", "(", "s", ")", "end" ]
cast item to int value.
[ "cast", "item", "to", "int", "value", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script_interpreter.rb#L540-L549
train
chaintope/bitcoinrb
lib/bitcoin/bloom_filter.rb
Bitcoin.BloomFilter.contains?
def contains?(data) return true if full? hash_funcs.times do |i| hash = to_hash(data, i) return false unless check_bit(hash) end true end
ruby
def contains?(data) return true if full? hash_funcs.times do |i| hash = to_hash(data, i) return false unless check_bit(hash) end true end
[ "def", "contains?", "(", "data", ")", "return", "true", "if", "full?", "hash_funcs", ".", "times", "do", "|", "i", "|", "hash", "=", "to_hash", "(", "data", ",", "i", ")", "return", "false", "unless", "check_bit", "(", "hash", ")", "end", "true", "end" ]
Returns true if the given data matches the filter @param [String] data The data to check the current filter @return [Boolean] true if the given data matches the filter
[ "Returns", "true", "if", "the", "given", "data", "matches", "the", "filter" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/bloom_filter.rb#L43-L50
train
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.hash_to_range
def hash_to_range(element) hash = SipHash.digest(key, element) map_into_range(hash, f) end
ruby
def hash_to_range(element) hash = SipHash.digest(key, element) map_into_range(hash, f) end
[ "def", "hash_to_range", "(", "element", ")", "hash", "=", "SipHash", ".", "digest", "(", "key", ",", "element", ")", "map_into_range", "(", "hash", ",", "f", ")", "end" ]
Hash a data element to an integer in the range [0, F). @param [String] element with binary format. @return [Integer]
[ "Hash", "a", "data", "element", "to", "an", "integer", "in", "the", "range", "[", "0", "F", ")", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L61-L64
train
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.match_internal?
def match_internal?(hashes, size) n, payload = Bitcoin.unpack_var_int(encoded.htb) bit_reader = Bitcoin::BitStreamReader.new(payload) value = 0 hashes_index = 0 n.times do delta = golomb_rice_decode(bit_reader, p) value += delta loop do return false if hashes_index == size return true if hashes[hashes_index] == value break if hashes[hashes_index] > value hashes_index += 1 end end false end
ruby
def match_internal?(hashes, size) n, payload = Bitcoin.unpack_var_int(encoded.htb) bit_reader = Bitcoin::BitStreamReader.new(payload) value = 0 hashes_index = 0 n.times do delta = golomb_rice_decode(bit_reader, p) value += delta loop do return false if hashes_index == size return true if hashes[hashes_index] == value break if hashes[hashes_index] > value hashes_index += 1 end end false end
[ "def", "match_internal?", "(", "hashes", ",", "size", ")", "n", ",", "payload", "=", "Bitcoin", ".", "unpack_var_int", "(", "encoded", ".", "htb", ")", "bit_reader", "=", "Bitcoin", "::", "BitStreamReader", ".", "new", "(", "payload", ")", "value", "=", "0", "hashes_index", "=", "0", "n", ".", "times", "do", "delta", "=", "golomb_rice_decode", "(", "bit_reader", ",", "p", ")", "value", "+=", "delta", "loop", "do", "return", "false", "if", "hashes_index", "==", "size", "return", "true", "if", "hashes", "[", "hashes_index", "]", "==", "value", "break", "if", "hashes", "[", "hashes_index", "]", ">", "value", "hashes_index", "+=", "1", "end", "end", "false", "end" ]
Checks if the elements may be in the set. @param [Array[Integer]] hashes the query hash list. @param [Integer] size query size. @return [Boolean] whether elements in set.
[ "Checks", "if", "the", "elements", "may", "be", "in", "the", "set", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L96-L112
train
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_encode
def golomb_rice_encode(bit_writer, p, x) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp. q -= nbits end bit_writer.write(0, 1) bit_writer.write(x, p) end
ruby
def golomb_rice_encode(bit_writer, p, x) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp. q -= nbits end bit_writer.write(0, 1) bit_writer.write(x, p) end
[ "def", "golomb_rice_encode", "(", "bit_writer", ",", "p", ",", "x", ")", "q", "=", "x", ">>", "p", "while", "q", ">", "0", "nbits", "=", "q", "<=", "64", "?", "q", ":", "64", "bit_writer", ".", "write", "(", "-", "1", ",", "nbits", ")", "# 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp.", "q", "-=", "nbits", "end", "bit_writer", ".", "write", "(", "0", ",", "1", ")", "bit_writer", ".", "write", "(", "x", ",", "p", ")", "end" ]
encode golomb rice
[ "encode", "golomb", "rice" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L115-L124
train
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_decode
def golomb_rice_decode(bit_reader, p) q = 0 while bit_reader.read(1) == 1 q +=1 end r = bit_reader.read(p) (q << p) + r end
ruby
def golomb_rice_decode(bit_reader, p) q = 0 while bit_reader.read(1) == 1 q +=1 end r = bit_reader.read(p) (q << p) + r end
[ "def", "golomb_rice_decode", "(", "bit_reader", ",", "p", ")", "q", "=", "0", "while", "bit_reader", ".", "read", "(", "1", ")", "==", "1", "q", "+=", "1", "end", "r", "=", "bit_reader", ".", "read", "(", "p", ")", "(", "q", "<<", "p", ")", "+", "r", "end" ]
decode golomb rice
[ "decode", "golomb", "rice" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L127-L134
train
Druwerd/caplock
lib/caplock.rb
Capistrano.Caplock.remote_file_content_same_as?
def remote_file_content_same_as?(full_path, content) Digest::MD5.hexdigest(content) == top.capture("md5sum #{full_path} | awk '{ print $1 }'").strip end
ruby
def remote_file_content_same_as?(full_path, content) Digest::MD5.hexdigest(content) == top.capture("md5sum #{full_path} | awk '{ print $1 }'").strip end
[ "def", "remote_file_content_same_as?", "(", "full_path", ",", "content", ")", "Digest", "::", "MD5", ".", "hexdigest", "(", "content", ")", "==", "top", ".", "capture", "(", "\"md5sum #{full_path} | awk '{ print $1 }'\"", ")", ".", "strip", "end" ]
Returns Boolean value indicating whether the file at +full_path+ matches +content+. Checks if file is equivalent to content by checking whether or not the MD5 of the remote content is the same as the MD5 of the String in +content+.
[ "Returns", "Boolean", "value", "indicating", "whether", "the", "file", "at", "+", "full_path", "+", "matches", "+", "content", "+", ".", "Checks", "if", "file", "is", "equivalent", "to", "content", "by", "checking", "whether", "or", "not", "the", "MD5", "of", "the", "remote", "content", "is", "the", "same", "as", "the", "MD5", "of", "the", "String", "in", "+", "content", "+", "." ]
04525a983abe2e63210d7d605073fdd39c641f73
https://github.com/Druwerd/caplock/blob/04525a983abe2e63210d7d605073fdd39c641f73/lib/caplock.rb#L27-L29
train
Druwerd/caplock
lib/caplock.rb
Capistrano.Caplock.remote_file_differs?
def remote_file_differs?(full_path, content) !remote_file_exists?(full_path) || remote_file_exists?(full_path) && !remote_file_content_same_as?(full_path, content) end
ruby
def remote_file_differs?(full_path, content) !remote_file_exists?(full_path) || remote_file_exists?(full_path) && !remote_file_content_same_as?(full_path, content) end
[ "def", "remote_file_differs?", "(", "full_path", ",", "content", ")", "!", "remote_file_exists?", "(", "full_path", ")", "||", "remote_file_exists?", "(", "full_path", ")", "&&", "!", "remote_file_content_same_as?", "(", "full_path", ",", "content", ")", "end" ]
Returns Boolean indicating whether the remote file is present and has the same contents as the String in +content+.
[ "Returns", "Boolean", "indicating", "whether", "the", "remote", "file", "is", "present", "and", "has", "the", "same", "contents", "as", "the", "String", "in", "+", "content", "+", "." ]
04525a983abe2e63210d7d605073fdd39c641f73
https://github.com/Druwerd/caplock/blob/04525a983abe2e63210d7d605073fdd39c641f73/lib/caplock.rb#L33-L35
train
enkessler/cuke_modeler
lib/cuke_modeler/adapters/gherkin_6_adapter.rb
CukeModeler.Gherkin6Adapter.adapt_tag!
def adapt_tag!(parsed_tag) # Saving off the original data parsed_tag['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_tag)) parsed_tag['name'] = parsed_tag.delete(:name) parsed_tag['line'] = parsed_tag.delete(:location)[:line] end
ruby
def adapt_tag!(parsed_tag) # Saving off the original data parsed_tag['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_tag)) parsed_tag['name'] = parsed_tag.delete(:name) parsed_tag['line'] = parsed_tag.delete(:location)[:line] end
[ "def", "adapt_tag!", "(", "parsed_tag", ")", "# Saving off the original data", "parsed_tag", "[", "'cuke_modeler_parsing_data'", "]", "=", "Marshal", "::", "load", "(", "Marshal", ".", "dump", "(", "parsed_tag", ")", ")", "parsed_tag", "[", "'name'", "]", "=", "parsed_tag", ".", "delete", "(", ":name", ")", "parsed_tag", "[", "'line'", "]", "=", "parsed_tag", ".", "delete", "(", ":location", ")", "[", ":line", "]", "end" ]
Adapts the AST sub-tree that is rooted at the given tag node.
[ "Adapts", "the", "AST", "sub", "-", "tree", "that", "is", "rooted", "at", "the", "given", "tag", "node", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/adapters/gherkin_6_adapter.rb#L171-L177
train
enkessler/cuke_modeler
lib/cuke_modeler/adapters/gherkin_6_adapter.rb
CukeModeler.Gherkin6Adapter.adapt_comment!
def adapt_comment!(parsed_comment) # Saving off the original data parsed_comment['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_comment)) parsed_comment['text'] = parsed_comment.delete(:text) parsed_comment['line'] = parsed_comment.delete(:location)[:line] end
ruby
def adapt_comment!(parsed_comment) # Saving off the original data parsed_comment['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_comment)) parsed_comment['text'] = parsed_comment.delete(:text) parsed_comment['line'] = parsed_comment.delete(:location)[:line] end
[ "def", "adapt_comment!", "(", "parsed_comment", ")", "# Saving off the original data", "parsed_comment", "[", "'cuke_modeler_parsing_data'", "]", "=", "Marshal", "::", "load", "(", "Marshal", ".", "dump", "(", "parsed_comment", ")", ")", "parsed_comment", "[", "'text'", "]", "=", "parsed_comment", ".", "delete", "(", ":text", ")", "parsed_comment", "[", "'line'", "]", "=", "parsed_comment", ".", "delete", "(", ":location", ")", "[", ":line", "]", "end" ]
Adapts the AST sub-tree that is rooted at the given comment node.
[ "Adapts", "the", "AST", "sub", "-", "tree", "that", "is", "rooted", "at", "the", "given", "comment", "node", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/adapters/gherkin_6_adapter.rb#L180-L186
train
enkessler/cuke_modeler
lib/cuke_modeler/models/feature.rb
CukeModeler.Feature.to_s
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n\n" + background_output_string if background text << "\n\n" + tests_output_string unless tests.empty? text end
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n\n" + background_output_string if background text << "\n\n" + tests_output_string unless tests.empty? text end
[ "def", "to_s", "text", "=", "''", "text", "<<", "tag_output_string", "+", "\"\\n\"", "unless", "tags", ".", "empty?", "text", "<<", "\"#{@keyword}:#{name_output_string}\"", "text", "<<", "\"\\n\"", "+", "description_output_string", "unless", "(", "description", ".", "nil?", "||", "description", ".", "empty?", ")", "text", "<<", "\"\\n\\n\"", "+", "background_output_string", "if", "background", "text", "<<", "\"\\n\\n\"", "+", "tests_output_string", "unless", "tests", ".", "empty?", "text", "end" ]
Returns a string representation of this model. For a feature model, this will be Gherkin text that is equivalent to the feature being modeled.
[ "Returns", "a", "string", "representation", "of", "this", "model", ".", "For", "a", "feature", "model", "this", "will", "be", "Gherkin", "text", "that", "is", "equivalent", "to", "the", "feature", "being", "modeled", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/models/feature.rb#L74-L84
train
enkessler/cuke_modeler
lib/cuke_modeler/models/step.rb
CukeModeler.Step.to_s
def to_s text = "#{keyword} #{self.text}" text << "\n" + block.to_s.split("\n").collect { |line| " #{line}" }.join("\n") if block text end
ruby
def to_s text = "#{keyword} #{self.text}" text << "\n" + block.to_s.split("\n").collect { |line| " #{line}" }.join("\n") if block text end
[ "def", "to_s", "text", "=", "\"#{keyword} #{self.text}\"", "text", "<<", "\"\\n\"", "+", "block", ".", "to_s", ".", "split", "(", "\"\\n\"", ")", ".", "collect", "{", "|", "line", "|", "\" #{line}\"", "}", ".", "join", "(", "\"\\n\"", ")", "if", "block", "text", "end" ]
Returns a string representation of this model. For a step model, this will be Gherkin text that is equivalent to the step being modeled.
[ "Returns", "a", "string", "representation", "of", "this", "model", ".", "For", "a", "step", "model", "this", "will", "be", "Gherkin", "text", "that", "is", "equivalent", "to", "the", "step", "being", "modeled", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/models/step.rb#L48-L53
train
enkessler/cuke_modeler
lib/cuke_modeler/adapters/gherkin_3_adapter.rb
CukeModeler.Gherkin3Adapter.adapt_doc_string!
def adapt_doc_string!(parsed_doc_string) # Saving off the original data parsed_doc_string['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_doc_string)) parsed_doc_string['value'] = parsed_doc_string.delete(:content) parsed_doc_string['content_type'] = parsed_doc_string.delete(:contentType) parsed_doc_string['line'] = parsed_doc_string.delete(:location)[:line] end
ruby
def adapt_doc_string!(parsed_doc_string) # Saving off the original data parsed_doc_string['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_doc_string)) parsed_doc_string['value'] = parsed_doc_string.delete(:content) parsed_doc_string['content_type'] = parsed_doc_string.delete(:contentType) parsed_doc_string['line'] = parsed_doc_string.delete(:location)[:line] end
[ "def", "adapt_doc_string!", "(", "parsed_doc_string", ")", "# Saving off the original data", "parsed_doc_string", "[", "'cuke_modeler_parsing_data'", "]", "=", "Marshal", "::", "load", "(", "Marshal", ".", "dump", "(", "parsed_doc_string", ")", ")", "parsed_doc_string", "[", "'value'", "]", "=", "parsed_doc_string", ".", "delete", "(", ":content", ")", "parsed_doc_string", "[", "'content_type'", "]", "=", "parsed_doc_string", ".", "delete", "(", ":contentType", ")", "parsed_doc_string", "[", "'line'", "]", "=", "parsed_doc_string", ".", "delete", "(", ":location", ")", "[", ":line", "]", "end" ]
Adapts the AST sub-tree that is rooted at the given doc string node.
[ "Adapts", "the", "AST", "sub", "-", "tree", "that", "is", "rooted", "at", "the", "given", "doc", "string", "node", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/adapters/gherkin_3_adapter.rb#L211-L218
train
enkessler/cuke_modeler
lib/cuke_modeler/models/outline.rb
CukeModeler.Outline.to_s
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n" unless (steps.empty? || description.nil? || description.empty?) text << "\n" + steps_output_string unless steps.empty? text << "\n\n" + examples_output_string unless examples.empty? text end
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n" unless (steps.empty? || description.nil? || description.empty?) text << "\n" + steps_output_string unless steps.empty? text << "\n\n" + examples_output_string unless examples.empty? text end
[ "def", "to_s", "text", "=", "''", "text", "<<", "tag_output_string", "+", "\"\\n\"", "unless", "tags", ".", "empty?", "text", "<<", "\"#{@keyword}:#{name_output_string}\"", "text", "<<", "\"\\n\"", "+", "description_output_string", "unless", "(", "description", ".", "nil?", "||", "description", ".", "empty?", ")", "text", "<<", "\"\\n\"", "unless", "(", "steps", ".", "empty?", "||", "description", ".", "nil?", "||", "description", ".", "empty?", ")", "text", "<<", "\"\\n\"", "+", "steps_output_string", "unless", "steps", ".", "empty?", "text", "<<", "\"\\n\\n\"", "+", "examples_output_string", "unless", "examples", ".", "empty?", "text", "end" ]
Returns a string representation of this model. For an outline model, this will be Gherkin text that is equivalent to the outline being modeled.
[ "Returns", "a", "string", "representation", "of", "this", "model", ".", "For", "an", "outline", "model", "this", "will", "be", "Gherkin", "text", "that", "is", "equivalent", "to", "the", "outline", "being", "modeled", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/models/outline.rb#L52-L63
train
enkessler/cuke_modeler
lib/cuke_modeler/containing.rb
CukeModeler.Containing.each_descendant
def each_descendant(&block) children.each do |child_model| block.call(child_model) child_model.each_descendant(&block) if child_model.respond_to?(:each_descendant) end end
ruby
def each_descendant(&block) children.each do |child_model| block.call(child_model) child_model.each_descendant(&block) if child_model.respond_to?(:each_descendant) end end
[ "def", "each_descendant", "(", "&", "block", ")", "children", ".", "each", "do", "|", "child_model", "|", "block", ".", "call", "(", "child_model", ")", "child_model", ".", "each_descendant", "(", "block", ")", "if", "child_model", ".", "respond_to?", "(", ":each_descendant", ")", "end", "end" ]
Executes the given code block with every model that is a child of this model.
[ "Executes", "the", "given", "code", "block", "with", "every", "model", "that", "is", "a", "child", "of", "this", "model", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/containing.rb#L8-L13
train
enkessler/cuke_modeler
lib/cuke_modeler/nested.rb
CukeModeler.Nested.get_ancestor
def get_ancestor(ancestor_type) target_type = {:directory => [Directory], :feature_file => [FeatureFile], :feature => [Feature], :test => [Scenario, Outline, Background], :background => [Background], :scenario => [Scenario], :outline => [Outline], :step => [Step], :table => [Table], :example => [Example], :row => [Row] }[ancestor_type] raise(ArgumentError, "Unknown ancestor type '#{ancestor_type}'.") if target_type.nil? ancestor = self.parent_model until target_type.include?(ancestor.class) || ancestor.nil? ancestor = ancestor.parent_model end ancestor end
ruby
def get_ancestor(ancestor_type) target_type = {:directory => [Directory], :feature_file => [FeatureFile], :feature => [Feature], :test => [Scenario, Outline, Background], :background => [Background], :scenario => [Scenario], :outline => [Outline], :step => [Step], :table => [Table], :example => [Example], :row => [Row] }[ancestor_type] raise(ArgumentError, "Unknown ancestor type '#{ancestor_type}'.") if target_type.nil? ancestor = self.parent_model until target_type.include?(ancestor.class) || ancestor.nil? ancestor = ancestor.parent_model end ancestor end
[ "def", "get_ancestor", "(", "ancestor_type", ")", "target_type", "=", "{", ":directory", "=>", "[", "Directory", "]", ",", ":feature_file", "=>", "[", "FeatureFile", "]", ",", ":feature", "=>", "[", "Feature", "]", ",", ":test", "=>", "[", "Scenario", ",", "Outline", ",", "Background", "]", ",", ":background", "=>", "[", "Background", "]", ",", ":scenario", "=>", "[", "Scenario", "]", ",", ":outline", "=>", "[", "Outline", "]", ",", ":step", "=>", "[", "Step", "]", ",", ":table", "=>", "[", "Table", "]", ",", ":example", "=>", "[", "Example", "]", ",", ":row", "=>", "[", "Row", "]", "}", "[", "ancestor_type", "]", "raise", "(", "ArgumentError", ",", "\"Unknown ancestor type '#{ancestor_type}'.\"", ")", "if", "target_type", ".", "nil?", "ancestor", "=", "self", ".", "parent_model", "until", "target_type", ".", "include?", "(", "ancestor", ".", "class", ")", "||", "ancestor", ".", "nil?", "ancestor", "=", "ancestor", ".", "parent_model", "end", "ancestor", "end" ]
Returns the ancestor model of this model that matches the given type.
[ "Returns", "the", "ancestor", "model", "of", "this", "model", "that", "matches", "the", "given", "type", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/nested.rb#L13-L38
train
enkessler/cuke_modeler
lib/cuke_modeler/models/example.rb
CukeModeler.Example.to_s
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n" unless (rows.empty? || description.nil? || description.empty?) text << "\n" + parameters_output_string if parameter_row text << "\n" + rows_output_string unless argument_rows.empty? text end
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n" unless (rows.empty? || description.nil? || description.empty?) text << "\n" + parameters_output_string if parameter_row text << "\n" + rows_output_string unless argument_rows.empty? text end
[ "def", "to_s", "text", "=", "''", "text", "<<", "tag_output_string", "+", "\"\\n\"", "unless", "tags", ".", "empty?", "text", "<<", "\"#{@keyword}:#{name_output_string}\"", "text", "<<", "\"\\n\"", "+", "description_output_string", "unless", "(", "description", ".", "nil?", "||", "description", ".", "empty?", ")", "text", "<<", "\"\\n\"", "unless", "(", "rows", ".", "empty?", "||", "description", ".", "nil?", "||", "description", ".", "empty?", ")", "text", "<<", "\"\\n\"", "+", "parameters_output_string", "if", "parameter_row", "text", "<<", "\"\\n\"", "+", "rows_output_string", "unless", "argument_rows", ".", "empty?", "text", "end" ]
Returns a string representation of this model. For an example model, this will be Gherkin text that is equivalent to the example being modeled.
[ "Returns", "a", "string", "representation", "of", "this", "model", ".", "For", "an", "example", "model", "this", "will", "be", "Gherkin", "text", "that", "is", "equivalent", "to", "the", "example", "being", "modeled", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/models/example.rb#L104-L115
train
negativecode/vines
lib/vines/stanza.rb
Vines.Stanza.broadcast
def broadcast(recipients) @node[FROM] = stream.user.jid.to_s recipients.each do |recipient| @node[TO] = recipient.user.jid.to_s recipient.write(@node) end end
ruby
def broadcast(recipients) @node[FROM] = stream.user.jid.to_s recipients.each do |recipient| @node[TO] = recipient.user.jid.to_s recipient.write(@node) end end
[ "def", "broadcast", "(", "recipients", ")", "@node", "[", "FROM", "]", "=", "stream", ".", "user", ".", "jid", ".", "to_s", "recipients", ".", "each", "do", "|", "recipient", "|", "@node", "[", "TO", "]", "=", "recipient", ".", "user", ".", "jid", ".", "to_s", "recipient", ".", "write", "(", "@node", ")", "end", "end" ]
Send the stanza to all recipients, stamping it with from and to addresses first.
[ "Send", "the", "stanza", "to", "all", "recipients", "stamping", "it", "with", "from", "and", "to", "addresses", "first", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stanza.rb#L33-L39
train
negativecode/vines
lib/vines/stanza.rb
Vines.Stanza.local?
def local? return true unless ROUTABLE_STANZAS.include?(@node.name) to = JID.new(@node[TO]) to.empty? || local_jid?(to) end
ruby
def local? return true unless ROUTABLE_STANZAS.include?(@node.name) to = JID.new(@node[TO]) to.empty? || local_jid?(to) end
[ "def", "local?", "return", "true", "unless", "ROUTABLE_STANZAS", ".", "include?", "(", "@node", ".", "name", ")", "to", "=", "JID", ".", "new", "(", "@node", "[", "TO", "]", ")", "to", ".", "empty?", "||", "local_jid?", "(", "to", ")", "end" ]
Returns true if this stanza should be processed locally. Returns false if it's destined for a remote domain or external component.
[ "Returns", "true", "if", "this", "stanza", "should", "be", "processed", "locally", ".", "Returns", "false", "if", "it", "s", "destined", "for", "a", "remote", "domain", "or", "external", "component", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stanza.rb#L43-L47
train
negativecode/vines
lib/vines/stanza.rb
Vines.Stanza.send_unavailable
def send_unavailable(from, to) available = router.available_resources(from, to) stanzas = available.map {|stream| unavailable(stream.user.jid) } broadcast_to_available_resources(stanzas, to) end
ruby
def send_unavailable(from, to) available = router.available_resources(from, to) stanzas = available.map {|stream| unavailable(stream.user.jid) } broadcast_to_available_resources(stanzas, to) end
[ "def", "send_unavailable", "(", "from", ",", "to", ")", "available", "=", "router", ".", "available_resources", "(", "from", ",", "to", ")", "stanzas", "=", "available", ".", "map", "{", "|", "stream", "|", "unavailable", "(", "stream", ".", "user", ".", "jid", ")", "}", "broadcast_to_available_resources", "(", "stanzas", ",", "to", ")", "end" ]
Broadcast unavailable presence from the user's available resources to the recipient's available resources. Route the stanza to a remote server if the recipient isn't hosted locally.
[ "Broadcast", "unavailable", "presence", "from", "the", "user", "s", "available", "resources", "to", "the", "recipient", "s", "available", "resources", ".", "Route", "the", "stanza", "to", "a", "remote", "server", "if", "the", "recipient", "isn", "t", "hosted", "locally", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stanza.rb#L80-L84
train
negativecode/vines
lib/vines/stanza.rb
Vines.Stanza.unavailable
def unavailable(from) doc = Document.new doc.create_element('presence', 'from' => from.to_s, 'id' => Kit.uuid, 'type' => 'unavailable') end
ruby
def unavailable(from) doc = Document.new doc.create_element('presence', 'from' => from.to_s, 'id' => Kit.uuid, 'type' => 'unavailable') end
[ "def", "unavailable", "(", "from", ")", "doc", "=", "Document", ".", "new", "doc", ".", "create_element", "(", "'presence'", ",", "'from'", "=>", "from", ".", "to_s", ",", "'id'", "=>", "Kit", ".", "uuid", ",", "'type'", "=>", "'unavailable'", ")", "end" ]
Return an unavailable presence stanza addressed from the given JID.
[ "Return", "an", "unavailable", "presence", "stanza", "addressed", "from", "the", "given", "JID", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stanza.rb#L87-L93
train
negativecode/vines
lib/vines/stanza.rb
Vines.Stanza.send_to_remote
def send_to_remote(stanzas, to) return false if local_jid?(to) to = JID.new(to) stanzas.each do |el| el[TO] = to.bare.to_s router.route(el) end true end
ruby
def send_to_remote(stanzas, to) return false if local_jid?(to) to = JID.new(to) stanzas.each do |el| el[TO] = to.bare.to_s router.route(el) end true end
[ "def", "send_to_remote", "(", "stanzas", ",", "to", ")", "return", "false", "if", "local_jid?", "(", "to", ")", "to", "=", "JID", ".", "new", "(", "to", ")", "stanzas", ".", "each", "do", "|", "el", "|", "el", "[", "TO", "]", "=", "to", ".", "bare", ".", "to_s", "router", ".", "route", "(", "el", ")", "end", "true", "end" ]
Route the stanzas to a remote server, stamping a bare JID as the to address. Bare JIDs are required for presence subscription stanzas sent to the remote contact's server. Return true if the stanzas were routed, false if they must be delivered locally.
[ "Route", "the", "stanzas", "to", "a", "remote", "server", "stamping", "a", "bare", "JID", "as", "the", "to", "address", ".", "Bare", "JIDs", "are", "required", "for", "presence", "subscription", "stanzas", "sent", "to", "the", "remote", "contact", "s", "server", ".", "Return", "true", "if", "the", "stanzas", "were", "routed", "false", "if", "they", "must", "be", "delivered", "locally", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stanza.rb#L135-L143
train
negativecode/vines
lib/vines/stanza.rb
Vines.Stanza.send_to_recipients
def send_to_recipients(stanzas, recipients) recipients.each do |recipient| stanzas.each do |el| el[TO] = recipient.user.jid.to_s recipient.write(el) end end end
ruby
def send_to_recipients(stanzas, recipients) recipients.each do |recipient| stanzas.each do |el| el[TO] = recipient.user.jid.to_s recipient.write(el) end end end
[ "def", "send_to_recipients", "(", "stanzas", ",", "recipients", ")", "recipients", ".", "each", "do", "|", "recipient", "|", "stanzas", ".", "each", "do", "|", "el", "|", "el", "[", "TO", "]", "=", "recipient", ".", "user", ".", "jid", ".", "to_s", "recipient", ".", "write", "(", "el", ")", "end", "end", "end" ]
Send the stanzas to the local recipient streams, stamping a full JID as the to address. It's important to use full JIDs, even when sending to local clients, because the stanzas may be routed to other cluster nodes for delivery. We need the receiving cluster node to send the stanza just to this full JID, not to lookup all JIDs for this user.
[ "Send", "the", "stanzas", "to", "the", "local", "recipient", "streams", "stamping", "a", "full", "JID", "as", "the", "to", "address", ".", "It", "s", "important", "to", "use", "full", "JIDs", "even", "when", "sending", "to", "local", "clients", "because", "the", "stanzas", "may", "be", "routed", "to", "other", "cluster", "nodes", "for", "delivery", ".", "We", "need", "the", "receiving", "cluster", "node", "to", "send", "the", "stanza", "just", "to", "this", "full", "JID", "not", "to", "lookup", "all", "JIDs", "for", "this", "user", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stanza.rb#L150-L157
train
negativecode/vines
lib/vines/user.rb
Vines.User.update_from
def update_from(user) @name = user.name @password = user.password @roster = user.roster.map {|c| c.clone } end
ruby
def update_from(user) @name = user.name @password = user.password @roster = user.roster.map {|c| c.clone } end
[ "def", "update_from", "(", "user", ")", "@name", "=", "user", ".", "name", "@password", "=", "user", ".", "password", "@roster", "=", "user", ".", "roster", ".", "map", "{", "|", "c", "|", "c", ".", "clone", "}", "end" ]
Update this user's information from the given user object.
[ "Update", "this", "user", "s", "information", "from", "the", "given", "user", "object", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/user.rb#L30-L34
train
negativecode/vines
lib/vines/user.rb
Vines.User.contact
def contact(jid) bare = JID.new(jid).bare @roster.find {|c| c.jid.bare == bare } end
ruby
def contact(jid) bare = JID.new(jid).bare @roster.find {|c| c.jid.bare == bare } end
[ "def", "contact", "(", "jid", ")", "bare", "=", "JID", ".", "new", "(", "jid", ")", ".", "bare", "@roster", ".", "find", "{", "|", "c", "|", "c", ".", "jid", ".", "bare", "==", "bare", "}", "end" ]
Returns the contact with this jid or nil if not found.
[ "Returns", "the", "contact", "with", "this", "jid", "or", "nil", "if", "not", "found", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/user.rb#L42-L45
train
negativecode/vines
lib/vines/user.rb
Vines.User.remove_contact
def remove_contact(jid) bare = JID.new(jid).bare @roster.reject! {|c| c.jid.bare == bare } end
ruby
def remove_contact(jid) bare = JID.new(jid).bare @roster.reject! {|c| c.jid.bare == bare } end
[ "def", "remove_contact", "(", "jid", ")", "bare", "=", "JID", ".", "new", "(", "jid", ")", ".", "bare", "@roster", ".", "reject!", "{", "|", "c", "|", "c", ".", "jid", ".", "bare", "==", "bare", "}", "end" ]
Removes the contact with this jid from the user's roster.
[ "Removes", "the", "contact", "with", "this", "jid", "from", "the", "user", "s", "roster", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/user.rb#L62-L65
train
negativecode/vines
lib/vines/user.rb
Vines.User.request_subscription
def request_subscription(jid) unless contact = contact(jid) contact = Contact.new(:jid => jid) @roster << contact end contact.ask = 'subscribe' if %w[none from].include?(contact.subscription) end
ruby
def request_subscription(jid) unless contact = contact(jid) contact = Contact.new(:jid => jid) @roster << contact end contact.ask = 'subscribe' if %w[none from].include?(contact.subscription) end
[ "def", "request_subscription", "(", "jid", ")", "unless", "contact", "=", "contact", "(", "jid", ")", "contact", "=", "Contact", ".", "new", "(", ":jid", "=>", "jid", ")", "@roster", "<<", "contact", "end", "contact", ".", "ask", "=", "'subscribe'", "if", "%w[", "none", "from", "]", ".", "include?", "(", "contact", ".", "subscription", ")", "end" ]
Update the contact's jid on this user's roster to signal that this user has requested the contact's permission to receive their presence updates.
[ "Update", "the", "contact", "s", "jid", "on", "this", "user", "s", "roster", "to", "signal", "that", "this", "user", "has", "requested", "the", "contact", "s", "permission", "to", "receive", "their", "presence", "updates", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/user.rb#L81-L87
train
negativecode/vines
lib/vines/user.rb
Vines.User.add_subscription_from
def add_subscription_from(jid) unless contact = contact(jid) contact = Contact.new(:jid => jid) @roster << contact end contact.subscribe_from end
ruby
def add_subscription_from(jid) unless contact = contact(jid) contact = Contact.new(:jid => jid) @roster << contact end contact.subscribe_from end
[ "def", "add_subscription_from", "(", "jid", ")", "unless", "contact", "=", "contact", "(", "jid", ")", "contact", "=", "Contact", ".", "new", "(", ":jid", "=>", "jid", ")", "@roster", "<<", "contact", "end", "contact", ".", "subscribe_from", "end" ]
Add the user's jid to this contact's roster with a subscription state of 'from.' This signals that this contact has approved a user's subscription.
[ "Add", "the", "user", "s", "jid", "to", "this", "contact", "s", "roster", "with", "a", "subscription", "state", "of", "from", ".", "This", "signals", "that", "this", "contact", "has", "approved", "a", "user", "s", "subscription", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/user.rb#L91-L97
train
negativecode/vines
lib/vines/user.rb
Vines.User.to_roster_xml
def to_roster_xml(id) doc = Nokogiri::XML::Document.new doc.create_element('iq', 'id' => id, 'type' => 'result') do |el| el << doc.create_element('query', 'xmlns' => 'jabber:iq:roster') do |query| @roster.sort!.each do |contact| query << contact.to_roster_xml end end end end
ruby
def to_roster_xml(id) doc = Nokogiri::XML::Document.new doc.create_element('iq', 'id' => id, 'type' => 'result') do |el| el << doc.create_element('query', 'xmlns' => 'jabber:iq:roster') do |query| @roster.sort!.each do |contact| query << contact.to_roster_xml end end end end
[ "def", "to_roster_xml", "(", "id", ")", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "new", "doc", ".", "create_element", "(", "'iq'", ",", "'id'", "=>", "id", ",", "'type'", "=>", "'result'", ")", "do", "|", "el", "|", "el", "<<", "doc", ".", "create_element", "(", "'query'", ",", "'xmlns'", "=>", "'jabber:iq:roster'", ")", "do", "|", "query", "|", "@roster", ".", "sort!", ".", "each", "do", "|", "contact", "|", "query", "<<", "contact", ".", "to_roster_xml", "end", "end", "end", "end" ]
Returns this user's roster contacts as an iq query element.
[ "Returns", "this", "user", "s", "roster", "contacts", "as", "an", "iq", "query", "element", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/user.rb#L112-L121
train
negativecode/vines
lib/vines/contact.rb
Vines.Contact.send_roster_push
def send_roster_push(recipient) doc = Nokogiri::XML::Document.new node = doc.create_element('iq', 'id' => Kit.uuid, 'to' => recipient.user.jid.to_s, 'type' => 'set') node << doc.create_element('query', 'xmlns' => NAMESPACES[:roster]) do |query| query << to_roster_xml end recipient.write(node) end
ruby
def send_roster_push(recipient) doc = Nokogiri::XML::Document.new node = doc.create_element('iq', 'id' => Kit.uuid, 'to' => recipient.user.jid.to_s, 'type' => 'set') node << doc.create_element('query', 'xmlns' => NAMESPACES[:roster]) do |query| query << to_roster_xml end recipient.write(node) end
[ "def", "send_roster_push", "(", "recipient", ")", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "new", "node", "=", "doc", ".", "create_element", "(", "'iq'", ",", "'id'", "=>", "Kit", ".", "uuid", ",", "'to'", "=>", "recipient", ".", "user", ".", "jid", ".", "to_s", ",", "'type'", "=>", "'set'", ")", "node", "<<", "doc", ".", "create_element", "(", "'query'", ",", "'xmlns'", "=>", "NAMESPACES", "[", ":roster", "]", ")", "do", "|", "query", "|", "query", "<<", "to_roster_xml", "end", "recipient", ".", "write", "(", "node", ")", "end" ]
Write an iq stanza to the recipient stream representing this contact's current roster item state.
[ "Write", "an", "iq", "stanza", "to", "the", "recipient", "stream", "representing", "this", "contact", "s", "current", "roster", "item", "state", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/contact.rb#L85-L95
train
negativecode/vines
lib/vines/cli.rb
Vines.CLI.start
def start register_storage opts = parse(ARGV) check_config(opts) command = Command.const_get(opts[:command].capitalize).new begin command.run(opts) rescue SystemExit # do nothing rescue Exception => e puts e.message exit(1) end end
ruby
def start register_storage opts = parse(ARGV) check_config(opts) command = Command.const_get(opts[:command].capitalize).new begin command.run(opts) rescue SystemExit # do nothing rescue Exception => e puts e.message exit(1) end end
[ "def", "start", "register_storage", "opts", "=", "parse", "(", "ARGV", ")", "check_config", "(", "opts", ")", "command", "=", "Command", ".", "const_get", "(", "opts", "[", ":command", "]", ".", "capitalize", ")", ".", "new", "begin", "command", ".", "run", "(", "opts", ")", "rescue", "SystemExit", "# do nothing", "rescue", "Exception", "=>", "e", "puts", "e", ".", "message", "exit", "(", "1", ")", "end", "end" ]
Run the command line application to parse arguments and run sub-commands. Exits the process with a non-zero return code to indicate failure. Returns nothing.
[ "Run", "the", "command", "line", "application", "to", "parse", "arguments", "and", "run", "sub", "-", "commands", ".", "Exits", "the", "process", "with", "a", "non", "-", "zero", "return", "code", "to", "indicate", "failure", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/cli.rb#L16-L29
train
negativecode/vines
lib/vines/cli.rb
Vines.CLI.check_config
def check_config(opts) return if %w[bcrypt init].include?(opts[:command]) unless File.exists?(opts[:config]) puts "No config file found at #{opts[:config]}" exit(1) end end
ruby
def check_config(opts) return if %w[bcrypt init].include?(opts[:command]) unless File.exists?(opts[:config]) puts "No config file found at #{opts[:config]}" exit(1) end end
[ "def", "check_config", "(", "opts", ")", "return", "if", "%w[", "bcrypt", "init", "]", ".", "include?", "(", "opts", "[", ":command", "]", ")", "unless", "File", ".", "exists?", "(", "opts", "[", ":config", "]", ")", "puts", "\"No config file found at #{opts[:config]}\"", "exit", "(", "1", ")", "end", "end" ]
Many commands must be run in the context of a vines server directory created with `vines init`. If the command can't find the server's config file, print an error message and exit. Returns nothing.
[ "Many", "commands", "must", "be", "run", "in", "the", "context", "of", "a", "vines", "server", "directory", "created", "with", "vines", "init", ".", "If", "the", "command", "can", "t", "find", "the", "server", "s", "config", "file", "print", "an", "error", "message", "and", "exit", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/cli.rb#L124-L130
train
negativecode/vines
lib/vines/config.rb
Vines.Config.pubsub
def pubsub(domain) host = @vhosts.values.find {|host| host.pubsub?(domain) } host.pubsubs[domain.to_s] if host end
ruby
def pubsub(domain) host = @vhosts.values.find {|host| host.pubsub?(domain) } host.pubsubs[domain.to_s] if host end
[ "def", "pubsub", "(", "domain", ")", "host", "=", "@vhosts", ".", "values", ".", "find", "{", "|", "host", "|", "host", ".", "pubsub?", "(", "domain", ")", "}", "host", ".", "pubsubs", "[", "domain", ".", "to_s", "]", "if", "host", "end" ]
Returns the PubSub system for the domain or nil if pubsub is not enabled for this domain.
[ "Returns", "the", "PubSub", "system", "for", "the", "domain", "or", "nil", "if", "pubsub", "is", "not", "enabled", "for", "this", "domain", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L97-L100
train
negativecode/vines
lib/vines/config.rb
Vines.Config.component?
def component?(*jids) !jids.flatten.index do |jid| !component_password(JID.new(jid).domain) end end
ruby
def component?(*jids) !jids.flatten.index do |jid| !component_password(JID.new(jid).domain) end end
[ "def", "component?", "(", "*", "jids", ")", "!", "jids", ".", "flatten", ".", "index", "do", "|", "jid", "|", "!", "component_password", "(", "JID", ".", "new", "(", "jid", ")", ".", "domain", ")", "end", "end" ]
Return true if all JIDs belong to components hosted by this server.
[ "Return", "true", "if", "all", "JIDs", "belong", "to", "components", "hosted", "by", "this", "server", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L109-L113
train
negativecode/vines
lib/vines/config.rb
Vines.Config.component_password
def component_password(domain) host = @vhosts.values.find {|host| host.component?(domain) } host.password(domain) if host end
ruby
def component_password(domain) host = @vhosts.values.find {|host| host.component?(domain) } host.password(domain) if host end
[ "def", "component_password", "(", "domain", ")", "host", "=", "@vhosts", ".", "values", ".", "find", "{", "|", "host", "|", "host", ".", "component?", "(", "domain", ")", "}", "host", ".", "password", "(", "domain", ")", "if", "host", "end" ]
Return the password for the component or nil if it's not hosted here.
[ "Return", "the", "password", "for", "the", "component", "or", "nil", "if", "it", "s", "not", "hosted", "here", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L116-L119
train
negativecode/vines
lib/vines/config.rb
Vines.Config.local_jid?
def local_jid?(*jids) !jids.flatten.index do |jid| !vhost?(JID.new(jid).domain) end end
ruby
def local_jid?(*jids) !jids.flatten.index do |jid| !vhost?(JID.new(jid).domain) end end
[ "def", "local_jid?", "(", "*", "jids", ")", "!", "jids", ".", "flatten", ".", "index", "do", "|", "jid", "|", "!", "vhost?", "(", "JID", ".", "new", "(", "jid", ")", ".", "domain", ")", "end", "end" ]
Return true if all of the JIDs are hosted by this server.
[ "Return", "true", "if", "all", "of", "the", "JIDs", "are", "hosted", "by", "this", "server", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L122-L126
train
negativecode/vines
lib/vines/config.rb
Vines.Config.allowed?
def allowed?(to, from) to, from = JID.new(to), JID.new(from) return false if to.empty? || from.empty? return true if to.domain == from.domain # same domain always allowed return cross_domain?(to, from) if local_jid?(to, from) # both virtual hosted here return check_subdomains(to, from) if subdomain?(to, from) # component/pubsub to component/pubsub return check_subdomain(to, from) if subdomain?(to) # to component/pubsub return check_subdomain(from, to) if subdomain?(from) # from component/pubsub return cross_domain?(to) if local_jid?(to) # from is remote return cross_domain?(from) if local_jid?(from) # to is remote return false end
ruby
def allowed?(to, from) to, from = JID.new(to), JID.new(from) return false if to.empty? || from.empty? return true if to.domain == from.domain # same domain always allowed return cross_domain?(to, from) if local_jid?(to, from) # both virtual hosted here return check_subdomains(to, from) if subdomain?(to, from) # component/pubsub to component/pubsub return check_subdomain(to, from) if subdomain?(to) # to component/pubsub return check_subdomain(from, to) if subdomain?(from) # from component/pubsub return cross_domain?(to) if local_jid?(to) # from is remote return cross_domain?(from) if local_jid?(from) # to is remote return false end
[ "def", "allowed?", "(", "to", ",", "from", ")", "to", ",", "from", "=", "JID", ".", "new", "(", "to", ")", ",", "JID", ".", "new", "(", "from", ")", "return", "false", "if", "to", ".", "empty?", "||", "from", ".", "empty?", "return", "true", "if", "to", ".", "domain", "==", "from", ".", "domain", "# same domain always allowed", "return", "cross_domain?", "(", "to", ",", "from", ")", "if", "local_jid?", "(", "to", ",", "from", ")", "# both virtual hosted here", "return", "check_subdomains", "(", "to", ",", "from", ")", "if", "subdomain?", "(", "to", ",", "from", ")", "# component/pubsub to component/pubsub", "return", "check_subdomain", "(", "to", ",", "from", ")", "if", "subdomain?", "(", "to", ")", "# to component/pubsub", "return", "check_subdomain", "(", "from", ",", "to", ")", "if", "subdomain?", "(", "from", ")", "# from component/pubsub", "return", "cross_domain?", "(", "to", ")", "if", "local_jid?", "(", "to", ")", "# from is remote", "return", "cross_domain?", "(", "from", ")", "if", "local_jid?", "(", "from", ")", "# to is remote", "return", "false", "end" ]
Return true if the two JIDs are allowed to send messages to each other. Both domains must have enabled cross_domain_messages in their config files.
[ "Return", "true", "if", "the", "two", "JIDs", "are", "allowed", "to", "send", "messages", "to", "each", "other", ".", "Both", "domains", "must", "have", "enabled", "cross_domain_messages", "in", "their", "config", "files", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L154-L165
train
negativecode/vines
lib/vines/config.rb
Vines.Config.strip_domain
def strip_domain(jid) domain = jid.domain.split('.').drop(1).join('.') JID.new(domain) end
ruby
def strip_domain(jid) domain = jid.domain.split('.').drop(1).join('.') JID.new(domain) end
[ "def", "strip_domain", "(", "jid", ")", "domain", "=", "jid", ".", "domain", ".", "split", "(", "'.'", ")", ".", "drop", "(", "1", ")", ".", "join", "(", "'.'", ")", "JID", ".", "new", "(", "domain", ")", "end" ]
Return the third-level JID's domain with the first subdomain stripped off to create a second-level domain. For example, [email protected] returns wonderland.lit.
[ "Return", "the", "third", "-", "level", "JID", "s", "domain", "with", "the", "first", "subdomain", "stripped", "off", "to", "create", "a", "second", "-", "level", "domain", ".", "For", "example", "alice" ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L201-L204
train
negativecode/vines
lib/vines/config.rb
Vines.Config.cross_domain?
def cross_domain?(*jids) !jids.flatten.index do |jid| !vhost(jid.domain).cross_domain_messages? end end
ruby
def cross_domain?(*jids) !jids.flatten.index do |jid| !vhost(jid.domain).cross_domain_messages? end end
[ "def", "cross_domain?", "(", "*", "jids", ")", "!", "jids", ".", "flatten", ".", "index", "do", "|", "jid", "|", "!", "vhost", "(", "jid", ".", "domain", ")", ".", "cross_domain_messages?", "end", "end" ]
Return true if all JIDs are allowed to exchange cross domain messages.
[ "Return", "true", "if", "all", "JIDs", "are", "allowed", "to", "exchange", "cross", "domain", "messages", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/config.rb#L207-L211
train
negativecode/vines
lib/vines/cluster.rb
Vines.Cluster.start
def start @connection.connect @publisher.broadcast(:online) @subscriber.subscribe EM.add_periodic_timer(1) { heartbeat } at_exit do @publisher.broadcast(:offline) @sessions.delete_all(@id) end end
ruby
def start @connection.connect @publisher.broadcast(:online) @subscriber.subscribe EM.add_periodic_timer(1) { heartbeat } at_exit do @publisher.broadcast(:offline) @sessions.delete_all(@id) end end
[ "def", "start", "@connection", ".", "connect", "@publisher", ".", "broadcast", "(", ":online", ")", "@subscriber", ".", "subscribe", "EM", ".", "add_periodic_timer", "(", "1", ")", "{", "heartbeat", "}", "at_exit", "do", "@publisher", ".", "broadcast", "(", ":offline", ")", "@sessions", ".", "delete_all", "(", "@id", ")", "end", "end" ]
Join this node to the cluster by broadcasting its state to the other nodes, subscribing to redis channels, and scheduling periodic heartbeat broadcasts. This method must be called after initialize or this node will not be a cluster member.
[ "Join", "this", "node", "to", "the", "cluster", "by", "broadcasting", "its", "state", "to", "the", "other", "nodes", "subscribing", "to", "redis", "channels", "and", "scheduling", "periodic", "heartbeat", "broadcasts", ".", "This", "method", "must", "be", "called", "after", "initialize", "or", "this", "node", "will", "not", "be", "a", "cluster", "member", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/cluster.rb#L43-L54
train
negativecode/vines
lib/vines/cluster.rb
Vines.Cluster.query
def query(name, *args) fiber, yielding = Fiber.current, true req = connection.send(name, *args) req.errback { fiber.resume rescue yielding = false } req.callback {|response| fiber.resume(response) } Fiber.yield if yielding end
ruby
def query(name, *args) fiber, yielding = Fiber.current, true req = connection.send(name, *args) req.errback { fiber.resume rescue yielding = false } req.callback {|response| fiber.resume(response) } Fiber.yield if yielding end
[ "def", "query", "(", "name", ",", "*", "args", ")", "fiber", ",", "yielding", "=", "Fiber", ".", "current", ",", "true", "req", "=", "connection", ".", "send", "(", "name", ",", "args", ")", "req", ".", "errback", "{", "fiber", ".", "resume", "rescue", "yielding", "=", "false", "}", "req", ".", "callback", "{", "|", "response", "|", "fiber", ".", "resume", "(", "response", ")", "}", "Fiber", ".", "yield", "if", "yielding", "end" ]
Turn an asynchronous redis query into a blocking call by pausing the fiber in which this code is running. Return the result of the query from this method, rather than passing it to a callback block.
[ "Turn", "an", "asynchronous", "redis", "query", "into", "a", "blocking", "call", "by", "pausing", "the", "fiber", "in", "which", "this", "code", "is", "running", ".", "Return", "the", "result", "of", "the", "query", "from", "this", "method", "rather", "than", "passing", "it", "to", "a", "callback", "block", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/cluster.rb#L120-L126
train
negativecode/vines
lib/vines/storage.rb
Vines.Storage.authenticate
def authenticate(username, password) user = find_user(username) hash = BCrypt::Password.new(user.password) rescue nil (hash && hash == password) ? user : nil end
ruby
def authenticate(username, password) user = find_user(username) hash = BCrypt::Password.new(user.password) rescue nil (hash && hash == password) ? user : nil end
[ "def", "authenticate", "(", "username", ",", "password", ")", "user", "=", "find_user", "(", "username", ")", "hash", "=", "BCrypt", "::", "Password", ".", "new", "(", "user", ".", "password", ")", "rescue", "nil", "(", "hash", "&&", "hash", "==", "password", ")", "?", "user", ":", "nil", "end" ]
Validate the username and password pair. username - The String login JID to verify. password - The String password the user presented to the server. Examples user = storage.authenticate('[email protected]', 'secr3t') puts user.nil? This default implementation validates the password against a bcrypt hash of the password stored in the database. Sub-classes not using bcrypt passwords must override this method. Returns a Vines::User object on success, nil on failure.
[ "Validate", "the", "username", "and", "password", "pair", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/storage.rb#L126-L130
train
negativecode/vines
lib/vines/storage.rb
Vines.Storage.authenticate_with_ldap
def authenticate_with_ldap(username, password, &block) op = operation { ldap.authenticate(username, password) } cb = proc {|user| save_ldap_user(user, &block) } EM.defer(op, cb) end
ruby
def authenticate_with_ldap(username, password, &block) op = operation { ldap.authenticate(username, password) } cb = proc {|user| save_ldap_user(user, &block) } EM.defer(op, cb) end
[ "def", "authenticate_with_ldap", "(", "username", ",", "password", ",", "&", "block", ")", "op", "=", "operation", "{", "ldap", ".", "authenticate", "(", "username", ",", "password", ")", "}", "cb", "=", "proc", "{", "|", "user", "|", "save_ldap_user", "(", "user", ",", "block", ")", "}", "EM", ".", "defer", "(", "op", ",", "cb", ")", "end" ]
Bind to the LDAP server using the provided username and password. If authentication succeeds, but the user is not yet stored in our database, save the user to the database. username - The String JID to authenticate. password - The String password the user provided. block - The block that receives the authenticated User or nil. Returns the authenticated User or nil if authentication failed.
[ "Bind", "to", "the", "LDAP", "server", "using", "the", "provided", "username", "and", "password", ".", "If", "authentication", "succeeds", "but", "the", "user", "is", "not", "yet", "stored", "in", "our", "database", "save", "the", "user", "to", "the", "database", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/storage.rb#L288-L292
train
negativecode/vines
lib/vines/storage.rb
Vines.Storage.save_ldap_user
def save_ldap_user(user, &block) Fiber.new do if user.nil? block.call elsif found = find_user(user.jid) block.call(found) else save_user(user) block.call(user) end end.resume end
ruby
def save_ldap_user(user, &block) Fiber.new do if user.nil? block.call elsif found = find_user(user.jid) block.call(found) else save_user(user) block.call(user) end end.resume end
[ "def", "save_ldap_user", "(", "user", ",", "&", "block", ")", "Fiber", ".", "new", "do", "if", "user", ".", "nil?", "block", ".", "call", "elsif", "found", "=", "find_user", "(", "user", ".", "jid", ")", "block", ".", "call", "(", "found", ")", "else", "save_user", "(", "user", ")", "block", ".", "call", "(", "user", ")", "end", "end", ".", "resume", "end" ]
Save missing users to the storage database after they're authenticated with LDAP. This allows admins to define users once in LDAP and have them sync to the chat database the first time they successfully sign in. user - The User to persist, possibly nil. block - The block that receives the saved User, possibly nil. Returns nothing.
[ "Save", "missing", "users", "to", "the", "storage", "database", "after", "they", "re", "authenticated", "with", "LDAP", ".", "This", "allows", "admins", "to", "define", "users", "once", "in", "LDAP", "and", "have", "them", "sync", "to", "the", "chat", "database", "the", "first", "time", "they", "successfully", "sign", "in", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/storage.rb#L303-L314
train
negativecode/vines
lib/vines/router.rb
Vines.Router.connected_resources
def connected_resources(jid, from, proxies=true) jid, from = JID.new(jid), JID.new(from) return [] unless @config.allowed?(jid, from) local = @clients[jid.bare] || EMPTY local = local.select {|stream| stream.user.jid == jid } unless jid.bare? remote = proxies ? proxies(jid) : EMPTY [local, remote].flatten end
ruby
def connected_resources(jid, from, proxies=true) jid, from = JID.new(jid), JID.new(from) return [] unless @config.allowed?(jid, from) local = @clients[jid.bare] || EMPTY local = local.select {|stream| stream.user.jid == jid } unless jid.bare? remote = proxies ? proxies(jid) : EMPTY [local, remote].flatten end
[ "def", "connected_resources", "(", "jid", ",", "from", ",", "proxies", "=", "true", ")", "jid", ",", "from", "=", "JID", ".", "new", "(", "jid", ")", ",", "JID", ".", "new", "(", "from", ")", "return", "[", "]", "unless", "@config", ".", "allowed?", "(", "jid", ",", "from", ")", "local", "=", "@clients", "[", "jid", ".", "bare", "]", "||", "EMPTY", "local", "=", "local", ".", "select", "{", "|", "stream", "|", "stream", ".", "user", ".", "jid", "==", "jid", "}", "unless", "jid", ".", "bare?", "remote", "=", "proxies", "?", "proxies", "(", "jid", ")", ":", "EMPTY", "[", "local", ",", "remote", "]", ".", "flatten", "end" ]
Returns streams for all connected resources for this JID. A resource is considered connected after it has completed authentication and resource binding.
[ "Returns", "streams", "for", "all", "connected", "resources", "for", "this", "JID", ".", "A", "resource", "is", "considered", "connected", "after", "it", "has", "completed", "authentication", "and", "resource", "binding", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L22-L30
train
negativecode/vines
lib/vines/router.rb
Vines.Router.delete
def delete(stream) case stream_type(stream) when :client then return unless stream.connected? jid = stream.user.jid.bare streams = @clients[jid] || [] streams.delete(stream) @clients.delete(jid) if streams.empty? when :server then @servers.delete(stream) when :component then @components.delete(stream) end end
ruby
def delete(stream) case stream_type(stream) when :client then return unless stream.connected? jid = stream.user.jid.bare streams = @clients[jid] || [] streams.delete(stream) @clients.delete(jid) if streams.empty? when :server then @servers.delete(stream) when :component then @components.delete(stream) end end
[ "def", "delete", "(", "stream", ")", "case", "stream_type", "(", "stream", ")", "when", ":client", "then", "return", "unless", "stream", ".", "connected?", "jid", "=", "stream", ".", "user", ".", "jid", ".", "bare", "streams", "=", "@clients", "[", "jid", "]", "||", "[", "]", "streams", ".", "delete", "(", "stream", ")", "@clients", ".", "delete", "(", "jid", ")", "if", "streams", ".", "empty?", "when", ":server", "then", "@servers", ".", "delete", "(", "stream", ")", "when", ":component", "then", "@components", ".", "delete", "(", "stream", ")", "end", "end" ]
Remove the connection from the routing table.
[ "Remove", "the", "connection", "from", "the", "routing", "table", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L64-L75
train
negativecode/vines
lib/vines/router.rb
Vines.Router.route
def route(stanza) to, from = %w[to from].map {|attr| JID.new(stanza[attr]) } return unless @config.allowed?(to, from) key = [to.domain, from.domain] if stream = connection_to(to, from) stream.write(stanza) elsif @pending.key?(key) @pending[key] << stanza elsif @config.s2s?(to.domain) @pending[key] << stanza Vines::Stream::Server.start(@config, to.domain, from.domain) do |stream| stream ? send_pending(key, stream) : return_pending(key) @pending.delete(key) end else raise StanzaErrors::RemoteServerNotFound.new(stanza, 'cancel') end end
ruby
def route(stanza) to, from = %w[to from].map {|attr| JID.new(stanza[attr]) } return unless @config.allowed?(to, from) key = [to.domain, from.domain] if stream = connection_to(to, from) stream.write(stanza) elsif @pending.key?(key) @pending[key] << stanza elsif @config.s2s?(to.domain) @pending[key] << stanza Vines::Stream::Server.start(@config, to.domain, from.domain) do |stream| stream ? send_pending(key, stream) : return_pending(key) @pending.delete(key) end else raise StanzaErrors::RemoteServerNotFound.new(stanza, 'cancel') end end
[ "def", "route", "(", "stanza", ")", "to", ",", "from", "=", "%w[", "to", "from", "]", ".", "map", "{", "|", "attr", "|", "JID", ".", "new", "(", "stanza", "[", "attr", "]", ")", "}", "return", "unless", "@config", ".", "allowed?", "(", "to", ",", "from", ")", "key", "=", "[", "to", ".", "domain", ",", "from", ".", "domain", "]", "if", "stream", "=", "connection_to", "(", "to", ",", "from", ")", "stream", ".", "write", "(", "stanza", ")", "elsif", "@pending", ".", "key?", "(", "key", ")", "@pending", "[", "key", "]", "<<", "stanza", "elsif", "@config", ".", "s2s?", "(", "to", ".", "domain", ")", "@pending", "[", "key", "]", "<<", "stanza", "Vines", "::", "Stream", "::", "Server", ".", "start", "(", "@config", ",", "to", ".", "domain", ",", "from", ".", "domain", ")", "do", "|", "stream", "|", "stream", "?", "send_pending", "(", "key", ",", "stream", ")", ":", "return_pending", "(", "key", ")", "@pending", ".", "delete", "(", "key", ")", "end", "else", "raise", "StanzaErrors", "::", "RemoteServerNotFound", ".", "new", "(", "stanza", ",", "'cancel'", ")", "end", "end" ]
Send the stanza to the appropriate remote server-to-server stream or an external component stream.
[ "Send", "the", "stanza", "to", "the", "appropriate", "remote", "server", "-", "to", "-", "server", "stream", "or", "an", "external", "component", "stream", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L79-L97
train
negativecode/vines
lib/vines/router.rb
Vines.Router.size
def size clients = @clients.values.inject(0) {|sum, arr| sum + arr.size } clients + @servers.size + @components.size end
ruby
def size clients = @clients.values.inject(0) {|sum, arr| sum + arr.size } clients + @servers.size + @components.size end
[ "def", "size", "clients", "=", "@clients", ".", "values", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "arr", "|", "sum", "+", "arr", ".", "size", "}", "clients", "+", "@servers", ".", "size", "+", "@components", ".", "size", "end" ]
Returns the total number of streams connected to the server.
[ "Returns", "the", "total", "number", "of", "streams", "connected", "to", "the", "server", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L100-L103
train
negativecode/vines
lib/vines/router.rb
Vines.Router.return_pending
def return_pending(key) @pending[key].each do |stanza| to, from = JID.new(stanza['to']), JID.new(stanza['from']) xml = StanzaErrors::RemoteServerNotFound.new(stanza, 'cancel').to_xml if @config.component?(from) connection_to(from, to).write(xml) rescue nil else connected_resources(from, to).each {|c| c.write(xml) } end end end
ruby
def return_pending(key) @pending[key].each do |stanza| to, from = JID.new(stanza['to']), JID.new(stanza['from']) xml = StanzaErrors::RemoteServerNotFound.new(stanza, 'cancel').to_xml if @config.component?(from) connection_to(from, to).write(xml) rescue nil else connected_resources(from, to).each {|c| c.write(xml) } end end end
[ "def", "return_pending", "(", "key", ")", "@pending", "[", "key", "]", ".", "each", "do", "|", "stanza", "|", "to", ",", "from", "=", "JID", ".", "new", "(", "stanza", "[", "'to'", "]", ")", ",", "JID", ".", "new", "(", "stanza", "[", "'from'", "]", ")", "xml", "=", "StanzaErrors", "::", "RemoteServerNotFound", ".", "new", "(", "stanza", ",", "'cancel'", ")", ".", "to_xml", "if", "@config", ".", "component?", "(", "from", ")", "connection_to", "(", "from", ",", "to", ")", ".", "write", "(", "xml", ")", "rescue", "nil", "else", "connected_resources", "(", "from", ",", "to", ")", ".", "each", "{", "|", "c", "|", "c", ".", "write", "(", "xml", ")", "}", "end", "end", "end" ]
Return all pending stanzas to their senders as remote-server-not-found errors. Called after a s2s stream has failed to connect.
[ "Return", "all", "pending", "stanzas", "to", "their", "senders", "as", "remote", "-", "server", "-", "not", "-", "found", "errors", ".", "Called", "after", "a", "s2s", "stream", "has", "failed", "to", "connect", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L118-L128
train
negativecode/vines
lib/vines/router.rb
Vines.Router.clients
def clients(jids, from, &filter) jids = filter_allowed(jids, from) local = @clients.values_at(*jids).compact.flatten.select(&filter) proxies = proxies(*jids).select(&filter) [local, proxies].flatten end
ruby
def clients(jids, from, &filter) jids = filter_allowed(jids, from) local = @clients.values_at(*jids).compact.flatten.select(&filter) proxies = proxies(*jids).select(&filter) [local, proxies].flatten end
[ "def", "clients", "(", "jids", ",", "from", ",", "&", "filter", ")", "jids", "=", "filter_allowed", "(", "jids", ",", "from", ")", "local", "=", "@clients", ".", "values_at", "(", "jids", ")", ".", "compact", ".", "flatten", ".", "select", "(", "filter", ")", "proxies", "=", "proxies", "(", "jids", ")", ".", "select", "(", "filter", ")", "[", "local", ",", "proxies", "]", ".", "flatten", "end" ]
Return the client streams to which the from address is allowed to contact. Apply the filter block to each stream to narrow the results before returning the streams.
[ "Return", "the", "client", "streams", "to", "which", "the", "from", "address", "is", "allowed", "to", "contact", ".", "Apply", "the", "filter", "block", "to", "each", "stream", "to", "narrow", "the", "results", "before", "returning", "the", "streams", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L133-L138
train
negativecode/vines
lib/vines/router.rb
Vines.Router.filter_allowed
def filter_allowed(jids, from) from = JID.new(from) jids.flatten.map {|jid| JID.new(jid).bare } .select {|jid| @config.allowed?(jid, from) } end
ruby
def filter_allowed(jids, from) from = JID.new(from) jids.flatten.map {|jid| JID.new(jid).bare } .select {|jid| @config.allowed?(jid, from) } end
[ "def", "filter_allowed", "(", "jids", ",", "from", ")", "from", "=", "JID", ".", "new", "(", "from", ")", "jids", ".", "flatten", ".", "map", "{", "|", "jid", "|", "JID", ".", "new", "(", "jid", ")", ".", "bare", "}", ".", "select", "{", "|", "jid", "|", "@config", ".", "allowed?", "(", "jid", ",", "from", ")", "}", "end" ]
Return the bare JIDs from the list that are allowed to talk to the +from+ JID.
[ "Return", "the", "bare", "JIDs", "from", "the", "list", "that", "are", "allowed", "to", "talk", "to", "the", "+", "from", "+", "JID", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/router.rb#L142-L146
train
negativecode/vines
lib/vines/daemon.rb
Vines.Daemon.running?
def running? begin pid && Process.kill(0, pid) rescue Errno::ESRCH delete_pid false rescue Errno::EPERM true end end
ruby
def running? begin pid && Process.kill(0, pid) rescue Errno::ESRCH delete_pid false rescue Errno::EPERM true end end
[ "def", "running?", "begin", "pid", "&&", "Process", ".", "kill", "(", "0", ",", "pid", ")", "rescue", "Errno", "::", "ESRCH", "delete_pid", "false", "rescue", "Errno", "::", "EPERM", "true", "end", "end" ]
Returns true if the process is running as determined by the numeric pid stored in the pid file created by a previous call to start.
[ "Returns", "true", "if", "the", "process", "is", "running", "as", "determined", "by", "the", "numeric", "pid", "stored", "in", "the", "pid", "file", "created", "by", "a", "previous", "call", "to", "start", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/daemon.rb#L39-L48
train
negativecode/vines
lib/vines/store.rb
Vines.Store.domain?
def domain?(pem, domain) if cert = OpenSSL::X509::Certificate.new(pem) rescue nil OpenSSL::SSL.verify_certificate_identity(cert, domain) rescue false end end
ruby
def domain?(pem, domain) if cert = OpenSSL::X509::Certificate.new(pem) rescue nil OpenSSL::SSL.verify_certificate_identity(cert, domain) rescue false end end
[ "def", "domain?", "(", "pem", ",", "domain", ")", "if", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "pem", ")", "rescue", "nil", "OpenSSL", "::", "SSL", ".", "verify_certificate_identity", "(", "cert", ",", "domain", ")", "rescue", "false", "end", "end" ]
Return true if the domain name matches one of the names in the certificate. In other words, is the certificate provided to us really for the domain to which we think we're connected? pem - The PEM encoded certificate String. domain - The domain name String. Returns true if the certificate was issued for the domain.
[ "Return", "true", "if", "the", "domain", "name", "matches", "one", "of", "the", "names", "in", "the", "certificate", ".", "In", "other", "words", "is", "the", "certificate", "provided", "to", "us", "really", "for", "the", "domain", "to", "which", "we", "think", "we", "re", "connected?" ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/store.rb#L43-L47
train
negativecode/vines
lib/vines/store.rb
Vines.Store.files_for_domain
def files_for_domain(domain) crt = File.expand_path("#{domain}.crt", @dir) key = File.expand_path("#{domain}.key", @dir) return [crt, key] if File.exists?(crt) && File.exists?(key) # Might be a wildcard cert file. @@sources.each do |file, certs| certs.each do |cert| if OpenSSL::SSL.verify_certificate_identity(cert, domain) key = file.chomp(File.extname(file)) + '.key' return [file, key] if File.exists?(file) && File.exists?(key) end end end nil end
ruby
def files_for_domain(domain) crt = File.expand_path("#{domain}.crt", @dir) key = File.expand_path("#{domain}.key", @dir) return [crt, key] if File.exists?(crt) && File.exists?(key) # Might be a wildcard cert file. @@sources.each do |file, certs| certs.each do |cert| if OpenSSL::SSL.verify_certificate_identity(cert, domain) key = file.chomp(File.extname(file)) + '.key' return [file, key] if File.exists?(file) && File.exists?(key) end end end nil end
[ "def", "files_for_domain", "(", "domain", ")", "crt", "=", "File", ".", "expand_path", "(", "\"#{domain}.crt\"", ",", "@dir", ")", "key", "=", "File", ".", "expand_path", "(", "\"#{domain}.key\"", ",", "@dir", ")", "return", "[", "crt", ",", "key", "]", "if", "File", ".", "exists?", "(", "crt", ")", "&&", "File", ".", "exists?", "(", "key", ")", "# Might be a wildcard cert file.", "@@sources", ".", "each", "do", "|", "file", ",", "certs", "|", "certs", ".", "each", "do", "|", "cert", "|", "if", "OpenSSL", "::", "SSL", ".", "verify_certificate_identity", "(", "cert", ",", "domain", ")", "key", "=", "file", ".", "chomp", "(", "File", ".", "extname", "(", "file", ")", ")", "+", "'.key'", "return", "[", "file", ",", "key", "]", "if", "File", ".", "exists?", "(", "file", ")", "&&", "File", ".", "exists?", "(", "key", ")", "end", "end", "end", "nil", "end" ]
Returns a pair of file names containing the public key certificate and matching private key for the given domain. This supports using wildcard certificate files to serve several subdomains. Finding the certificate and private key file for a domain follows these steps: - Look for <domain>.crt and <domain>.key files in the conf/certs directory. If found, return those file names, otherwise . . . - Inspect all conf/certs/*.crt files for certificates that contain the domain name either as the subject common name (CN) or as a DNS subjectAltName. The corresponding private key must be in a file of the same name as the certificate's, but with a .key extension. So in the simplest configuration, the tea.wonderland.lit encryption files would be named: - conf/certs/tea.wonderland.lit.crt - conf/certs/tea.wonderland.lit.key However, in the case of a wildcard certificate for *.wonderland.lit, the files would be: - conf/certs/wonderland.lit.crt - conf/certs/wonderland.lit.key These same two files would be returned for the subdomains of: - tea.wonderland.lit - crumpets.wonderland.lit - etc. domain - The String domain name. Returns a two element String array for the certificate and private key file names or nil if not found.
[ "Returns", "a", "pair", "of", "file", "names", "containing", "the", "public", "key", "certificate", "and", "matching", "private", "key", "for", "the", "given", "domain", ".", "This", "supports", "using", "wildcard", "certificate", "files", "to", "serve", "several", "subdomains", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/store.rb#L106-L121
train
negativecode/vines
lib/vines/stream.rb
Vines.Stream.post_init
def post_init @remote_addr, @local_addr = addresses @user, @closed, @stanza_size = nil, false, 0 @bucket = TokenBucket.new(100, 10) @store = Store.new(@config.certs) @nodes = EM::Queue.new process_node_queue create_parser log.info { "%s %21s -> %s" % ['Stream connected:'.ljust(PAD), @remote_addr, @local_addr] } end
ruby
def post_init @remote_addr, @local_addr = addresses @user, @closed, @stanza_size = nil, false, 0 @bucket = TokenBucket.new(100, 10) @store = Store.new(@config.certs) @nodes = EM::Queue.new process_node_queue create_parser log.info { "%s %21s -> %s" % ['Stream connected:'.ljust(PAD), @remote_addr, @local_addr] } end
[ "def", "post_init", "@remote_addr", ",", "@local_addr", "=", "addresses", "@user", ",", "@closed", ",", "@stanza_size", "=", "nil", ",", "false", ",", "0", "@bucket", "=", "TokenBucket", ".", "new", "(", "100", ",", "10", ")", "@store", "=", "Store", ".", "new", "(", "@config", ".", "certs", ")", "@nodes", "=", "EM", "::", "Queue", ".", "new", "process_node_queue", "create_parser", "log", ".", "info", "{", "\"%s %21s -> %s\"", "%", "[", "'Stream connected:'", ".", "ljust", "(", "PAD", ")", ",", "@remote_addr", ",", "@local_addr", "]", "}", "end" ]
Initialize the stream after its connection to the server has completed. EventMachine calls this method when an incoming connection is accepted into the event loop. Returns nothing.
[ "Initialize", "the", "stream", "after", "its", "connection", "to", "the", "server", "has", "completed", ".", "EventMachine", "calls", "this", "method", "when", "an", "incoming", "connection", "is", "accepted", "into", "the", "event", "loop", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stream.rb#L25-L35
train
negativecode/vines
lib/vines/stream.rb
Vines.Stream.receive_data
def receive_data(data) return if @closed @stanza_size += data.bytesize if @stanza_size < max_stanza_size @parser << data rescue error(StreamErrors::NotWellFormed.new) else error(StreamErrors::PolicyViolation.new('max stanza size reached')) end end
ruby
def receive_data(data) return if @closed @stanza_size += data.bytesize if @stanza_size < max_stanza_size @parser << data rescue error(StreamErrors::NotWellFormed.new) else error(StreamErrors::PolicyViolation.new('max stanza size reached')) end end
[ "def", "receive_data", "(", "data", ")", "return", "if", "@closed", "@stanza_size", "+=", "data", ".", "bytesize", "if", "@stanza_size", "<", "max_stanza_size", "@parser", "<<", "data", "rescue", "error", "(", "StreamErrors", "::", "NotWellFormed", ".", "new", ")", "else", "error", "(", "StreamErrors", "::", "PolicyViolation", ".", "new", "(", "'max stanza size reached'", ")", ")", "end", "end" ]
Read bytes off the stream and feed them into the XML parser. EventMachine is responsible for calling this method on its event loop as connections become readable. data - The byte String sent to the server from the client, hopefully XML. Returns nothing.
[ "Read", "bytes", "off", "the", "stream", "and", "feed", "them", "into", "the", "XML", "parser", ".", "EventMachine", "is", "responsible", "for", "calling", "this", "method", "on", "its", "event", "loop", "as", "connections", "become", "readable", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stream.rb#L69-L77
train
negativecode/vines
lib/vines/stream.rb
Vines.Stream.write
def write(data) log_node(data, :out) if data.respond_to?(:to_xml) data = data.to_xml(:indent => 0) end send_data(data) end
ruby
def write(data) log_node(data, :out) if data.respond_to?(:to_xml) data = data.to_xml(:indent => 0) end send_data(data) end
[ "def", "write", "(", "data", ")", "log_node", "(", "data", ",", ":out", ")", "if", "data", ".", "respond_to?", "(", ":to_xml", ")", "data", "=", "data", ".", "to_xml", "(", ":indent", "=>", "0", ")", "end", "send_data", "(", "data", ")", "end" ]
Send the data over the wire to this client. data - The XML String or XML::Node to write to the socket. Returns nothing.
[ "Send", "the", "data", "over", "the", "wire", "to", "this", "client", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stream.rb#L141-L147
train
negativecode/vines
lib/vines/stream.rb
Vines.Stream.error
def error(e) case e when SaslError, StanzaError write(e.to_xml) when StreamError send_stream_error(e) close_stream else log.error(e) send_stream_error(StreamErrors::InternalServerError.new) close_stream end end
ruby
def error(e) case e when SaslError, StanzaError write(e.to_xml) when StreamError send_stream_error(e) close_stream else log.error(e) send_stream_error(StreamErrors::InternalServerError.new) close_stream end end
[ "def", "error", "(", "e", ")", "case", "e", "when", "SaslError", ",", "StanzaError", "write", "(", "e", ".", "to_xml", ")", "when", "StreamError", "send_stream_error", "(", "e", ")", "close_stream", "else", "log", ".", "error", "(", "e", ")", "send_stream_error", "(", "StreamErrors", "::", "InternalServerError", ".", "new", ")", "close_stream", "end", "end" ]
Stream level errors close the stream while stanza and SASL errors are written to the client and leave the stream open. All exceptions should pass through this method for consistent handling. e - The StandardError, usually XmppError, that occurred. Returns nothing.
[ "Stream", "level", "errors", "close", "the", "stream", "while", "stanza", "and", "SASL", "errors", "are", "written", "to", "the", "client", "and", "leave", "the", "stream", "open", ".", "All", "exceptions", "should", "pass", "through", "this", "method", "for", "consistent", "handling", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stream.rb#L184-L196
train
negativecode/vines
lib/vines/stream.rb
Vines.Stream.addresses
def addresses [get_peername, get_sockname].map do |addr| addr ? Socket.unpack_sockaddr_in(addr)[0, 2].reverse.join(':') : 'unknown' end end
ruby
def addresses [get_peername, get_sockname].map do |addr| addr ? Socket.unpack_sockaddr_in(addr)[0, 2].reverse.join(':') : 'unknown' end end
[ "def", "addresses", "[", "get_peername", ",", "get_sockname", "]", ".", "map", "do", "|", "addr", "|", "addr", "?", "Socket", ".", "unpack_sockaddr_in", "(", "addr", ")", "[", "0", ",", "2", "]", ".", "reverse", ".", "join", "(", "':'", ")", ":", "'unknown'", "end", "end" ]
Determine the remote and local socket addresses used by this connection. Returns a two-element Array of String addresses.
[ "Determine", "the", "remote", "and", "local", "socket", "addresses", "used", "by", "this", "connection", "." ]
245d6c971dd8604d74265d67fd4e2a78319d71a2
https://github.com/negativecode/vines/blob/245d6c971dd8604d74265d67fd4e2a78319d71a2/lib/vines/stream.rb#L207-L211
train
sozialhelden/rosemary
lib/rosemary/member.rb
Rosemary.Member.to_xml
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] xml.member(:type => type, :ref => ref, :role => role) end
ruby
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] xml.member(:type => type, :ref => ref, :role => role) end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "xml", "=", "options", "[", ":builder", "]", "||=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "unless", "options", "[", ":skip_instruct", "]", "xml", ".", "member", "(", ":type", "=>", "type", ",", ":ref", "=>", "ref", ",", ":role", "=>", "role", ")", "end" ]
Create a new Member object. Type can be one of 'node', 'way' or 'relation'. Ref is the ID of the corresponding Node, Way, or Relation. Role is a freeform string and can be empty. Return XML for this way. This method uses the Builder library. The only parameter ist the builder object.
[ "Create", "a", "new", "Member", "object", ".", "Type", "can", "be", "one", "of", "node", "way", "or", "relation", ".", "Ref", "is", "the", "ID", "of", "the", "corresponding", "Node", "Way", "or", "Relation", ".", "Role", "is", "a", "freeform", "string", "and", "can", "be", "empty", ".", "Return", "XML", "for", "this", "way", ".", "This", "method", "uses", "the", "Builder", "library", ".", "The", "only", "parameter", "ist", "the", "builder", "object", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/member.rb#L32-L36
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.destroy
def destroy(element, changeset) element.changeset = changeset.id response = delete("/#{element.type.downcase}/#{element.id}", :body => element.to_xml) unless element.id.nil? response.to_i # New version number end
ruby
def destroy(element, changeset) element.changeset = changeset.id response = delete("/#{element.type.downcase}/#{element.id}", :body => element.to_xml) unless element.id.nil? response.to_i # New version number end
[ "def", "destroy", "(", "element", ",", "changeset", ")", "element", ".", "changeset", "=", "changeset", ".", "id", "response", "=", "delete", "(", "\"/#{element.type.downcase}/#{element.id}\"", ",", ":body", "=>", "element", ".", "to_xml", ")", "unless", "element", ".", "id", ".", "nil?", "response", ".", "to_i", "# New version number", "end" ]
Deletes the given element using API write access. @param [Rosemary::Element] element the element to be created @param [Rosemary::Changeset] changeset the changeset to be used to wrap the write access. @return [Fixnum] the new version of the deleted element.
[ "Deletes", "the", "given", "element", "using", "API", "write", "access", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L122-L126
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.save
def save(element, changeset) response = if element.id.nil? create(element, changeset) else update(element, changeset) end end
ruby
def save(element, changeset) response = if element.id.nil? create(element, changeset) else update(element, changeset) end end
[ "def", "save", "(", "element", ",", "changeset", ")", "response", "=", "if", "element", ".", "id", ".", "nil?", "create", "(", "element", ",", "changeset", ")", "else", "update", "(", "element", ",", "changeset", ")", "end", "end" ]
Creates or updates an element depending on the current state of persistance. @param [Rosemary::Element] element the element to be created @param [Rosemary::Changeset] changeset the changeset to be used to wrap the write access.
[ "Creates", "or", "updates", "an", "element", "depending", "on", "the", "current", "state", "of", "persistance", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L132-L138
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.create
def create(element, changeset) element.changeset = changeset.id put("/#{element.type.downcase}/create", :body => element.to_xml) end
ruby
def create(element, changeset) element.changeset = changeset.id put("/#{element.type.downcase}/create", :body => element.to_xml) end
[ "def", "create", "(", "element", ",", "changeset", ")", "element", ".", "changeset", "=", "changeset", ".", "id", "put", "(", "\"/#{element.type.downcase}/create\"", ",", ":body", "=>", "element", ".", "to_xml", ")", "end" ]
Create a new element using API write access. @param [Rosemary::Element] element the element to be created @param [Rosemary::Changeset] changeset the changeset to be used to wrap the write access. @return [Fixnum] the id of the newly created element.
[ "Create", "a", "new", "element", "using", "API", "write", "access", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L145-L148
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.update
def update(element, changeset) element.changeset = changeset.id response = put("/#{element.type.downcase}/#{element.id}", :body => element.to_xml) response.to_i # New Version number end
ruby
def update(element, changeset) element.changeset = changeset.id response = put("/#{element.type.downcase}/#{element.id}", :body => element.to_xml) response.to_i # New Version number end
[ "def", "update", "(", "element", ",", "changeset", ")", "element", ".", "changeset", "=", "changeset", ".", "id", "response", "=", "put", "(", "\"/#{element.type.downcase}/#{element.id}\"", ",", ":body", "=>", "element", ".", "to_xml", ")", "response", ".", "to_i", "# New Version number", "end" ]
Update an existing element using API write access. @param [Rosemary::Element] element the element to be created @param [Rosemary::Changeset] changeset the changeset to be used to wrap the write access. @return [Fixnum] the versiom of the updated element.
[ "Update", "an", "existing", "element", "using", "API", "write", "access", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L155-L159
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.create_changeset
def create_changeset(comment = nil, tags = {}) tags.merge!(:comment => comment) { |key, v1, v2| v1 } changeset = Changeset.new(:tags => tags) changeset_id = put("/changeset/create", :body => changeset.to_xml).to_i find_changeset(changeset_id) unless changeset_id == 0 end
ruby
def create_changeset(comment = nil, tags = {}) tags.merge!(:comment => comment) { |key, v1, v2| v1 } changeset = Changeset.new(:tags => tags) changeset_id = put("/changeset/create", :body => changeset.to_xml).to_i find_changeset(changeset_id) unless changeset_id == 0 end
[ "def", "create_changeset", "(", "comment", "=", "nil", ",", "tags", "=", "{", "}", ")", "tags", ".", "merge!", "(", ":comment", "=>", "comment", ")", "{", "|", "key", ",", "v1", ",", "v2", "|", "v1", "}", "changeset", "=", "Changeset", ".", "new", "(", ":tags", "=>", "tags", ")", "changeset_id", "=", "put", "(", "\"/changeset/create\"", ",", ":body", "=>", "changeset", ".", "to_xml", ")", ".", "to_i", "find_changeset", "(", "changeset_id", ")", "unless", "changeset_id", "==", "0", "end" ]
Create a new changeset with an optional comment @param [String] comment a meaningful comment for this changeset @return [Rosemary::Changeset] the changeset which was newly created @raise [Rosemary::NotFound] in case the changeset could not be found
[ "Create", "a", "new", "changeset", "with", "an", "optional", "comment" ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L166-L171
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.do_request
def do_request(method, url, options = {}) begin response = self.class.send(method, api_url(url), options) check_response_codes(response) response.parsed_response rescue Timeout::Error raise Unavailable.new('Service Unavailable') end end
ruby
def do_request(method, url, options = {}) begin response = self.class.send(method, api_url(url), options) check_response_codes(response) response.parsed_response rescue Timeout::Error raise Unavailable.new('Service Unavailable') end end
[ "def", "do_request", "(", "method", ",", "url", ",", "options", "=", "{", "}", ")", "begin", "response", "=", "self", ".", "class", ".", "send", "(", "method", ",", "api_url", "(", "url", ")", ",", "options", ")", "check_response_codes", "(", "response", ")", "response", ".", "parsed_response", "rescue", "Timeout", "::", "Error", "raise", "Unavailable", ".", "new", "(", "'Service Unavailable'", ")", "end", "end" ]
Do a API request without authentication
[ "Do", "a", "API", "request", "without", "authentication" ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L244-L252
train
sozialhelden/rosemary
lib/rosemary/api.rb
Rosemary.Api.do_authenticated_request
def do_authenticated_request(method, url, options = {}) begin response = case client when BasicAuthClient self.class.send(method, api_url(url), options.merge(:basic_auth => client.credentials)) when OauthClient # We have to wrap the result of the access_token request into an HTTParty::Response object # to keep duck typing with HTTParty result = client.send(method, api_url(url), options) content_type = Parser.format_from_mimetype(result.content_type) parsed_response = Parser.call(result.body, content_type) HTTParty::Response.new(nil, result, lambda { parsed_response }) else raise CredentialsMissing end check_response_codes(response) response.parsed_response rescue Timeout::Error raise Unavailable.new('Service Unavailable') end end
ruby
def do_authenticated_request(method, url, options = {}) begin response = case client when BasicAuthClient self.class.send(method, api_url(url), options.merge(:basic_auth => client.credentials)) when OauthClient # We have to wrap the result of the access_token request into an HTTParty::Response object # to keep duck typing with HTTParty result = client.send(method, api_url(url), options) content_type = Parser.format_from_mimetype(result.content_type) parsed_response = Parser.call(result.body, content_type) HTTParty::Response.new(nil, result, lambda { parsed_response }) else raise CredentialsMissing end check_response_codes(response) response.parsed_response rescue Timeout::Error raise Unavailable.new('Service Unavailable') end end
[ "def", "do_authenticated_request", "(", "method", ",", "url", ",", "options", "=", "{", "}", ")", "begin", "response", "=", "case", "client", "when", "BasicAuthClient", "self", ".", "class", ".", "send", "(", "method", ",", "api_url", "(", "url", ")", ",", "options", ".", "merge", "(", ":basic_auth", "=>", "client", ".", "credentials", ")", ")", "when", "OauthClient", "# We have to wrap the result of the access_token request into an HTTParty::Response object", "# to keep duck typing with HTTParty", "result", "=", "client", ".", "send", "(", "method", ",", "api_url", "(", "url", ")", ",", "options", ")", "content_type", "=", "Parser", ".", "format_from_mimetype", "(", "result", ".", "content_type", ")", "parsed_response", "=", "Parser", ".", "call", "(", "result", ".", "body", ",", "content_type", ")", "HTTParty", "::", "Response", ".", "new", "(", "nil", ",", "result", ",", "lambda", "{", "parsed_response", "}", ")", "else", "raise", "CredentialsMissing", "end", "check_response_codes", "(", "response", ")", "response", ".", "parsed_response", "rescue", "Timeout", "::", "Error", "raise", "Unavailable", ".", "new", "(", "'Service Unavailable'", ")", "end", "end" ]
Do a API request with authentication, using the given client
[ "Do", "a", "API", "request", "with", "authentication", "using", "the", "given", "client" ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/api.rb#L255-L276
train
sozialhelden/rosemary
lib/rosemary/way.rb
Rosemary.Way.<<
def <<(stuff) case stuff when Array # call this method recursively stuff.each do |item| self << item end when Rosemary::Node nodes << stuff.id when String nodes << stuff.to_i when Integer nodes << stuff else tags.merge!(stuff) end self # return self to allow chaining end
ruby
def <<(stuff) case stuff when Array # call this method recursively stuff.each do |item| self << item end when Rosemary::Node nodes << stuff.id when String nodes << stuff.to_i when Integer nodes << stuff else tags.merge!(stuff) end self # return self to allow chaining end
[ "def", "<<", "(", "stuff", ")", "case", "stuff", "when", "Array", "# call this method recursively", "stuff", ".", "each", "do", "|", "item", "|", "self", "<<", "item", "end", "when", "Rosemary", "::", "Node", "nodes", "<<", "stuff", ".", "id", "when", "String", "nodes", "<<", "stuff", ".", "to_i", "when", "Integer", "nodes", "<<", "stuff", "else", "tags", ".", "merge!", "(", "stuff", ")", "end", "self", "# return self to allow chaining", "end" ]
Add one or more tags or nodes to this way. The argument can be one of the following: * If the argument is a Hash or an OSM::Tags object, those tags are added. * If the argument is an OSM::Node object, its ID is added to the list of node IDs. * If the argument is an Integer or String containing an Integer, this ID is added to the list of node IDs. * If the argument is an Array the function is called recursively, i.e. all items in the Array are added. Returns the way to allow chaining. @return [Rosemary::Way] the way itself
[ "Add", "one", "or", "more", "tags", "or", "nodes", "to", "this", "way", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/way.rb#L44-L60
train
sozialhelden/rosemary
lib/rosemary/tags.rb
Rosemary.Tags.to_xml
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] each do |key, value| # Remove leading and trailing whitespace from tag values xml.tag(:k => key, :v => coder.decode(value.strip)) unless value.blank? end unless empty? end
ruby
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] each do |key, value| # Remove leading and trailing whitespace from tag values xml.tag(:k => key, :v => coder.decode(value.strip)) unless value.blank? end unless empty? end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "xml", "=", "options", "[", ":builder", "]", "||=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "unless", "options", "[", ":skip_instruct", "]", "each", "do", "|", "key", ",", "value", "|", "# Remove leading and trailing whitespace from tag values", "xml", ".", "tag", "(", ":k", "=>", "key", ",", ":v", "=>", "coder", ".", "decode", "(", "value", ".", "strip", ")", ")", "unless", "value", ".", "blank?", "end", "unless", "empty?", "end" ]
Return XML for these tags. This method uses the Builder library. The only parameter ist the builder object.
[ "Return", "XML", "for", "these", "tags", ".", "This", "method", "uses", "the", "Builder", "library", ".", "The", "only", "parameter", "ist", "the", "builder", "object", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/tags.rb#L13-L20
train
sozialhelden/rosemary
lib/rosemary/changeset.rb
Rosemary.Changeset.to_xml
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] xml.osm do xml.changeset(attributes) do tags.each do |k,v| xml.tag(:k => k, :v => v) end unless tags.empty? end end end
ruby
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] xml.osm do xml.changeset(attributes) do tags.each do |k,v| xml.tag(:k => k, :v => v) end unless tags.empty? end end end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "xml", "=", "options", "[", ":builder", "]", "||=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "unless", "options", "[", ":skip_instruct", "]", "xml", ".", "osm", "do", "xml", ".", "changeset", "(", "attributes", ")", "do", "tags", ".", "each", "do", "|", "k", ",", "v", "|", "xml", ".", "tag", "(", ":k", "=>", "k", ",", ":v", "=>", "v", ")", "end", "unless", "tags", ".", "empty?", "end", "end", "end" ]
Renders the object as an xml representation compatible to the OSM API @return [String] XML
[ "Renders", "the", "object", "as", "an", "xml", "representation", "compatible", "to", "the", "OSM", "API" ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/changeset.rb#L87-L97
train
sozialhelden/rosemary
lib/rosemary/relation.rb
Rosemary.Relation.to_xml
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] xml.osm(:generator => "rosemary v#{Rosemary::VERSION}", :version => Rosemary::Api::API_VERSION) do xml.relation(attributes) do members.each do |member| member.to_xml(:builder => xml, :skip_instruct => true) end tags.to_xml(:builder => xml, :skip_instruct => true) end end end
ruby
def to_xml(options = {}) xml = options[:builder] ||= Builder::XmlMarkup.new xml.instruct! unless options[:skip_instruct] xml.osm(:generator => "rosemary v#{Rosemary::VERSION}", :version => Rosemary::Api::API_VERSION) do xml.relation(attributes) do members.each do |member| member.to_xml(:builder => xml, :skip_instruct => true) end tags.to_xml(:builder => xml, :skip_instruct => true) end end end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "xml", "=", "options", "[", ":builder", "]", "||=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "unless", "options", "[", ":skip_instruct", "]", "xml", ".", "osm", "(", ":generator", "=>", "\"rosemary v#{Rosemary::VERSION}\"", ",", ":version", "=>", "Rosemary", "::", "Api", "::", "API_VERSION", ")", "do", "xml", ".", "relation", "(", "attributes", ")", "do", "members", ".", "each", "do", "|", "member", "|", "member", ".", "to_xml", "(", ":builder", "=>", "xml", ",", ":skip_instruct", "=>", "true", ")", "end", "tags", ".", "to_xml", "(", ":builder", "=>", "xml", ",", ":skip_instruct", "=>", "true", ")", "end", "end", "end" ]
Return XML for this relation. This method uses the Builder library. The only parameter ist the builder object.
[ "Return", "XML", "for", "this", "relation", ".", "This", "method", "uses", "the", "Builder", "library", ".", "The", "only", "parameter", "ist", "the", "builder", "object", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/relation.rb#L29-L40
train
sozialhelden/rosemary
lib/rosemary/element.rb
Rosemary.Element.add_tags
def add_tags(new_tags) case new_tags when Array # Called with an array # Call recursively for each entry new_tags.each do |tag_hash| add_tags(tag_hash) end when Hash # Called with a hash #check if it is weird {'k' => 'key', 'v' => 'value'} syntax if (new_tags.size == 2 && new_tags.keys.include?('k') && new_tags.keys.include?('v')) # call recursively with values from k and v keys. add_tags({new_tags['k'] => new_tags['v']}) else # OK, this seems to be a proper ruby hash with a single entry new_tags.each do |k,v| self.tags[k] = v end end end self # return self so calls can be chained end
ruby
def add_tags(new_tags) case new_tags when Array # Called with an array # Call recursively for each entry new_tags.each do |tag_hash| add_tags(tag_hash) end when Hash # Called with a hash #check if it is weird {'k' => 'key', 'v' => 'value'} syntax if (new_tags.size == 2 && new_tags.keys.include?('k') && new_tags.keys.include?('v')) # call recursively with values from k and v keys. add_tags({new_tags['k'] => new_tags['v']}) else # OK, this seems to be a proper ruby hash with a single entry new_tags.each do |k,v| self.tags[k] = v end end end self # return self so calls can be chained end
[ "def", "add_tags", "(", "new_tags", ")", "case", "new_tags", "when", "Array", "# Called with an array", "# Call recursively for each entry", "new_tags", ".", "each", "do", "|", "tag_hash", "|", "add_tags", "(", "tag_hash", ")", "end", "when", "Hash", "# Called with a hash", "#check if it is weird {'k' => 'key', 'v' => 'value'} syntax", "if", "(", "new_tags", ".", "size", "==", "2", "&&", "new_tags", ".", "keys", ".", "include?", "(", "'k'", ")", "&&", "new_tags", ".", "keys", ".", "include?", "(", "'v'", ")", ")", "# call recursively with values from k and v keys.", "add_tags", "(", "{", "new_tags", "[", "'k'", "]", "=>", "new_tags", "[", "'v'", "]", "}", ")", "else", "# OK, this seems to be a proper ruby hash with a single entry", "new_tags", ".", "each", "do", "|", "k", ",", "v", "|", "self", ".", "tags", "[", "k", "]", "=", "v", "end", "end", "end", "self", "# return self so calls can be chained", "end" ]
Add one or more tags to this object. call-seq: add_tags(Hash) -> OsmObject
[ "Add", "one", "or", "more", "tags", "to", "this", "object", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/element.rb#L115-L135
train
sozialhelden/rosemary
lib/rosemary/element.rb
Rosemary.Element.get_relations_from_api
def get_relations_from_api(api=Rosemary::API.new) api.get_relations_referring_to_object(type, self.id.to_i) end
ruby
def get_relations_from_api(api=Rosemary::API.new) api.get_relations_referring_to_object(type, self.id.to_i) end
[ "def", "get_relations_from_api", "(", "api", "=", "Rosemary", "::", "API", ".", "new", ")", "api", ".", "get_relations_referring_to_object", "(", "type", ",", "self", ".", "id", ".", "to_i", ")", "end" ]
Get all relations from the API that have his object as members. The optional parameter is an Rosemary::API object. If none is specified the default OSM API is used. Returns an array of Relation objects or an empty array.
[ "Get", "all", "relations", "from", "the", "API", "that", "have", "his", "object", "as", "members", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/element.rb#L189-L191
train
sozialhelden/rosemary
lib/rosemary/element.rb
Rosemary.Element.get_history_from_api
def get_history_from_api(api=Rosemary::API.new) api.get_history(type, self.id.to_i) end
ruby
def get_history_from_api(api=Rosemary::API.new) api.get_history(type, self.id.to_i) end
[ "def", "get_history_from_api", "(", "api", "=", "Rosemary", "::", "API", ".", "new", ")", "api", ".", "get_history", "(", "type", ",", "self", ".", "id", ".", "to_i", ")", "end" ]
Get the history of this object from the API. The optional parameter is an Rosemary::API object. If none is specified the default OSM API is used. Returns an array of Rosemary::Node, Rosemary::Way, or Rosemary::Relation objects with all the versions.
[ "Get", "the", "history", "of", "this", "object", "from", "the", "API", "." ]
b381016d0817f3601aa1967b460a48ef6977e409
https://github.com/sozialhelden/rosemary/blob/b381016d0817f3601aa1967b460a48ef6977e409/lib/rosemary/element.rb#L200-L202
train
Programatica/cow_proxy
lib/cow_proxy/struct.rb
CowProxy.Struct.dig
def dig(key, *args) value = send(key) args.empty? ? value : value&.dig(*args) end
ruby
def dig(key, *args) value = send(key) args.empty? ? value : value&.dig(*args) end
[ "def", "dig", "(", "key", ",", "*", "args", ")", "value", "=", "send", "(", "key", ")", "args", ".", "empty?", "?", "value", ":", "value", "&.", "dig", "(", "args", ")", "end" ]
Extracts the nested value specified by the sequence of idx objects by calling dig at each step, returning nil if any intermediate step is nil. @return CowProxy wrapped value from wrapped object
[ "Extracts", "the", "nested", "value", "specified", "by", "the", "sequence", "of", "idx", "objects", "by", "calling", "dig", "at", "each", "step", "returning", "nil", "if", "any", "intermediate", "step", "is", "nil", "." ]
05b8de4b31607c0c88193ef5db7228541a735672
https://github.com/Programatica/cow_proxy/blob/05b8de4b31607c0c88193ef5db7228541a735672/lib/cow_proxy/struct.rb#L8-L11
train
Programatica/cow_proxy
lib/cow_proxy/array.rb
CowProxy.Array.map!
def map! __copy_on_write__ return enum_for(:map!) unless block_given? __getobj__.each.with_index do |_, i| self[i] = yield(self[i]) end end
ruby
def map! __copy_on_write__ return enum_for(:map!) unless block_given? __getobj__.each.with_index do |_, i| self[i] = yield(self[i]) end end
[ "def", "map!", "__copy_on_write__", "return", "enum_for", "(", ":map!", ")", "unless", "block_given?", "__getobj__", ".", "each", ".", "with_index", "do", "|", "_", ",", "i", "|", "self", "[", "i", "]", "=", "yield", "(", "self", "[", "i", "]", ")", "end", "end" ]
Invokes the given block once for each element of self, replacing the element with the value returned by the block. @yield [item] Gives each element in self to the block @yieldparam item Wrapped item in self @yieldreturn item to replace @return [CowProxy::Array] self if block given @return [Enumerator] if no block given
[ "Invokes", "the", "given", "block", "once", "for", "each", "element", "of", "self", "replacing", "the", "element", "with", "the", "value", "returned", "by", "the", "block", "." ]
05b8de4b31607c0c88193ef5db7228541a735672
https://github.com/Programatica/cow_proxy/blob/05b8de4b31607c0c88193ef5db7228541a735672/lib/cow_proxy/array.rb#L31-L37
train
bloom-lang/bud
lib/bud/storage/dbm.rb
Bud.BudDbmTable.tick_deltas
def tick_deltas unless @delta.empty? merge_to_db(@delta) @tick_delta.concat(@delta.values) if accumulate_tick_deltas @delta.clear end unless @new_delta.empty? # We allow @new_delta to contain duplicates but eliminate them here. We # can't just allow duplicate delta tuples because that might cause # spurious infinite delta processing loops. @new_delta.reject! {|key, val| self[key] == val} @delta = @new_delta @new_delta = {} end return !(@delta.empty?) end
ruby
def tick_deltas unless @delta.empty? merge_to_db(@delta) @tick_delta.concat(@delta.values) if accumulate_tick_deltas @delta.clear end unless @new_delta.empty? # We allow @new_delta to contain duplicates but eliminate them here. We # can't just allow duplicate delta tuples because that might cause # spurious infinite delta processing loops. @new_delta.reject! {|key, val| self[key] == val} @delta = @new_delta @new_delta = {} end return !(@delta.empty?) end
[ "def", "tick_deltas", "unless", "@delta", ".", "empty?", "merge_to_db", "(", "@delta", ")", "@tick_delta", ".", "concat", "(", "@delta", ".", "values", ")", "if", "accumulate_tick_deltas", "@delta", ".", "clear", "end", "unless", "@new_delta", ".", "empty?", "# We allow @new_delta to contain duplicates but eliminate them here. We", "# can't just allow duplicate delta tuples because that might cause", "# spurious infinite delta processing loops.", "@new_delta", ".", "reject!", "{", "|", "key", ",", "val", "|", "self", "[", "key", "]", "==", "val", "}", "@delta", "=", "@new_delta", "@new_delta", "=", "{", "}", "end", "return", "!", "(", "@delta", ".", "empty?", ")", "end" ]
move deltas to on-disk storage, and new_deltas to deltas
[ "move", "deltas", "to", "on", "-", "disk", "storage", "and", "new_deltas", "to", "deltas" ]
9b665b9140cb2a36611391a0a51fa746175e1db4
https://github.com/bloom-lang/bud/blob/9b665b9140cb2a36611391a0a51fa746175e1db4/lib/bud/storage/dbm.rb#L140-L156
train
bloom-lang/bud
lib/bud/storage/dbm.rb
Bud.BudDbmTable.tick
def tick deleted = nil @to_delete.each do |tuple| k = get_key_vals(tuple) k_str = MessagePack.pack(k) cols_str = @dbm[k_str] unless cols_str.nil? db_cols = MessagePack.unpack(cols_str) delete_cols = val_cols.map{|c| tuple[cols.index(c)]} if db_cols == delete_cols deleted ||= @dbm.delete k_str end end end @to_delete = [] @invalidated = !deleted.nil? unless @pending.empty? @delta = @pending @pending = {} end flush end
ruby
def tick deleted = nil @to_delete.each do |tuple| k = get_key_vals(tuple) k_str = MessagePack.pack(k) cols_str = @dbm[k_str] unless cols_str.nil? db_cols = MessagePack.unpack(cols_str) delete_cols = val_cols.map{|c| tuple[cols.index(c)]} if db_cols == delete_cols deleted ||= @dbm.delete k_str end end end @to_delete = [] @invalidated = !deleted.nil? unless @pending.empty? @delta = @pending @pending = {} end flush end
[ "def", "tick", "deleted", "=", "nil", "@to_delete", ".", "each", "do", "|", "tuple", "|", "k", "=", "get_key_vals", "(", "tuple", ")", "k_str", "=", "MessagePack", ".", "pack", "(", "k", ")", "cols_str", "=", "@dbm", "[", "k_str", "]", "unless", "cols_str", ".", "nil?", "db_cols", "=", "MessagePack", ".", "unpack", "(", "cols_str", ")", "delete_cols", "=", "val_cols", ".", "map", "{", "|", "c", "|", "tuple", "[", "cols", ".", "index", "(", "c", ")", "]", "}", "if", "db_cols", "==", "delete_cols", "deleted", "||=", "@dbm", ".", "delete", "k_str", "end", "end", "end", "@to_delete", "=", "[", "]", "@invalidated", "=", "!", "deleted", ".", "nil?", "unless", "@pending", ".", "empty?", "@delta", "=", "@pending", "@pending", "=", "{", "}", "end", "flush", "end" ]
Remove to_delete and then move pending => delta.
[ "Remove", "to_delete", "and", "then", "move", "pending", "=", ">", "delta", "." ]
9b665b9140cb2a36611391a0a51fa746175e1db4
https://github.com/bloom-lang/bud/blob/9b665b9140cb2a36611391a0a51fa746175e1db4/lib/bud/storage/dbm.rb#L193-L215
train
bloom-lang/bud
lib/bud/storage/zookeeper.rb
Bud.BudZkTable.start_watchers
def start_watchers # Watcher callbacks are invoked in a separate Ruby thread. Note that there # is a possible deadlock between invoking watcher callbacks and calling # close(): if we get a watcher event and a close at around the same time, # the close might fire first. Closing the Zk handle will block on # dispatching outstanding watchers, but it does so holding the @zk_mutex, # causing a deadlock. Hence, we just have the watcher callback spin on the # @zk_mutex, aborting if the handle is ever closed. @child_watcher = Zookeeper::Callbacks::WatcherCallback.new do while true break if @zk.closed? if @zk_mutex.try_lock get_and_watch unless @zk.closed? @zk_mutex.unlock break end end end @stat_watcher = Zookeeper::Callbacks::WatcherCallback.new do while true break if @zk.closed? if @zk_mutex.try_lock stat_and_watch unless @zk.closed? @zk_mutex.unlock break end end end stat_and_watch end
ruby
def start_watchers # Watcher callbacks are invoked in a separate Ruby thread. Note that there # is a possible deadlock between invoking watcher callbacks and calling # close(): if we get a watcher event and a close at around the same time, # the close might fire first. Closing the Zk handle will block on # dispatching outstanding watchers, but it does so holding the @zk_mutex, # causing a deadlock. Hence, we just have the watcher callback spin on the # @zk_mutex, aborting if the handle is ever closed. @child_watcher = Zookeeper::Callbacks::WatcherCallback.new do while true break if @zk.closed? if @zk_mutex.try_lock get_and_watch unless @zk.closed? @zk_mutex.unlock break end end end @stat_watcher = Zookeeper::Callbacks::WatcherCallback.new do while true break if @zk.closed? if @zk_mutex.try_lock stat_and_watch unless @zk.closed? @zk_mutex.unlock break end end end stat_and_watch end
[ "def", "start_watchers", "# Watcher callbacks are invoked in a separate Ruby thread. Note that there", "# is a possible deadlock between invoking watcher callbacks and calling", "# close(): if we get a watcher event and a close at around the same time,", "# the close might fire first. Closing the Zk handle will block on", "# dispatching outstanding watchers, but it does so holding the @zk_mutex,", "# causing a deadlock. Hence, we just have the watcher callback spin on the", "# @zk_mutex, aborting if the handle is ever closed.", "@child_watcher", "=", "Zookeeper", "::", "Callbacks", "::", "WatcherCallback", ".", "new", "do", "while", "true", "break", "if", "@zk", ".", "closed?", "if", "@zk_mutex", ".", "try_lock", "get_and_watch", "unless", "@zk", ".", "closed?", "@zk_mutex", ".", "unlock", "break", "end", "end", "end", "@stat_watcher", "=", "Zookeeper", "::", "Callbacks", "::", "WatcherCallback", ".", "new", "do", "while", "true", "break", "if", "@zk", ".", "closed?", "if", "@zk_mutex", ".", "try_lock", "stat_and_watch", "unless", "@zk", ".", "closed?", "@zk_mutex", ".", "unlock", "break", "end", "end", "end", "stat_and_watch", "end" ]
Since the watcher callbacks might invoke EventMachine, we wait until after EM startup to start watching for Zk events.
[ "Since", "the", "watcher", "callbacks", "might", "invoke", "EventMachine", "we", "wait", "until", "after", "EM", "startup", "to", "start", "watching", "for", "Zk", "events", "." ]
9b665b9140cb2a36611391a0a51fa746175e1db4
https://github.com/bloom-lang/bud/blob/9b665b9140cb2a36611391a0a51fa746175e1db4/lib/bud/storage/zookeeper.rb#L38-L69
train
bloom-lang/bud
lib/bud/collections.rb
Bud.BudChannel.payloads
def payloads(&blk) return self.pro(&blk) if @is_loopback if @payload_struct.nil? payload_cols = cols.dup payload_cols.delete_at(@locspec_idx) @payload_struct = Bud::TupleStruct.new(*payload_cols) @payload_colnums = payload_cols.map {|k| cols.index(k)} end retval = self.pro do |t| @payload_struct.new(*t.values_at(*@payload_colnums)) end retval = retval.pro(&blk) unless blk.nil? return retval end
ruby
def payloads(&blk) return self.pro(&blk) if @is_loopback if @payload_struct.nil? payload_cols = cols.dup payload_cols.delete_at(@locspec_idx) @payload_struct = Bud::TupleStruct.new(*payload_cols) @payload_colnums = payload_cols.map {|k| cols.index(k)} end retval = self.pro do |t| @payload_struct.new(*t.values_at(*@payload_colnums)) end retval = retval.pro(&blk) unless blk.nil? return retval end
[ "def", "payloads", "(", "&", "blk", ")", "return", "self", ".", "pro", "(", "blk", ")", "if", "@is_loopback", "if", "@payload_struct", ".", "nil?", "payload_cols", "=", "cols", ".", "dup", "payload_cols", ".", "delete_at", "(", "@locspec_idx", ")", "@payload_struct", "=", "Bud", "::", "TupleStruct", ".", "new", "(", "payload_cols", ")", "@payload_colnums", "=", "payload_cols", ".", "map", "{", "|", "k", "|", "cols", ".", "index", "(", "k", ")", "}", "end", "retval", "=", "self", ".", "pro", "do", "|", "t", "|", "@payload_struct", ".", "new", "(", "t", ".", "values_at", "(", "@payload_colnums", ")", ")", "end", "retval", "=", "retval", ".", "pro", "(", "blk", ")", "unless", "blk", ".", "nil?", "return", "retval", "end" ]
project to the non-address fields
[ "project", "to", "the", "non", "-", "address", "fields" ]
9b665b9140cb2a36611391a0a51fa746175e1db4
https://github.com/bloom-lang/bud/blob/9b665b9140cb2a36611391a0a51fa746175e1db4/lib/bud/collections.rb#L1023-L1038
train
shioyama/mobility
lib/mobility/util.rb
Mobility.Util.camelize
def camelize(str) call_or_yield str do str.to_s.sub(/^[a-z\d]*/) { $&.capitalize }.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub('/', '::') end end
ruby
def camelize(str) call_or_yield str do str.to_s.sub(/^[a-z\d]*/) { $&.capitalize }.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub('/', '::') end end
[ "def", "camelize", "(", "str", ")", "call_or_yield", "str", "do", "str", ".", "to_s", ".", "sub", "(", "/", "\\d", "/", ")", "{", "$&", ".", "capitalize", "}", ".", "gsub", "(", "/", "\\/", "\\d", "/", ")", "{", "\"#{$1}#{$2.capitalize}\"", "}", ".", "gsub", "(", "'/'", ",", "'::'", ")", "end", "end" ]
Converts strings to UpperCamelCase. @param [String] str @return [String]
[ "Converts", "strings", "to", "UpperCamelCase", "." ]
69869281149a50574e9572733489e1e4599c1620
https://github.com/shioyama/mobility/blob/69869281149a50574e9572733489e1e4599c1620/lib/mobility/util.rb#L43-L47
train
shioyama/mobility
lib/mobility/util.rb
Mobility.Util.call_or_yield
def call_or_yield(object) caller_method = caller_locations(1,1)[0].label if object.respond_to?(caller_method) object.public_send(caller_method) else yield end end
ruby
def call_or_yield(object) caller_method = caller_locations(1,1)[0].label if object.respond_to?(caller_method) object.public_send(caller_method) else yield end end
[ "def", "call_or_yield", "(", "object", ")", "caller_method", "=", "caller_locations", "(", "1", ",", "1", ")", "[", "0", "]", ".", "label", "if", "object", ".", "respond_to?", "(", "caller_method", ")", "object", ".", "public_send", "(", "caller_method", ")", "else", "yield", "end", "end" ]
Calls caller method on object if defined, otherwise yields to block
[ "Calls", "caller", "method", "on", "object", "if", "defined", "otherwise", "yields", "to", "block" ]
69869281149a50574e9572733489e1e4599c1620
https://github.com/shioyama/mobility/blob/69869281149a50574e9572733489e1e4599c1620/lib/mobility/util.rb#L115-L122
train
shioyama/mobility
spec/support/helpers.rb
Helpers.LazyDescribedClass.described_class
def described_class klass = super return klass if klass # crawl up metadata tree looking for description that can be constantized this_metadata = metadata while this_metadata do candidate = this_metadata[:description_args].first begin return candidate.constantize if String === candidate rescue NameError, NoMethodError end this_metadata = this_metadata[:parent_example_group] end end
ruby
def described_class klass = super return klass if klass # crawl up metadata tree looking for description that can be constantized this_metadata = metadata while this_metadata do candidate = this_metadata[:description_args].first begin return candidate.constantize if String === candidate rescue NameError, NoMethodError end this_metadata = this_metadata[:parent_example_group] end end
[ "def", "described_class", "klass", "=", "super", "return", "klass", "if", "klass", "# crawl up metadata tree looking for description that can be constantized", "this_metadata", "=", "metadata", "while", "this_metadata", "do", "candidate", "=", "this_metadata", "[", ":description_args", "]", ".", "first", "begin", "return", "candidate", ".", "constantize", "if", "String", "===", "candidate", "rescue", "NameError", ",", "NoMethodError", "end", "this_metadata", "=", "this_metadata", "[", ":parent_example_group", "]", "end", "end" ]
lazy-load described_class if it's a string
[ "lazy", "-", "load", "described_class", "if", "it", "s", "a", "string" ]
69869281149a50574e9572733489e1e4599c1620
https://github.com/shioyama/mobility/blob/69869281149a50574e9572733489e1e4599c1620/spec/support/helpers.rb#L21-L35
train