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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
keithrbennett/trick_bag
lib/trick_bag/operators/operators.rb
TrickBag.Operators.multi_eq
def multi_eq(*values) # If there is only 1 arg, it must be an array of at least 2 elements. values = values.first if values.first.is_a?(Array) && values.size == 1 raise ArgumentError.new("Must be called with at least 2 parameters; was: #{values.inspect}") if values.size < 2 values[1..-1].all? { |value| value == values.first } end
ruby
def multi_eq(*values) # If there is only 1 arg, it must be an array of at least 2 elements. values = values.first if values.first.is_a?(Array) && values.size == 1 raise ArgumentError.new("Must be called with at least 2 parameters; was: #{values.inspect}") if values.size < 2 values[1..-1].all? { |value| value == values.first } end
[ "def", "multi_eq", "(", "*", "values", ")", "values", "=", "values", ".", "first", "if", "values", ".", "first", ".", "is_a?", "(", "Array", ")", "&&", "values", ".", "size", "==", "1", "raise", "ArgumentError", ".", "new", "(", "\"Must be called with at least 2 parameters; was: #{values.inspect}\"", ")", "if", "values", ".", "size", "<", "2", "values", "[", "1", "..", "-", "1", "]", ".", "all?", "{", "|", "value", "|", "value", "==", "values", ".", "first", "}", "end" ]
Returns whether or not all passed values are equal Ex: multi_eq(1, 1, 1, 2) => false; multi_eq(1, 1, 1, 1) => true
[ "Returns", "whether", "or", "not", "all", "passed", "values", "are", "equal" ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/operators/operators.rb#L9-L14
train
solutious/rudy
lib/rudy/machines.rb
Rudy.Machines.exists?
def exists?(pos=nil) machines = pos.nil? ? list : get(pos) !machines.nil? end
ruby
def exists?(pos=nil) machines = pos.nil? ? list : get(pos) !machines.nil? end
[ "def", "exists?", "(", "pos", "=", "nil", ")", "machines", "=", "pos", ".", "nil?", "?", "list", ":", "get", "(", "pos", ")", "!", "machines", ".", "nil?", "end" ]
Returns true if any machine metadata exists for this group
[ "Returns", "true", "if", "any", "machine", "metadata", "exists", "for", "this", "group" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/machines.rb#L34-L37
train
solutious/rudy
lib/rudy/machines.rb
Rudy.Machines.running?
def running?(pos=nil) group = pos.nil? ? list : [get(pos)].compact return false if group.nil? || group.empty? group.collect! { |m| m.instance_running? } !group.member?(false) end
ruby
def running?(pos=nil) group = pos.nil? ? list : [get(pos)].compact return false if group.nil? || group.empty? group.collect! { |m| m.instance_running? } !group.member?(false) end
[ "def", "running?", "(", "pos", "=", "nil", ")", "group", "=", "pos", ".", "nil?", "?", "list", ":", "[", "get", "(", "pos", ")", "]", ".", "compact", "return", "false", "if", "group", ".", "nil?", "||", "group", ".", "empty?", "group", ".", "collect!", "{", "|", "m", "|", "m", ".", "instance_running?", "}", "!", "group", ".", "member?", "(", "false", ")", "end" ]
Returns true if all machines in the group are running instances
[ "Returns", "true", "if", "all", "machines", "in", "the", "group", "are", "running", "instances" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/machines.rb#L40-L45
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.create_auth_message
def create_auth_message(remote_pubkey, ephemeral_privkey=nil, nonce=nil) raise RLPxSessionError, 'must be initiator' unless initiator? raise InvalidKeyError, 'invalid remote pubkey' unless Crypto::ECCx.valid_key?(remote_pubkey) @remote_pubkey = remote_pubkey token = @ecc.get_ecdh_key remote_pubkey flag = 0x0 @initiator_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) raise RLPxSessionError, 'invalid nonce length' unless @initiator_nonce.size == 32 token_xor_nonce = Utils.sxor token, @initiator_nonce raise RLPxSessionError, 'invalid token xor nonce length' unless token_xor_nonce.size == 32 ephemeral_pubkey = @ephemeral_ecc.raw_pubkey raise InvalidKeyError, 'invalid ephemeral pubkey' unless ephemeral_pubkey.size == 512 / 8 && Crypto::ECCx.valid_key?(ephemeral_pubkey) sig = @ephemeral_ecc.sign token_xor_nonce raise RLPxSessionError, 'invalid signature' unless sig.size == 65 auth_message = "#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}" raise RLPxSessionError, 'invalid auth message length' unless auth_message.size == 194 auth_message end
ruby
def create_auth_message(remote_pubkey, ephemeral_privkey=nil, nonce=nil) raise RLPxSessionError, 'must be initiator' unless initiator? raise InvalidKeyError, 'invalid remote pubkey' unless Crypto::ECCx.valid_key?(remote_pubkey) @remote_pubkey = remote_pubkey token = @ecc.get_ecdh_key remote_pubkey flag = 0x0 @initiator_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) raise RLPxSessionError, 'invalid nonce length' unless @initiator_nonce.size == 32 token_xor_nonce = Utils.sxor token, @initiator_nonce raise RLPxSessionError, 'invalid token xor nonce length' unless token_xor_nonce.size == 32 ephemeral_pubkey = @ephemeral_ecc.raw_pubkey raise InvalidKeyError, 'invalid ephemeral pubkey' unless ephemeral_pubkey.size == 512 / 8 && Crypto::ECCx.valid_key?(ephemeral_pubkey) sig = @ephemeral_ecc.sign token_xor_nonce raise RLPxSessionError, 'invalid signature' unless sig.size == 65 auth_message = "#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}" raise RLPxSessionError, 'invalid auth message length' unless auth_message.size == 194 auth_message end
[ "def", "create_auth_message", "(", "remote_pubkey", ",", "ephemeral_privkey", "=", "nil", ",", "nonce", "=", "nil", ")", "raise", "RLPxSessionError", ",", "'must be initiator'", "unless", "initiator?", "raise", "InvalidKeyError", ",", "'invalid remote pubkey'", "unless", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "remote_pubkey", ")", "@remote_pubkey", "=", "remote_pubkey", "token", "=", "@ecc", ".", "get_ecdh_key", "remote_pubkey", "flag", "=", "0x0", "@initiator_nonce", "=", "nonce", "||", "Crypto", ".", "keccak256", "(", "Utils", ".", "int_to_big_endian", "(", "SecureRandom", ".", "random_number", "(", "TT256", ")", ")", ")", "raise", "RLPxSessionError", ",", "'invalid nonce length'", "unless", "@initiator_nonce", ".", "size", "==", "32", "token_xor_nonce", "=", "Utils", ".", "sxor", "token", ",", "@initiator_nonce", "raise", "RLPxSessionError", ",", "'invalid token xor nonce length'", "unless", "token_xor_nonce", ".", "size", "==", "32", "ephemeral_pubkey", "=", "@ephemeral_ecc", ".", "raw_pubkey", "raise", "InvalidKeyError", ",", "'invalid ephemeral pubkey'", "unless", "ephemeral_pubkey", ".", "size", "==", "512", "/", "8", "&&", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "ephemeral_pubkey", ")", "sig", "=", "@ephemeral_ecc", ".", "sign", "token_xor_nonce", "raise", "RLPxSessionError", ",", "'invalid signature'", "unless", "sig", ".", "size", "==", "65", "auth_message", "=", "\"#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}\"", "raise", "RLPxSessionError", ",", "'invalid auth message length'", "unless", "auth_message", ".", "size", "==", "194", "auth_message", "end" ]
Handshake Auth Message Handling 1. initiator generates ecdhe-random and nonce and creates auth 2. initiator connects to remote and sends auth New: E(remote-pubk, S(ephemeral-privk, ecdh-shared-secret ^ nonce) || H(ephemeral-pubk) || pubk || nonce || 0x0 ) Known: E(remote-pubk, S(ephemeral-privk, token ^ nonce) || H(ephemeral-pubk) || pubk || nonce || 0x1 )
[ "Handshake", "Auth", "Message", "Handling" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L128-L153
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.create_auth_ack_message
def create_auth_ack_message(ephemeral_pubkey=nil, nonce=nil, version=SUPPORTED_RLPX_VERSION, eip8=false) raise RLPxSessionError, 'must not be initiator' if initiator? ephemeral_pubkey = ephemeral_pubkey || @ephemeral_ecc.raw_pubkey @responder_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) if eip8 || @got_eip8_auth msg = create_eip8_auth_ack_message ephemeral_pubkey, @responder_nonce, version raise RLPxSessionError, 'invalid msg size' unless msg.size > 97 else msg = "#{ephemeral_pubkey}#{@responder_nonce}\x00" raise RLPxSessionError, 'invalid msg size' unless msg.size == 97 end msg end
ruby
def create_auth_ack_message(ephemeral_pubkey=nil, nonce=nil, version=SUPPORTED_RLPX_VERSION, eip8=false) raise RLPxSessionError, 'must not be initiator' if initiator? ephemeral_pubkey = ephemeral_pubkey || @ephemeral_ecc.raw_pubkey @responder_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) if eip8 || @got_eip8_auth msg = create_eip8_auth_ack_message ephemeral_pubkey, @responder_nonce, version raise RLPxSessionError, 'invalid msg size' unless msg.size > 97 else msg = "#{ephemeral_pubkey}#{@responder_nonce}\x00" raise RLPxSessionError, 'invalid msg size' unless msg.size == 97 end msg end
[ "def", "create_auth_ack_message", "(", "ephemeral_pubkey", "=", "nil", ",", "nonce", "=", "nil", ",", "version", "=", "SUPPORTED_RLPX_VERSION", ",", "eip8", "=", "false", ")", "raise", "RLPxSessionError", ",", "'must not be initiator'", "if", "initiator?", "ephemeral_pubkey", "=", "ephemeral_pubkey", "||", "@ephemeral_ecc", ".", "raw_pubkey", "@responder_nonce", "=", "nonce", "||", "Crypto", ".", "keccak256", "(", "Utils", ".", "int_to_big_endian", "(", "SecureRandom", ".", "random_number", "(", "TT256", ")", ")", ")", "if", "eip8", "||", "@got_eip8_auth", "msg", "=", "create_eip8_auth_ack_message", "ephemeral_pubkey", ",", "@responder_nonce", ",", "version", "raise", "RLPxSessionError", ",", "'invalid msg size'", "unless", "msg", ".", "size", ">", "97", "else", "msg", "=", "\"#{ephemeral_pubkey}#{@responder_nonce}\\x00\"", "raise", "RLPxSessionError", ",", "'invalid msg size'", "unless", "msg", ".", "size", "==", "97", "end", "msg", "end" ]
Handshake ack message handling authRecipient = E(remote-pubk, remote-ephemeral-pubk || nonce || 0x1) // token found authRecipient = E(remote-pubk, remote-ephemeral-pubk || nonce || 0x0) // token not found nonce, ephemeral_pubkey, version are local
[ "Handshake", "ack", "message", "handling" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L208-L223
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.setup_cipher
def setup_cipher raise RLPxSessionError, 'missing responder nonce' unless @responder_nonce raise RLPxSessionError, 'missing initiator_nonce' unless @initiator_nonce raise RLPxSessionError, 'missing auth_init' unless @auth_init raise RLPxSessionError, 'missing auth_ack' unless @auth_ack raise RLPxSessionError, 'missing remote ephemeral pubkey' unless @remote_ephemeral_pubkey raise InvalidKeyError, 'invalid remote ephemeral pubkey' unless Crypto::ECCx.valid_key?(@remote_ephemeral_pubkey) # derive base secrets from ephemeral key agreement # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk) @ecdhe_shared_secret = @ephemeral_ecc.get_ecdh_key(@remote_ephemeral_pubkey) @shared_secret = Crypto.keccak256("#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}") @token = Crypto.keccak256 @shared_secret @aes_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@shared_secret}" @mac_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@aes_secret}" mac1 = keccak256 "#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}" mac2 = keccak256 "#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}" if initiator? @egress_mac, @ingress_mac = mac1, mac2 else @egress_mac, @ingress_mac = mac2, mac1 end iv = "\x00" * 16 @aes_enc = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.encrypt c.iv = iv c.key = @aes_secret end @aes_dec = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.decrypt c.iv = iv c.key = @aes_secret end @mac_enc = OpenSSL::Cipher.new(MAC_CIPHER).tap do |c| c.encrypt c.key = @mac_secret end @ready = true end
ruby
def setup_cipher raise RLPxSessionError, 'missing responder nonce' unless @responder_nonce raise RLPxSessionError, 'missing initiator_nonce' unless @initiator_nonce raise RLPxSessionError, 'missing auth_init' unless @auth_init raise RLPxSessionError, 'missing auth_ack' unless @auth_ack raise RLPxSessionError, 'missing remote ephemeral pubkey' unless @remote_ephemeral_pubkey raise InvalidKeyError, 'invalid remote ephemeral pubkey' unless Crypto::ECCx.valid_key?(@remote_ephemeral_pubkey) # derive base secrets from ephemeral key agreement # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk) @ecdhe_shared_secret = @ephemeral_ecc.get_ecdh_key(@remote_ephemeral_pubkey) @shared_secret = Crypto.keccak256("#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}") @token = Crypto.keccak256 @shared_secret @aes_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@shared_secret}" @mac_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@aes_secret}" mac1 = keccak256 "#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}" mac2 = keccak256 "#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}" if initiator? @egress_mac, @ingress_mac = mac1, mac2 else @egress_mac, @ingress_mac = mac2, mac1 end iv = "\x00" * 16 @aes_enc = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.encrypt c.iv = iv c.key = @aes_secret end @aes_dec = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.decrypt c.iv = iv c.key = @aes_secret end @mac_enc = OpenSSL::Cipher.new(MAC_CIPHER).tap do |c| c.encrypt c.key = @mac_secret end @ready = true end
[ "def", "setup_cipher", "raise", "RLPxSessionError", ",", "'missing responder nonce'", "unless", "@responder_nonce", "raise", "RLPxSessionError", ",", "'missing initiator_nonce'", "unless", "@initiator_nonce", "raise", "RLPxSessionError", ",", "'missing auth_init'", "unless", "@auth_init", "raise", "RLPxSessionError", ",", "'missing auth_ack'", "unless", "@auth_ack", "raise", "RLPxSessionError", ",", "'missing remote ephemeral pubkey'", "unless", "@remote_ephemeral_pubkey", "raise", "InvalidKeyError", ",", "'invalid remote ephemeral pubkey'", "unless", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "@remote_ephemeral_pubkey", ")", "@ecdhe_shared_secret", "=", "@ephemeral_ecc", ".", "get_ecdh_key", "(", "@remote_ephemeral_pubkey", ")", "@shared_secret", "=", "Crypto", ".", "keccak256", "(", "\"#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}\"", ")", "@token", "=", "Crypto", ".", "keccak256", "@shared_secret", "@aes_secret", "=", "Crypto", ".", "keccak256", "\"#{@ecdhe_shared_secret}#{@shared_secret}\"", "@mac_secret", "=", "Crypto", ".", "keccak256", "\"#{@ecdhe_shared_secret}#{@aes_secret}\"", "mac1", "=", "keccak256", "\"#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}\"", "mac2", "=", "keccak256", "\"#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}\"", "if", "initiator?", "@egress_mac", ",", "@ingress_mac", "=", "mac1", ",", "mac2", "else", "@egress_mac", ",", "@ingress_mac", "=", "mac2", ",", "mac1", "end", "iv", "=", "\"\\x00\"", "*", "16", "@aes_enc", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "ENC_CIPHER", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "encrypt", "c", ".", "iv", "=", "iv", "c", ".", "key", "=", "@aes_secret", "end", "@aes_dec", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "ENC_CIPHER", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "decrypt", "c", ".", "iv", "=", "iv", "c", ".", "key", "=", "@aes_secret", "end", "@mac_enc", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "MAC_CIPHER", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "encrypt", "c", ".", "key", "=", "@mac_secret", "end", "@ready", "=", "true", "end" ]
Handshake Key Derivation
[ "Handshake", "Key", "Derivation" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L273-L315
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_auth_plain
def decode_auth_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,307] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 194 sig = message[0,65] pubkey = message[65+32,64] raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey) nonce = message[65+32+64,32] flag = message[(65+32+64+32)..-1].ord raise RLPxSessionError, 'invalid flag' unless flag == 0 [307, sig, pubkey, nonce, 4] end
ruby
def decode_auth_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,307] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 194 sig = message[0,65] pubkey = message[65+32,64] raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey) nonce = message[65+32+64,32] flag = message[(65+32+64+32)..-1].ord raise RLPxSessionError, 'invalid flag' unless flag == 0 [307, sig, pubkey, nonce, 4] end
[ "def", "decode_auth_plain", "(", "ciphertext", ")", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "ciphertext", "[", "0", ",", "307", "]", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "raise", "RLPxSessionError", ",", "'invalid message length'", "unless", "message", ".", "size", "==", "194", "sig", "=", "message", "[", "0", ",", "65", "]", "pubkey", "=", "message", "[", "65", "+", "32", ",", "64", "]", "raise", "InvalidKeyError", ",", "'invalid initiator pubkey'", "unless", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "pubkey", ")", "nonce", "=", "message", "[", "65", "+", "32", "+", "64", ",", "32", "]", "flag", "=", "message", "[", "(", "65", "+", "32", "+", "64", "+", "32", ")", "..", "-", "1", "]", ".", "ord", "raise", "RLPxSessionError", ",", "'invalid flag'", "unless", "flag", "==", "0", "[", "307", ",", "sig", ",", "pubkey", ",", "nonce", ",", "4", "]", "end" ]
decode legacy pre-EIP-8 auth message format
[ "decode", "legacy", "pre", "-", "EIP", "-", "8", "auth", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L358-L375
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_auth_eip8
def decode_auth_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext size' unless ciphertext.size >= size message = begin @ecc.ecies_decrypt ciphertext[2...size], ciphertext[0,2] rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_auth_sedes, strict: false raise RLPxSessionError, 'invalid values size' unless values.size >= 4 [size] + values[0,4] end
ruby
def decode_auth_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext size' unless ciphertext.size >= size message = begin @ecc.ecies_decrypt ciphertext[2...size], ciphertext[0,2] rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_auth_sedes, strict: false raise RLPxSessionError, 'invalid values size' unless values.size >= 4 [size] + values[0,4] end
[ "def", "decode_auth_eip8", "(", "ciphertext", ")", "size", "=", "ciphertext", "[", "0", ",", "2", "]", ".", "unpack", "(", "'S>'", ")", ".", "first", "+", "2", "raise", "RLPxSessionError", ",", "'invalid ciphertext size'", "unless", "ciphertext", ".", "size", ">=", "size", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "ciphertext", "[", "2", "...", "size", "]", ",", "ciphertext", "[", "0", ",", "2", "]", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "values", "=", "RLP", ".", "decode", "message", ",", "sedes", ":", "eip8_auth_sedes", ",", "strict", ":", "false", "raise", "RLPxSessionError", ",", "'invalid values size'", "unless", "values", ".", "size", ">=", "4", "[", "size", "]", "+", "values", "[", "0", ",", "4", "]", "end" ]
decode EIP-8 auth message format
[ "decode", "EIP", "-", "8", "auth", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L380-L394
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_ack_plain
def decode_ack_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,210] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 64+32+1 ephemeral_pubkey = message[0,64] nonce = message[64,32] known = message[-1].ord raise RLPxSessionError, 'invalid known byte' unless known == 0 [210, ephemeral_pubkey, nonce, 4] end
ruby
def decode_ack_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,210] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 64+32+1 ephemeral_pubkey = message[0,64] nonce = message[64,32] known = message[-1].ord raise RLPxSessionError, 'invalid known byte' unless known == 0 [210, ephemeral_pubkey, nonce, 4] end
[ "def", "decode_ack_plain", "(", "ciphertext", ")", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "ciphertext", "[", "0", ",", "210", "]", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "raise", "RLPxSessionError", ",", "'invalid message length'", "unless", "message", ".", "size", "==", "64", "+", "32", "+", "1", "ephemeral_pubkey", "=", "message", "[", "0", ",", "64", "]", "nonce", "=", "message", "[", "64", ",", "32", "]", "known", "=", "message", "[", "-", "1", "]", ".", "ord", "raise", "RLPxSessionError", ",", "'invalid known byte'", "unless", "known", "==", "0", "[", "210", ",", "ephemeral_pubkey", ",", "nonce", ",", "4", "]", "end" ]
decode legacy pre-EIP-8 ack message format
[ "decode", "legacy", "pre", "-", "EIP", "-", "8", "ack", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L399-L413
train
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_ack_eip8
def decode_ack_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext length' unless ciphertext.size == size message = begin @ecc.ecies_decrypt(ciphertext[2...size], ciphertext[0,2]) rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_ack_sedes, strict: false raise RLPxSessionError, 'invalid values length' unless values.size >= 3 [size] + values[0,3] end
ruby
def decode_ack_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext length' unless ciphertext.size == size message = begin @ecc.ecies_decrypt(ciphertext[2...size], ciphertext[0,2]) rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_ack_sedes, strict: false raise RLPxSessionError, 'invalid values length' unless values.size >= 3 [size] + values[0,3] end
[ "def", "decode_ack_eip8", "(", "ciphertext", ")", "size", "=", "ciphertext", "[", "0", ",", "2", "]", ".", "unpack", "(", "'S>'", ")", ".", "first", "+", "2", "raise", "RLPxSessionError", ",", "'invalid ciphertext length'", "unless", "ciphertext", ".", "size", "==", "size", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "(", "ciphertext", "[", "2", "...", "size", "]", ",", "ciphertext", "[", "0", ",", "2", "]", ")", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "values", "=", "RLP", ".", "decode", "message", ",", "sedes", ":", "eip8_ack_sedes", ",", "strict", ":", "false", "raise", "RLPxSessionError", ",", "'invalid values length'", "unless", "values", ".", "size", ">=", "3", "[", "size", "]", "+", "values", "[", "0", ",", "3", "]", "end" ]
decode EIP-8 ack message format
[ "decode", "EIP", "-", "8", "ack", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L418-L431
train
solutious/rudy
lib/rudy/global.rb
Rudy.Global.apply_system_defaults
def apply_system_defaults if @region.nil? && @zone.nil? @region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE elsif @region.nil? @region = @zone.to_s.gsub(/[a-z]$/, '').to_sym elsif @zone.nil? @zone = "#{@region}b".to_sym end @environment ||= Rudy::DEFAULT_ENVIRONMENT @role ||= Rudy::DEFAULT_ROLE @localhost ||= Rudy.sysinfo.hostname || 'localhost' @auto = false if @auto.nil? end
ruby
def apply_system_defaults if @region.nil? && @zone.nil? @region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE elsif @region.nil? @region = @zone.to_s.gsub(/[a-z]$/, '').to_sym elsif @zone.nil? @zone = "#{@region}b".to_sym end @environment ||= Rudy::DEFAULT_ENVIRONMENT @role ||= Rudy::DEFAULT_ROLE @localhost ||= Rudy.sysinfo.hostname || 'localhost' @auto = false if @auto.nil? end
[ "def", "apply_system_defaults", "if", "@region", ".", "nil?", "&&", "@zone", ".", "nil?", "@region", ",", "@zone", "=", "Rudy", "::", "DEFAULT_REGION", ",", "Rudy", "::", "DEFAULT_ZONE", "elsif", "@region", ".", "nil?", "@region", "=", "@zone", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "to_sym", "elsif", "@zone", ".", "nil?", "@zone", "=", "\"#{@region}b\"", ".", "to_sym", "end", "@environment", "||=", "Rudy", "::", "DEFAULT_ENVIRONMENT", "@role", "||=", "Rudy", "::", "DEFAULT_ROLE", "@localhost", "||=", "Rudy", ".", "sysinfo", ".", "hostname", "||", "'localhost'", "@auto", "=", "false", "if", "@auto", ".", "nil?", "end" ]
Apply defaults for parameters that must have values
[ "Apply", "defaults", "for", "parameters", "that", "must", "have", "values" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/global.rb#L141-L154
train
solutious/rudy
lib/rudy/global.rb
Rudy.Global.clear_system_defaults
def clear_system_defaults @region = nil if @region == Rudy::DEFAULT_REGION @zone = nil if @zone == Rudy::DEFAULT_ZONE @environment = nil if @environment == Rudy::DEFAULT_ENVIRONMENT @role = nil if @role == Rudy::DEFAULT_ROLE @localhost = nil if @localhost == (Rudy.sysinfo.hostname || 'localhost') @auto = nil if @auto == false end
ruby
def clear_system_defaults @region = nil if @region == Rudy::DEFAULT_REGION @zone = nil if @zone == Rudy::DEFAULT_ZONE @environment = nil if @environment == Rudy::DEFAULT_ENVIRONMENT @role = nil if @role == Rudy::DEFAULT_ROLE @localhost = nil if @localhost == (Rudy.sysinfo.hostname || 'localhost') @auto = nil if @auto == false end
[ "def", "clear_system_defaults", "@region", "=", "nil", "if", "@region", "==", "Rudy", "::", "DEFAULT_REGION", "@zone", "=", "nil", "if", "@zone", "==", "Rudy", "::", "DEFAULT_ZONE", "@environment", "=", "nil", "if", "@environment", "==", "Rudy", "::", "DEFAULT_ENVIRONMENT", "@role", "=", "nil", "if", "@role", "==", "Rudy", "::", "DEFAULT_ROLE", "@localhost", "=", "nil", "if", "@localhost", "==", "(", "Rudy", ".", "sysinfo", ".", "hostname", "||", "'localhost'", ")", "@auto", "=", "nil", "if", "@auto", "==", "false", "end" ]
Unapply defaults for parameters that must have values. This is important when reloading configuration since we don't overwrite existing values. If the default ones remained the configuration would not be applied.
[ "Unapply", "defaults", "for", "parameters", "that", "must", "have", "values", ".", "This", "is", "important", "when", "reloading", "configuration", "since", "we", "don", "t", "overwrite", "existing", "values", ".", "If", "the", "default", "ones", "remained", "the", "configuration", "would", "not", "be", "applied", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/global.rb#L160-L167
train
solutious/rudy
lib/rudy/routines/handlers/rye.rb
Rudy::Routines::Handlers.RyeTools.print_command
def print_command(user, host, cmd) #return if @@global.parallel cmd ||= "" cmd, user = cmd.to_s, user.to_s prompt = user == "root" ? "#" : "$" li ("%s@%s%s %s" % [user, host, prompt, cmd.bright]) end
ruby
def print_command(user, host, cmd) #return if @@global.parallel cmd ||= "" cmd, user = cmd.to_s, user.to_s prompt = user == "root" ? "#" : "$" li ("%s@%s%s %s" % [user, host, prompt, cmd.bright]) end
[ "def", "print_command", "(", "user", ",", "host", ",", "cmd", ")", "cmd", "||=", "\"\"", "cmd", ",", "user", "=", "cmd", ".", "to_s", ",", "user", ".", "to_s", "prompt", "=", "user", "==", "\"root\"", "?", "\"#\"", ":", "\"$\"", "li", "(", "\"%s@%s%s %s\"", "%", "[", "user", ",", "host", ",", "prompt", ",", "cmd", ".", "bright", "]", ")", "end" ]
Returns a formatted string for printing command info
[ "Returns", "a", "formatted", "string", "for", "printing", "command", "info" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/routines/handlers/rye.rb#L117-L123
train
Rightpoint/circleci_artifact
lib/circleci_artifact.rb
CircleciArtifact.Fetcher.parse
def parse(artifacts:, queries:) raise ArgumentError, 'Error: Must have artifacts' if artifacts.nil? raise ArgumentError, 'Error: Must have queries' unless queries.is_a?(Array) # Example # [ # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/cherry-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/cherry-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/cherry-pie.png" # }, # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/rhubarb-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png" # } # ] results = ResultSet.new artifacts.body.each do |artifact| url = artifact['url'] if url.nil? STDERR.puts "Warning: No URL found on #{artifact}" next end query = queries.find { |q| url.include?(q.url_substring) } next if query.nil? result = Result.new(query: query, url: url) results.add_result(result) end results end
ruby
def parse(artifacts:, queries:) raise ArgumentError, 'Error: Must have artifacts' if artifacts.nil? raise ArgumentError, 'Error: Must have queries' unless queries.is_a?(Array) # Example # [ # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/cherry-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/cherry-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/cherry-pie.png" # }, # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/rhubarb-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png" # } # ] results = ResultSet.new artifacts.body.each do |artifact| url = artifact['url'] if url.nil? STDERR.puts "Warning: No URL found on #{artifact}" next end query = queries.find { |q| url.include?(q.url_substring) } next if query.nil? result = Result.new(query: query, url: url) results.add_result(result) end results end
[ "def", "parse", "(", "artifacts", ":", ",", "queries", ":", ")", "raise", "ArgumentError", ",", "'Error: Must have artifacts'", "if", "artifacts", ".", "nil?", "raise", "ArgumentError", ",", "'Error: Must have queries'", "unless", "queries", ".", "is_a?", "(", "Array", ")", "results", "=", "ResultSet", ".", "new", "artifacts", ".", "body", ".", "each", "do", "|", "artifact", "|", "url", "=", "artifact", "[", "'url'", "]", "if", "url", ".", "nil?", "STDERR", ".", "puts", "\"Warning: No URL found on #{artifact}\"", "next", "end", "query", "=", "queries", ".", "find", "{", "|", "q", "|", "url", ".", "include?", "(", "q", ".", "url_substring", ")", "}", "next", "if", "query", ".", "nil?", "result", "=", "Result", ".", "new", "(", "query", ":", "query", ",", "url", ":", "url", ")", "results", ".", "add_result", "(", "result", ")", "end", "results", "end" ]
Internal method for extracting results @param artifacts [CircleCi::Artifacts] @param queries [Array<Query>] @return [ResultSet]
[ "Internal", "method", "for", "extracting", "results" ]
ea9c453c7c7ec6d9b6cf6f486b97f2ada161d5d3
https://github.com/Rightpoint/circleci_artifact/blob/ea9c453c7c7ec6d9b6cf6f486b97f2ada161d5d3/lib/circleci_artifact.rb#L126-L162
train
encoreshao/crunchbase-ruby-library
lib/crunchbase/client.rb
Crunchbase.Client.get
def get(permalink, kclass_name, relationship_name = nil) case kclass_name when 'Person' person(permalink, relationship_name) when 'Organization' organization(permalink, relationship_name) end end
ruby
def get(permalink, kclass_name, relationship_name = nil) case kclass_name when 'Person' person(permalink, relationship_name) when 'Organization' organization(permalink, relationship_name) end end
[ "def", "get", "(", "permalink", ",", "kclass_name", ",", "relationship_name", "=", "nil", ")", "case", "kclass_name", "when", "'Person'", "person", "(", "permalink", ",", "relationship_name", ")", "when", "'Organization'", "organization", "(", "permalink", ",", "relationship_name", ")", "end", "end" ]
Get information by permalink with optional one relationship
[ "Get", "information", "by", "permalink", "with", "optional", "one", "relationship" ]
9844f8538ef0e4b33000948d9342d2d7119f3f0c
https://github.com/encoreshao/crunchbase-ruby-library/blob/9844f8538ef0e4b33000948d9342d2d7119f3f0c/lib/crunchbase/client.rb#L6-L13
train
tiagopog/scrapifier
lib/scrapifier/methods.rb
Scrapifier.Methods.scrapify
def scrapify(options = {}) uri, meta = find_uri(options[:which]), {} return meta if uri.nil? if !(uri =~ sf_regex(:image)) meta = sf_eval_uri(uri, options[:images]) elsif !sf_check_img_ext(uri, options[:images]).empty? [:title, :description, :uri, :images].each { |k| meta[k] = uri } end meta end
ruby
def scrapify(options = {}) uri, meta = find_uri(options[:which]), {} return meta if uri.nil? if !(uri =~ sf_regex(:image)) meta = sf_eval_uri(uri, options[:images]) elsif !sf_check_img_ext(uri, options[:images]).empty? [:title, :description, :uri, :images].each { |k| meta[k] = uri } end meta end
[ "def", "scrapify", "(", "options", "=", "{", "}", ")", "uri", ",", "meta", "=", "find_uri", "(", "options", "[", ":which", "]", ")", ",", "{", "}", "return", "meta", "if", "uri", ".", "nil?", "if", "!", "(", "uri", "=~", "sf_regex", "(", ":image", ")", ")", "meta", "=", "sf_eval_uri", "(", "uri", ",", "options", "[", ":images", "]", ")", "elsif", "!", "sf_check_img_ext", "(", "uri", ",", "options", "[", ":images", "]", ")", ".", "empty?", "[", ":title", ",", ":description", ",", ":uri", ",", ":images", "]", ".", "each", "{", "|", "k", "|", "meta", "[", "k", "]", "=", "uri", "}", "end", "meta", "end" ]
Get metadata from an URI using the screen scraping technique. Example: >> 'Wow! What an awesome site: http://adtangerine.com!'.scrapify => { :title => "AdTangerine | Advertising Platform for Social Media", :description => "AdTangerine is an advertising platform that...", :images => [ "http://adtangerine.com/assets/logo_adt_og.png", "http://adtangerine.com/assets/logo_adt_og.png ], :uri => "http://adtangerine.com" } Arguments: options: (Hash) - which: (Integer) Which URI in the String will be used. It starts from 0 to N. - images: (Symbol or Array) Image extensions which are allowed to be returned as result.
[ "Get", "metadata", "from", "an", "URI", "using", "the", "screen", "scraping", "technique", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/methods.rb#L30-L41
train
tiagopog/scrapifier
lib/scrapifier/methods.rb
Scrapifier.Methods.find_uri
def find_uri(which = 0) which = scan(sf_regex(:uri))[which.to_i][0] which =~ sf_regex(:protocol) ? which : "http://#{which}" rescue NoMethodError nil end
ruby
def find_uri(which = 0) which = scan(sf_regex(:uri))[which.to_i][0] which =~ sf_regex(:protocol) ? which : "http://#{which}" rescue NoMethodError nil end
[ "def", "find_uri", "(", "which", "=", "0", ")", "which", "=", "scan", "(", "sf_regex", "(", ":uri", ")", ")", "[", "which", ".", "to_i", "]", "[", "0", "]", "which", "=~", "sf_regex", "(", ":protocol", ")", "?", "which", ":", "\"http://#{which}\"", "rescue", "NoMethodError", "nil", "end" ]
Find URIs in the String. Example: >> 'Wow! What an awesome site: http://adtangerine.com!'.find_uri => 'http://adtangerine.com' >> 'Very cool: http://adtangerine.com and www.twitflink.com'.find_uri 1 => 'www.twitflink.com' Arguments: which: (Integer) - Which URI in the String: first (0), second (1) and so on.
[ "Find", "URIs", "in", "the", "String", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/methods.rb#L53-L58
train
stereocat/expectacle
lib/expectacle/thrower_preview.rb
Expectacle.Thrower.previewed_host_param
def previewed_host_param host_param = @host_param.dup enable_mode = @enable_mode @enable_mode = false host_param[:username] = embed_user_name host_param[:password] = embed_password host_param[:ipaddr] = embed_ipaddr @enable_mode = true host_param[:enable] = embed_password @enable_mode = enable_mode host_param end
ruby
def previewed_host_param host_param = @host_param.dup enable_mode = @enable_mode @enable_mode = false host_param[:username] = embed_user_name host_param[:password] = embed_password host_param[:ipaddr] = embed_ipaddr @enable_mode = true host_param[:enable] = embed_password @enable_mode = enable_mode host_param end
[ "def", "previewed_host_param", "host_param", "=", "@host_param", ".", "dup", "enable_mode", "=", "@enable_mode", "@enable_mode", "=", "false", "host_param", "[", ":username", "]", "=", "embed_user_name", "host_param", "[", ":password", "]", "=", "embed_password", "host_param", "[", ":ipaddr", "]", "=", "embed_ipaddr", "@enable_mode", "=", "true", "host_param", "[", ":enable", "]", "=", "embed_password", "@enable_mode", "=", "enable_mode", "host_param", "end" ]
Setup parameters for a host to preview
[ "Setup", "parameters", "for", "a", "host", "to", "preview" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_preview.rb#L49-L60
train
dankimio/acts_as_learnable
lib/acts_as_learnable/base.rb
ActsAsLearnable.InstanceMethods.reset
def reset self.repetitions = 0 self.interval = 0 self.due = Date.today self.studied_at = Date.today save end
ruby
def reset self.repetitions = 0 self.interval = 0 self.due = Date.today self.studied_at = Date.today save end
[ "def", "reset", "self", ".", "repetitions", "=", "0", "self", ".", "interval", "=", "0", "self", ".", "due", "=", "Date", ".", "today", "self", ".", "studied_at", "=", "Date", ".", "today", "save", "end" ]
Bad recall quality, start over
[ "Bad", "recall", "quality", "start", "over" ]
2bffb223691da31ae8d6519e0cc24dd21f402fee
https://github.com/dankimio/acts_as_learnable/blob/2bffb223691da31ae8d6519e0cc24dd21f402fee/lib/acts_as_learnable/base.rb#L46-L52
train
rsutphin/handbrake.rb
lib/handbrake/cli.rb
HandBrake.CLI.output
def output(filename, options={}) options = options.dup overwrite = options.delete :overwrite case overwrite when true, nil # no special behavior when false raise FileExistsError, filename if File.exist?(filename) when :ignore if File.exist?(filename) trace "Ignoring transcode to #{filename.inspect} because it already exists" return end else raise "Unsupported value for :overwrite: #{overwrite.inspect}" end atomic = options.delete :atomic interim_filename = case atomic when true partial_filename(filename) when String partial_filename(File.join(atomic, File.basename(filename))) when false, nil filename else fail "Unsupported value for :atomic: #{atomic.inspect}" end unless options.empty? raise "Unknown options for output: #{options.keys.inspect}" end FileUtils.mkdir_p(File.dirname(interim_filename), fileutils_options) run('--output', interim_filename) if filename != interim_filename replace = if File.exist?(filename) trace "#{filename.inspect} showed up during transcode" case overwrite when false raise FileExistsError, filename when :ignore trace "- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it" false else trace '- will replace with new transcode' true end else true end FileUtils.mkdir_p(File.dirname(filename), fileutils_options) FileUtils.mv(interim_filename, filename, fileutils_options) if replace end end
ruby
def output(filename, options={}) options = options.dup overwrite = options.delete :overwrite case overwrite when true, nil # no special behavior when false raise FileExistsError, filename if File.exist?(filename) when :ignore if File.exist?(filename) trace "Ignoring transcode to #{filename.inspect} because it already exists" return end else raise "Unsupported value for :overwrite: #{overwrite.inspect}" end atomic = options.delete :atomic interim_filename = case atomic when true partial_filename(filename) when String partial_filename(File.join(atomic, File.basename(filename))) when false, nil filename else fail "Unsupported value for :atomic: #{atomic.inspect}" end unless options.empty? raise "Unknown options for output: #{options.keys.inspect}" end FileUtils.mkdir_p(File.dirname(interim_filename), fileutils_options) run('--output', interim_filename) if filename != interim_filename replace = if File.exist?(filename) trace "#{filename.inspect} showed up during transcode" case overwrite when false raise FileExistsError, filename when :ignore trace "- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it" false else trace '- will replace with new transcode' true end else true end FileUtils.mkdir_p(File.dirname(filename), fileutils_options) FileUtils.mv(interim_filename, filename, fileutils_options) if replace end end
[ "def", "output", "(", "filename", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "overwrite", "=", "options", ".", "delete", ":overwrite", "case", "overwrite", "when", "true", ",", "nil", "when", "false", "raise", "FileExistsError", ",", "filename", "if", "File", ".", "exist?", "(", "filename", ")", "when", ":ignore", "if", "File", ".", "exist?", "(", "filename", ")", "trace", "\"Ignoring transcode to #{filename.inspect} because it already exists\"", "return", "end", "else", "raise", "\"Unsupported value for :overwrite: #{overwrite.inspect}\"", "end", "atomic", "=", "options", ".", "delete", ":atomic", "interim_filename", "=", "case", "atomic", "when", "true", "partial_filename", "(", "filename", ")", "when", "String", "partial_filename", "(", "File", ".", "join", "(", "atomic", ",", "File", ".", "basename", "(", "filename", ")", ")", ")", "when", "false", ",", "nil", "filename", "else", "fail", "\"Unsupported value for :atomic: #{atomic.inspect}\"", "end", "unless", "options", ".", "empty?", "raise", "\"Unknown options for output: #{options.keys.inspect}\"", "end", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "interim_filename", ")", ",", "fileutils_options", ")", "run", "(", "'--output'", ",", "interim_filename", ")", "if", "filename", "!=", "interim_filename", "replace", "=", "if", "File", ".", "exist?", "(", "filename", ")", "trace", "\"#{filename.inspect} showed up during transcode\"", "case", "overwrite", "when", "false", "raise", "FileExistsError", ",", "filename", "when", ":ignore", "trace", "\"- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it\"", "false", "else", "trace", "'- will replace with new transcode'", "true", "end", "else", "true", "end", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "filename", ")", ",", "fileutils_options", ")", "FileUtils", ".", "mv", "(", "interim_filename", ",", "filename", ",", "fileutils_options", ")", "if", "replace", "end", "end" ]
Performs a conversion. This method immediately begins the transcoding process; set all other options first. @param [String] filename the desired name for the final output file. @param [Hash] options additional options to control the behavior of the output process. The provided hash will not be modified. @option options [Boolean,:ignore] :overwrite (true) determines the behavior if the desired output file already exists. If `true`, the file is replaced. If `false`, an exception is thrown. If `:ignore`, the file is skipped; i.e., HandBrakeCLI is not invoked. @option options [Boolean, String] :atomic (false) provides a pseudo-atomic mode for transcoded output. If true, the transcode will go into a temporary file and only be copied to the specified filename if it completes. If the value is literally `true`, the temporary filename is the target filename with `.handbraking` inserted before the extension. If the value is a string, it is interpreted as a path; the temporary file is written to this path instead of in the ultimate target directory. Any `:overwrite` checking will be applied to the target filename both before and after the transcode happens (the temporary file will always be overwritten). This option is intended to aid in writing automatically resumable batch scripts. @return [void]
[ "Performs", "a", "conversion", ".", "This", "method", "immediately", "begins", "the", "transcoding", "process", ";", "set", "all", "other", "options", "first", "." ]
86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec
https://github.com/rsutphin/handbrake.rb/blob/86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec/lib/handbrake/cli.rb#L140-L197
train
rsutphin/handbrake.rb
lib/handbrake/cli.rb
HandBrake.CLI.preset_list
def preset_list result = run('--preset-list') result.output.scan(%r{\< (.*?)\n(.*?)\>}m).inject({}) { |h1, (cat, block)| h1[cat.strip] = block.scan(/\+(.*?):(.*?)\n/).inject({}) { |h2, (name, args)| h2[name.strip] = args.strip h2 } h1 } end
ruby
def preset_list result = run('--preset-list') result.output.scan(%r{\< (.*?)\n(.*?)\>}m).inject({}) { |h1, (cat, block)| h1[cat.strip] = block.scan(/\+(.*?):(.*?)\n/).inject({}) { |h2, (name, args)| h2[name.strip] = args.strip h2 } h1 } end
[ "def", "preset_list", "result", "=", "run", "(", "'--preset-list'", ")", "result", ".", "output", ".", "scan", "(", "%r{", "\\<", "\\n", "\\>", "}m", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "h1", ",", "(", "cat", ",", "block", ")", "|", "h1", "[", "cat", ".", "strip", "]", "=", "block", ".", "scan", "(", "/", "\\+", "\\n", "/", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "h2", ",", "(", "name", ",", "args", ")", "|", "h2", "[", "name", ".", "strip", "]", "=", "args", ".", "strip", "h2", "}", "h1", "}", "end" ]
Returns a structure describing the presets that the current HandBrake install knows about. The structure is a two-level hash. The keys in the first level are the preset categories. The keys in the second level are the preset names and the values are string representations of the arguments for that preset. (This method is included for completeness only. This library does not provide a mechanism to translate the argument lists returned here into the configuration for a {HandBrake::CLI} instance.) @return [Hash]
[ "Returns", "a", "structure", "describing", "the", "presets", "that", "the", "current", "HandBrake", "install", "knows", "about", ".", "The", "structure", "is", "a", "two", "-", "level", "hash", ".", "The", "keys", "in", "the", "first", "level", "are", "the", "preset", "categories", ".", "The", "keys", "in", "the", "second", "level", "are", "the", "preset", "names", "and", "the", "values", "are", "string", "representations", "of", "the", "arguments", "for", "that", "preset", "." ]
86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec
https://github.com/rsutphin/handbrake.rb/blob/86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec/lib/handbrake/cli.rb#L260-L269
train
rsutphin/handbrake.rb
lib/handbrake/cli.rb
HandBrake.CLI.method_missing
def method_missing(name, *args) copy = self.dup copy.instance_eval { @args << [name, *(args.collect { |a| a.to_s })] } copy end
ruby
def method_missing(name, *args) copy = self.dup copy.instance_eval { @args << [name, *(args.collect { |a| a.to_s })] } copy end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "copy", "=", "self", ".", "dup", "copy", ".", "instance_eval", "{", "@args", "<<", "[", "name", ",", "*", "(", "args", ".", "collect", "{", "|", "a", "|", "a", ".", "to_s", "}", ")", "]", "}", "copy", "end" ]
Copies this CLI instance and appends another command line switch plus optional arguments. This method does not do any validation of the switch name; if you use an invalid one, HandBrakeCLI will fail when it is ultimately invoked. @return [CLI]
[ "Copies", "this", "CLI", "instance", "and", "appends", "another", "command", "line", "switch", "plus", "optional", "arguments", "." ]
86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec
https://github.com/rsutphin/handbrake.rb/blob/86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec/lib/handbrake/cli.rb#L303-L307
train
keithrbennett/trick_bag
lib/trick_bag/timing/timing.rb
TrickBag.Timing.retry_until_true_or_timeout
def retry_until_true_or_timeout( sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) test_preconditions = -> do # Method signature has changed from: # (predicate, sleep_interval, timeout_secs, output_stream = $stdout) # to: # (sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) # # Test to see that when old signature is used, a descriptive error is raised. # # This test should be removed when we go to version 1.0. if sleep_interval.respond_to?(:call) raise ArgumentError.new('Sorry, method signature has changed to: ' \ '(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).' \ ' Also a code block can now be provided instead of a lambda.') end if block_given? && predicate raise ArgumentError.new('Both a predicate lambda and a code block were specified.' \ ' Please specify one or the other but not both.') end end test_preconditions.() success = false start_time = Time.now end_time = start_time + timeout_secs text_generator = ->() do now = Time.now elapsed = now - start_time to_go = end_time - now '%9.3f %9.3f' % [elapsed, to_go] end status_updater = ::TrickBag::Io::TextModeStatusUpdater.new(text_generator, output_stream) loop do break if Time.now >= end_time success = !! (block_given? ? yield : predicate.()) break if success status_updater.print sleep(sleep_interval) end output_stream.print "\n" success end
ruby
def retry_until_true_or_timeout( sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) test_preconditions = -> do # Method signature has changed from: # (predicate, sleep_interval, timeout_secs, output_stream = $stdout) # to: # (sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) # # Test to see that when old signature is used, a descriptive error is raised. # # This test should be removed when we go to version 1.0. if sleep_interval.respond_to?(:call) raise ArgumentError.new('Sorry, method signature has changed to: ' \ '(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).' \ ' Also a code block can now be provided instead of a lambda.') end if block_given? && predicate raise ArgumentError.new('Both a predicate lambda and a code block were specified.' \ ' Please specify one or the other but not both.') end end test_preconditions.() success = false start_time = Time.now end_time = start_time + timeout_secs text_generator = ->() do now = Time.now elapsed = now - start_time to_go = end_time - now '%9.3f %9.3f' % [elapsed, to_go] end status_updater = ::TrickBag::Io::TextModeStatusUpdater.new(text_generator, output_stream) loop do break if Time.now >= end_time success = !! (block_given? ? yield : predicate.()) break if success status_updater.print sleep(sleep_interval) end output_stream.print "\n" success end
[ "def", "retry_until_true_or_timeout", "(", "sleep_interval", ",", "timeout_secs", ",", "output_stream", "=", "$stdout", ",", "predicate", "=", "nil", ")", "test_preconditions", "=", "->", "do", "if", "sleep_interval", ".", "respond_to?", "(", ":call", ")", "raise", "ArgumentError", ".", "new", "(", "'Sorry, method signature has changed to: '", "'(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).'", "' Also a code block can now be provided instead of a lambda.'", ")", "end", "if", "block_given?", "&&", "predicate", "raise", "ArgumentError", ".", "new", "(", "'Both a predicate lambda and a code block were specified.'", "' Please specify one or the other but not both.'", ")", "end", "end", "test_preconditions", ".", "(", ")", "success", "=", "false", "start_time", "=", "Time", ".", "now", "end_time", "=", "start_time", "+", "timeout_secs", "text_generator", "=", "->", "(", ")", "do", "now", "=", "Time", ".", "now", "elapsed", "=", "now", "-", "start_time", "to_go", "=", "end_time", "-", "now", "'%9.3f %9.3f'", "%", "[", "elapsed", ",", "to_go", "]", "end", "status_updater", "=", "::", "TrickBag", "::", "Io", "::", "TextModeStatusUpdater", ".", "new", "(", "text_generator", ",", "output_stream", ")", "loop", "do", "break", "if", "Time", ".", "now", ">=", "end_time", "success", "=", "!", "!", "(", "block_given?", "?", "yield", ":", "predicate", ".", "(", ")", ")", "break", "if", "success", "status_updater", ".", "print", "sleep", "(", "sleep_interval", ")", "end", "output_stream", ".", "print", "\"\\n\"", "success", "end" ]
Calls a predicate proc repeatedly, sleeping the specified interval between calls, returning if the predicate returns true, and giving up after the specified number of seconds. Displays elapsed and remaining times on the terminal. Outputs the time elapsed and the time to go. @param predicate something that can be called with .() or .call that returns a truthy value that indicates no further retries are necessary @param sleep_interval number of seconds (fractions ok) to wait between tries @param timeout_secs maximum number of seconds (fractions ok) during which to retry @return true if/when the predicate returns true, false if it times out Ex: TrickBag::Timing.retry_until_true_or_timeout(->{false}, 1.0, 5) Example Code: require 'trick_bag' predicate = -> { false } print "Waiting 10 seconds for true to be returned (but it won't):\n" TrickBag::Timing.retry_until_true_or_timeout(predicate, 1, 10)
[ "Calls", "a", "predicate", "proc", "repeatedly", "sleeping", "the", "specified", "interval", "between", "calls", "returning", "if", "the", "predicate", "returns", "true", "and", "giving", "up", "after", "the", "specified", "number", "of", "seconds", ".", "Displays", "elapsed", "and", "remaining", "times", "on", "the", "terminal", ".", "Outputs", "the", "time", "elapsed", "and", "the", "time", "to", "go", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/timing/timing.rb#L31-L82
train
keithrbennett/trick_bag
lib/trick_bag/timing/timing.rb
TrickBag.Timing.benchmark
def benchmark(caption, out_stream = $stdout, &block) return_value = nil bm = Benchmark.measure { return_value = block.call } out_stream << bm.to_s.chomp << ": #{caption}\n" return_value end
ruby
def benchmark(caption, out_stream = $stdout, &block) return_value = nil bm = Benchmark.measure { return_value = block.call } out_stream << bm.to_s.chomp << ": #{caption}\n" return_value end
[ "def", "benchmark", "(", "caption", ",", "out_stream", "=", "$stdout", ",", "&", "block", ")", "return_value", "=", "nil", "bm", "=", "Benchmark", ".", "measure", "{", "return_value", "=", "block", ".", "call", "}", "out_stream", "<<", "bm", ".", "to_s", ".", "chomp", "<<", "\": #{caption}\\n\"", "return_value", "end" ]
Executes the passed block with the Ruby Benchmark standard library. Prints the benchmark string to the specified output stream. Returns the passed block's return value. e.g. benchmark('time to loop 1,000,000 times') { 1_000_000.times { 42 }; 'hi' } outputs the following string: 0.050000 0.000000 0.050000 ( 0.042376): time to loop 1,000,000 times and returns: 'hi' @param caption the text fragment to print after the timing data @param out_stream object responding to << that will get the output string defaults to $stdout @block the block to execute and benchmark
[ "Executes", "the", "passed", "block", "with", "the", "Ruby", "Benchmark", "standard", "library", ".", "Prints", "the", "benchmark", "string", "to", "the", "specified", "output", "stream", ".", "Returns", "the", "passed", "block", "s", "return", "value", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/timing/timing.rb#L98-L103
train
keithrbennett/trick_bag
lib/trick_bag/timing/timing.rb
TrickBag.Timing.try_with_timeout
def try_with_timeout(max_seconds, check_interval_in_secs, &block) raise "Must pass block to this method" unless block_given? end_time = Time.now + max_seconds block_return_value = nil thread = Thread.new { block_return_value = block.call } while Time.now < end_time unless thread.alive? return [true, block_return_value] end sleep(check_interval_in_secs) end thread.kill [false, nil] end
ruby
def try_with_timeout(max_seconds, check_interval_in_secs, &block) raise "Must pass block to this method" unless block_given? end_time = Time.now + max_seconds block_return_value = nil thread = Thread.new { block_return_value = block.call } while Time.now < end_time unless thread.alive? return [true, block_return_value] end sleep(check_interval_in_secs) end thread.kill [false, nil] end
[ "def", "try_with_timeout", "(", "max_seconds", ",", "check_interval_in_secs", ",", "&", "block", ")", "raise", "\"Must pass block to this method\"", "unless", "block_given?", "end_time", "=", "Time", ".", "now", "+", "max_seconds", "block_return_value", "=", "nil", "thread", "=", "Thread", ".", "new", "{", "block_return_value", "=", "block", ".", "call", "}", "while", "Time", ".", "now", "<", "end_time", "unless", "thread", ".", "alive?", "return", "[", "true", ",", "block_return_value", "]", "end", "sleep", "(", "check_interval_in_secs", ")", "end", "thread", ".", "kill", "[", "false", ",", "nil", "]", "end" ]
Runs the passed block in a new thread, ensuring that its execution time does not exceed the specified duration. @param max_seconds maximum number of seconds to wait for completion @param check_interval_in_secs interval in seconds at which to check for completion @block block of code to execute in the secondary thread @return [true, block return value] if the block completes before timeout or [false, nil] if the block is still active (i.e. the thread is still alive) when max_seconds is reached
[ "Runs", "the", "passed", "block", "in", "a", "new", "thread", "ensuring", "that", "its", "execution", "time", "does", "not", "exceed", "the", "specified", "duration", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/timing/timing.rb#L116-L129
train
cryptape/ruby-devp2p
lib/devp2p/command.rb
DEVp2p.Command.create
def create(proto, *args) options = args.last.is_a?(Hash) ? args.pop : {} raise ArgumentError, "proto #{proto} must be protocol" unless proto.is_a?(Protocol) raise ArgumentError, "command structure mismatch" if !options.empty? && structure.instance_of?(RLP::Sedes::CountableList) options.empty? ? args : options end
ruby
def create(proto, *args) options = args.last.is_a?(Hash) ? args.pop : {} raise ArgumentError, "proto #{proto} must be protocol" unless proto.is_a?(Protocol) raise ArgumentError, "command structure mismatch" if !options.empty? && structure.instance_of?(RLP::Sedes::CountableList) options.empty? ? args : options end
[ "def", "create", "(", "proto", ",", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "raise", "ArgumentError", ",", "\"proto #{proto} must be protocol\"", "unless", "proto", ".", "is_a?", "(", "Protocol", ")", "raise", "ArgumentError", ",", "\"command structure mismatch\"", "if", "!", "options", ".", "empty?", "&&", "structure", ".", "instance_of?", "(", "RLP", "::", "Sedes", "::", "CountableList", ")", "options", ".", "empty?", "?", "args", ":", "options", "end" ]
optionally implement create
[ "optionally", "implement", "create" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/command.rb#L65-L70
train
cryptape/ruby-devp2p
lib/devp2p/command.rb
DEVp2p.Command.receive
def receive(proto, data) if structure.instance_of?(RLP::Sedes::CountableList) receive_callbacks.each {|cb| cb.call(proto, data) } else receive_callbacks.each {|cb| cb.call(proto, **data) } end end
ruby
def receive(proto, data) if structure.instance_of?(RLP::Sedes::CountableList) receive_callbacks.each {|cb| cb.call(proto, data) } else receive_callbacks.each {|cb| cb.call(proto, **data) } end end
[ "def", "receive", "(", "proto", ",", "data", ")", "if", "structure", ".", "instance_of?", "(", "RLP", "::", "Sedes", "::", "CountableList", ")", "receive_callbacks", ".", "each", "{", "|", "cb", "|", "cb", ".", "call", "(", "proto", ",", "data", ")", "}", "else", "receive_callbacks", ".", "each", "{", "|", "cb", "|", "cb", ".", "call", "(", "proto", ",", "**", "data", ")", "}", "end", "end" ]
optionally implement receive
[ "optionally", "implement", "receive" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/command.rb#L73-L79
train
ruby-protobuf/protobuf-core
lib/protobuf/encoder.rb
Protobuf.Encoder.write_pair
def write_pair(field, value) key = (field.tag << 3) | field.wire_type stream << ::Protobuf::Field::VarintField.encode(key) stream << field.encode(value) end
ruby
def write_pair(field, value) key = (field.tag << 3) | field.wire_type stream << ::Protobuf::Field::VarintField.encode(key) stream << field.encode(value) end
[ "def", "write_pair", "(", "field", ",", "value", ")", "key", "=", "(", "field", ".", "tag", "<<", "3", ")", "|", "field", ".", "wire_type", "stream", "<<", "::", "Protobuf", "::", "Field", "::", "VarintField", ".", "encode", "(", "key", ")", "stream", "<<", "field", ".", "encode", "(", "value", ")", "end" ]
Encode key and value, and write to +stream+.
[ "Encode", "key", "and", "value", "and", "write", "to", "+", "stream", "+", "." ]
67c37d1c54cadfe9a9e56b8df351549eed1e38bd
https://github.com/ruby-protobuf/protobuf-core/blob/67c37d1c54cadfe9a9e56b8df351549eed1e38bd/lib/protobuf/encoder.rb#L60-L64
train
solutious/rudy
lib/rudy/backups.rb
Rudy.Backups.get
def get(path) tmp = Rudy::Backup.new path backups = Rudy::Backups.list :path => path return nil unless backups.is_a?(Array) && !backups.empty? backups.first end
ruby
def get(path) tmp = Rudy::Backup.new path backups = Rudy::Backups.list :path => path return nil unless backups.is_a?(Array) && !backups.empty? backups.first end
[ "def", "get", "(", "path", ")", "tmp", "=", "Rudy", "::", "Backup", ".", "new", "path", "backups", "=", "Rudy", "::", "Backups", ".", "list", ":path", "=>", "path", "return", "nil", "unless", "backups", ".", "is_a?", "(", "Array", ")", "&&", "!", "backups", ".", "empty?", "backups", ".", "first", "end" ]
Returns the most recent backup object for the given path
[ "Returns", "the", "most", "recent", "backup", "object", "for", "the", "given", "path" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/backups.rb#L12-L17
train
cryptape/ruby-devp2p
lib/devp2p/multiplexer.rb
DEVp2p.Multiplexer.pop_frames
def pop_frames protocols = @queues.keys idx = protocols.index next_protocol protocols = protocols[idx..-1] + protocols[0,idx] protocols.each do |id| frames = pop_frames_for_protocol id return frames unless frames.empty? end [] end
ruby
def pop_frames protocols = @queues.keys idx = protocols.index next_protocol protocols = protocols[idx..-1] + protocols[0,idx] protocols.each do |id| frames = pop_frames_for_protocol id return frames unless frames.empty? end [] end
[ "def", "pop_frames", "protocols", "=", "@queues", ".", "keys", "idx", "=", "protocols", ".", "index", "next_protocol", "protocols", "=", "protocols", "[", "idx", "..", "-", "1", "]", "+", "protocols", "[", "0", ",", "idx", "]", "protocols", ".", "each", "do", "|", "id", "|", "frames", "=", "pop_frames_for_protocol", "id", "return", "frames", "unless", "frames", ".", "empty?", "end", "[", "]", "end" ]
Returns the frames for the next protocol up to protocol window size bytes.
[ "Returns", "the", "frames", "for", "the", "next", "protocol", "up", "to", "protocol", "window", "size", "bytes", "." ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/multiplexer.rb#L183-L194
train
keithrbennett/trick_bag
lib/trick_bag/formatters/formatters.rb
TrickBag.Formatters.array_diff
def array_diff(array1, array2, format = :text) string1 = array1.join("\n") + "\n" string2 = array2.join("\n") + "\n" Diffy::Diff.new(string1, string2).to_s(format) end
ruby
def array_diff(array1, array2, format = :text) string1 = array1.join("\n") + "\n" string2 = array2.join("\n") + "\n" Diffy::Diff.new(string1, string2).to_s(format) end
[ "def", "array_diff", "(", "array1", ",", "array2", ",", "format", "=", ":text", ")", "string1", "=", "array1", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "string2", "=", "array2", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "Diffy", "::", "Diff", ".", "new", "(", "string1", ",", "string2", ")", ".", "to_s", "(", "format", ")", "end" ]
Shows a visual diff of 2 arrays by comparing the string representations of the arrays with one element per line. @param format can be any valid Diffy option, e.g. :color see https://github.com/samg/diffy/blob/master/lib/diffy/format.rb
[ "Shows", "a", "visual", "diff", "of", "2", "arrays", "by", "comparing", "the", "string", "representations", "of", "the", "arrays", "with", "one", "element", "per", "line", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/formatters/formatters.rb#L136-L140
train
cryptape/ruby-devp2p
lib/devp2p/crypto.rb
DEVp2p.Crypto.encrypt
def encrypt(data, raw_pubkey) raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64 Crypto::ECIES.encrypt data, raw_pubkey end
ruby
def encrypt(data, raw_pubkey) raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64 Crypto::ECIES.encrypt data, raw_pubkey end
[ "def", "encrypt", "(", "data", ",", "raw_pubkey", ")", "raise", "ArgumentError", ",", "\"invalid pubkey of length #{raw_pubkey.size}\"", "unless", "raw_pubkey", ".", "size", "==", "64", "Crypto", "::", "ECIES", ".", "encrypt", "data", ",", "raw_pubkey", "end" ]
Encrypt data with ECIES method using the public key of the recipient.
[ "Encrypt", "data", "with", "ECIES", "method", "using", "the", "public", "key", "of", "the", "recipient", "." ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/crypto.rb#L67-L70
train
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_eval_uri
def sf_eval_uri(uri, exts = []) doc = Nokogiri::HTML(open(uri).read) doc.encoding, meta = 'utf-8', { uri: uri } [:title, :description, :keywords, :lang, :encode, :reply_to, :author].each do |k| node = doc.xpath(sf_xpaths[k])[0] meta[k] = node.nil? ? '-' : node.text end meta[:images] = sf_fix_imgs(doc.xpath(sf_xpaths[:image]), uri, exts) meta rescue SocketError {} end
ruby
def sf_eval_uri(uri, exts = []) doc = Nokogiri::HTML(open(uri).read) doc.encoding, meta = 'utf-8', { uri: uri } [:title, :description, :keywords, :lang, :encode, :reply_to, :author].each do |k| node = doc.xpath(sf_xpaths[k])[0] meta[k] = node.nil? ? '-' : node.text end meta[:images] = sf_fix_imgs(doc.xpath(sf_xpaths[:image]), uri, exts) meta rescue SocketError {} end
[ "def", "sf_eval_uri", "(", "uri", ",", "exts", "=", "[", "]", ")", "doc", "=", "Nokogiri", "::", "HTML", "(", "open", "(", "uri", ")", ".", "read", ")", "doc", ".", "encoding", ",", "meta", "=", "'utf-8'", ",", "{", "uri", ":", "uri", "}", "[", ":title", ",", ":description", ",", ":keywords", ",", ":lang", ",", ":encode", ",", ":reply_to", ",", ":author", "]", ".", "each", "do", "|", "k", "|", "node", "=", "doc", ".", "xpath", "(", "sf_xpaths", "[", "k", "]", ")", "[", "0", "]", "meta", "[", "k", "]", "=", "node", ".", "nil?", "?", "'-'", ":", "node", ".", "text", "end", "meta", "[", ":images", "]", "=", "sf_fix_imgs", "(", "doc", ".", "xpath", "(", "sf_xpaths", "[", ":image", "]", ")", ",", "uri", ",", "exts", ")", "meta", "rescue", "SocketError", "{", "}", "end" ]
Evaluate the URI's HTML document and get its metadata. Example: >> eval_uri('http://adtangerine.com', [:png]) => { :title => "AdTangerine | Advertising Platform for Social Media", :description => "AdTangerine is an advertising platform that...", :images => [ "http://adtangerine.com/assets/logo_adt_og.png", "http://adtangerine.com/assets/logo_adt_og.png ], :uri => "http://adtangerine.com" } Arguments: uri: (String) - URI. exts: (Array) - Allowed type of images.
[ "Evaluate", "the", "URI", "s", "HTML", "document", "and", "get", "its", "metadata", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L27-L40
train
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_check_img_ext
def sf_check_img_ext(images, allowed = []) allowed ||= [] if images.is_a?(String) images = images.split elsif !images.is_a?(Array) images = [] end images.select { |i| i =~ sf_regex(:image, allowed) } end
ruby
def sf_check_img_ext(images, allowed = []) allowed ||= [] if images.is_a?(String) images = images.split elsif !images.is_a?(Array) images = [] end images.select { |i| i =~ sf_regex(:image, allowed) } end
[ "def", "sf_check_img_ext", "(", "images", ",", "allowed", "=", "[", "]", ")", "allowed", "||=", "[", "]", "if", "images", ".", "is_a?", "(", "String", ")", "images", "=", "images", ".", "split", "elsif", "!", "images", ".", "is_a?", "(", "Array", ")", "images", "=", "[", "]", "end", "images", ".", "select", "{", "|", "i", "|", "i", "=~", "sf_regex", "(", ":image", ",", "allowed", ")", "}", "end" ]
Filter images returning those with the allowed extentions. Example: >> sf_check_img_ext('http://source.com/image.gif', :jpg) => [] >> sf_check_img_ext( ['http://source.com/image.gif','http://source.com/image.jpg'], [:jpg, :png] ) => ['http://source.com/image.jpg'] Arguments: images: (String or Array) - Images which will be checked. allowed: (String, Symbol or Array) - Allowed types of image extension.
[ "Filter", "images", "returning", "those", "with", "the", "allowed", "extentions", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L57-L65
train
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_regex
def sf_regex(type, *args) type = type.to_sym unless type.is_a? Symbol type == :image && sf_img_regex(args.flatten) || sf_uri_regex[type] end
ruby
def sf_regex(type, *args) type = type.to_sym unless type.is_a? Symbol type == :image && sf_img_regex(args.flatten) || sf_uri_regex[type] end
[ "def", "sf_regex", "(", "type", ",", "*", "args", ")", "type", "=", "type", ".", "to_sym", "unless", "type", ".", "is_a?", "Symbol", "type", "==", ":image", "&&", "sf_img_regex", "(", "args", ".", "flatten", ")", "||", "sf_uri_regex", "[", "type", "]", "end" ]
Select regexes for URIs, protocols and image extensions. Example: >> sf_regex(:uri) => /\b((((ht|f)tp[s]?:\/\/).../i, >> sf_regex(:image, :jpg) => /(^http{1}[s]?:\/\/([w]{3}\.)?.+\.(jpg)(\?.+)?$)/i Arguments: type: (Symbol or String) - Regex type: :uri, :protocol, :image args: (*) - Anything.
[ "Select", "regexes", "for", "URIs", "protocols", "and", "image", "extensions", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L79-L82
train
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_xpaths
def sf_xpaths { title: XPath::TITLE, description: XPath::DESC, keywords: XPath::KEYWORDS, lang: XPath::LANG, encode: XPath::ENCODE, reply_to: XPath::REPLY_TO, author: XPath::AUTHOR, image: XPath::IMG } end
ruby
def sf_xpaths { title: XPath::TITLE, description: XPath::DESC, keywords: XPath::KEYWORDS, lang: XPath::LANG, encode: XPath::ENCODE, reply_to: XPath::REPLY_TO, author: XPath::AUTHOR, image: XPath::IMG } end
[ "def", "sf_xpaths", "{", "title", ":", "XPath", "::", "TITLE", ",", "description", ":", "XPath", "::", "DESC", ",", "keywords", ":", "XPath", "::", "KEYWORDS", ",", "lang", ":", "XPath", "::", "LANG", ",", "encode", ":", "XPath", "::", "ENCODE", ",", "reply_to", ":", "XPath", "::", "REPLY_TO", ",", "author", ":", "XPath", "::", "AUTHOR", ",", "image", ":", "XPath", "::", "IMG", "}", "end" ]
Organize XPaths.
[ "Organize", "XPaths", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L118-L127
train
tiagopog/scrapifier
lib/scrapifier/support.rb
Scrapifier.Support.sf_fix_imgs
def sf_fix_imgs(imgs, uri, exts = []) sf_check_img_ext(imgs.map do |img| img = img.to_s unless img =~ sf_regex(:protocol) img = sf_fix_protocol(img, sf_domain(uri)) end img if img =~ sf_regex(:image) end.compact, exts) end
ruby
def sf_fix_imgs(imgs, uri, exts = []) sf_check_img_ext(imgs.map do |img| img = img.to_s unless img =~ sf_regex(:protocol) img = sf_fix_protocol(img, sf_domain(uri)) end img if img =~ sf_regex(:image) end.compact, exts) end
[ "def", "sf_fix_imgs", "(", "imgs", ",", "uri", ",", "exts", "=", "[", "]", ")", "sf_check_img_ext", "(", "imgs", ".", "map", "do", "|", "img", "|", "img", "=", "img", ".", "to_s", "unless", "img", "=~", "sf_regex", "(", ":protocol", ")", "img", "=", "sf_fix_protocol", "(", "img", ",", "sf_domain", "(", "uri", ")", ")", "end", "img", "if", "img", "=~", "sf_regex", "(", ":image", ")", "end", ".", "compact", ",", "exts", ")", "end" ]
Check and return only the valid image URIs. Example: >> sf_fix_imgs( ['http://adtangerine.com/image.png', '/assets/image.jpg'], 'http://adtangerine.com', :jpg ) => ['http://adtangerine/assets/image.jpg'] Arguments: imgs: (Array) - Image URIs got from the HTML doc. uri: (String) - Used as basis to the URIs that don't have any protocol/domain set. exts: (Symbol or Array) - Allowed image extesntions.
[ "Check", "and", "return", "only", "the", "valid", "image", "URIs", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/support.rb#L145-L153
train
solutious/rudy
lib/rudy/huxtable.rb
Rudy.Huxtable.known_machine_group?
def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config.machines return false if !@@config && !@@global zon, env, rol = @@global.zone, @@global.environment, @@global.role conf = @@config.machines.find_deferred(@@global.region, zon, [env, rol]) conf ||= @@config.machines.find_deferred(zon, [env, rol]) !conf.nil? end
ruby
def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config.machines return false if !@@config && !@@global zon, env, rol = @@global.zone, @@global.environment, @@global.role conf = @@config.machines.find_deferred(@@global.region, zon, [env, rol]) conf ||= @@config.machines.find_deferred(zon, [env, rol]) !conf.nil? end
[ "def", "known_machine_group?", "raise", "NoConfig", "unless", "@@config", "return", "true", "if", "default_machine_group?", "raise", "NoMachinesConfig", "unless", "@@config", ".", "machines", "return", "false", "if", "!", "@@config", "&&", "!", "@@global", "zon", ",", "env", ",", "rol", "=", "@@global", ".", "zone", ",", "@@global", ".", "environment", ",", "@@global", ".", "role", "conf", "=", "@@config", ".", "machines", ".", "find_deferred", "(", "@@global", ".", "region", ",", "zon", ",", "[", "env", ",", "rol", "]", ")", "conf", "||=", "@@config", ".", "machines", ".", "find_deferred", "(", "zon", ",", "[", "env", ",", "rol", "]", ")", "!", "conf", ".", "nil?", "end" ]
Looks for ENV-ROLE configuration in machines. There must be at least one definition in the config for this to return true That's how Rudy knows the current group is defined.
[ "Looks", "for", "ENV", "-", "ROLE", "configuration", "in", "machines", ".", "There", "must", "be", "at", "least", "one", "definition", "in", "the", "config", "for", "this", "to", "return", "true", "That", "s", "how", "Rudy", "knows", "the", "current", "group", "is", "defined", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/huxtable.rb#L246-L255
train
solutious/rudy
lib/rudy/huxtable.rb
Rudy.Huxtable.fetch_routine_config
def fetch_routine_config(action) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config.routines raise NoGlobal unless @@global action = action.to_s.tr('-:', '_') zon, env, rol = @@global.zone, @@global.environment, @@global.role disk_defs = fetch_machine_param(:disks) || {} # We want to find only one routines config with the name +action+. # This is unlike the routines config where it's okay to merge via # precedence. routine = @@config.routines.find_deferred(@@global.environment, @@global.role, action) routine ||= @@config.routines.find_deferred([@@global.environment, @@global.role], action) routine ||= @@config.routines.find_deferred(@@global.role, action) return nil unless routine return routine unless routine.has_key?(:disks) routine.disks.each_pair do |raction,disks| unless disks.kind_of?(Hash) li "#{raction} is not defined. Check your #{action} routines config.".color(:red) next end disks.each_pair do |path, props| unless disk_defs.has_key?(path) li "#{path} is not defined. Check your machines config.".color(:red) routine.disks[raction].delete(path) next end routine.disks[raction][path] = disk_defs[path].merge(props) end end routine end
ruby
def fetch_routine_config(action) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config.routines raise NoGlobal unless @@global action = action.to_s.tr('-:', '_') zon, env, rol = @@global.zone, @@global.environment, @@global.role disk_defs = fetch_machine_param(:disks) || {} # We want to find only one routines config with the name +action+. # This is unlike the routines config where it's okay to merge via # precedence. routine = @@config.routines.find_deferred(@@global.environment, @@global.role, action) routine ||= @@config.routines.find_deferred([@@global.environment, @@global.role], action) routine ||= @@config.routines.find_deferred(@@global.role, action) return nil unless routine return routine unless routine.has_key?(:disks) routine.disks.each_pair do |raction,disks| unless disks.kind_of?(Hash) li "#{raction} is not defined. Check your #{action} routines config.".color(:red) next end disks.each_pair do |path, props| unless disk_defs.has_key?(path) li "#{path} is not defined. Check your machines config.".color(:red) routine.disks[raction].delete(path) next end routine.disks[raction][path] = disk_defs[path].merge(props) end end routine end
[ "def", "fetch_routine_config", "(", "action", ")", "raise", "\"No action specified\"", "unless", "action", "raise", "NoConfig", "unless", "@@config", "raise", "NoRoutinesConfig", "unless", "@@config", ".", "routines", "raise", "NoGlobal", "unless", "@@global", "action", "=", "action", ".", "to_s", ".", "tr", "(", "'-:'", ",", "'_'", ")", "zon", ",", "env", ",", "rol", "=", "@@global", ".", "zone", ",", "@@global", ".", "environment", ",", "@@global", ".", "role", "disk_defs", "=", "fetch_machine_param", "(", ":disks", ")", "||", "{", "}", "routine", "=", "@@config", ".", "routines", ".", "find_deferred", "(", "@@global", ".", "environment", ",", "@@global", ".", "role", ",", "action", ")", "routine", "||=", "@@config", ".", "routines", ".", "find_deferred", "(", "[", "@@global", ".", "environment", ",", "@@global", ".", "role", "]", ",", "action", ")", "routine", "||=", "@@config", ".", "routines", ".", "find_deferred", "(", "@@global", ".", "role", ",", "action", ")", "return", "nil", "unless", "routine", "return", "routine", "unless", "routine", ".", "has_key?", "(", ":disks", ")", "routine", ".", "disks", ".", "each_pair", "do", "|", "raction", ",", "disks", "|", "unless", "disks", ".", "kind_of?", "(", "Hash", ")", "li", "\"#{raction} is not defined. Check your #{action} routines config.\"", ".", "color", "(", ":red", ")", "next", "end", "disks", ".", "each_pair", "do", "|", "path", ",", "props", "|", "unless", "disk_defs", ".", "has_key?", "(", "path", ")", "li", "\"#{path} is not defined. Check your machines config.\"", ".", "color", "(", ":red", ")", "routine", ".", "disks", "[", "raction", "]", ".", "delete", "(", "path", ")", "next", "end", "routine", ".", "disks", "[", "raction", "]", "[", "path", "]", "=", "disk_defs", "[", "path", "]", ".", "merge", "(", "props", ")", "end", "end", "routine", "end" ]
We grab the appropriate routines config and check the paths against those defined for the matching machine group. Disks that appear in a routine but not in a machine will be removed and a warning printed. Otherwise, the routines config is merged on top of the machine config and that's what we return. This means that all the disk info is returned so we know what size they are and stuff. Return a hash: :after: - :root: !ruby/object:Proc {} - :rudy: !ruby/object:Proc {} :disks: :create: /rudy/example1: :device: /dev/sdr :size: 2 /rudy/example2: :device: /dev/sdm :size: 1 NOTE: dashes in +action+ are converted to underscores. We do this because routine names are defined by method names and valid method names don't use dashes. This way, we can use a dash on the command-line which looks nicer (underscore still works of course).
[ "We", "grab", "the", "appropriate", "routines", "config", "and", "check", "the", "paths", "against", "those", "defined", "for", "the", "matching", "machine", "group", ".", "Disks", "that", "appear", "in", "a", "routine", "but", "not", "in", "a", "machine", "will", "be", "removed", "and", "a", "warning", "printed", ".", "Otherwise", "the", "routines", "config", "is", "merged", "on", "top", "of", "the", "machine", "config", "and", "that", "s", "what", "we", "return", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/huxtable.rb#L286-L325
train
solutious/rudy
lib/rudy/huxtable.rb
Rudy.Huxtable.default_machine_group?
def default_machine_group? default_env = @@config.defaults.environment || Rudy::DEFAULT_ENVIRONMENT default_rol = @@config.defaults.role || Rudy::DEFAULT_ROLE @@global.environment == default_env && @@global.role == default_rol end
ruby
def default_machine_group? default_env = @@config.defaults.environment || Rudy::DEFAULT_ENVIRONMENT default_rol = @@config.defaults.role || Rudy::DEFAULT_ROLE @@global.environment == default_env && @@global.role == default_rol end
[ "def", "default_machine_group?", "default_env", "=", "@@config", ".", "defaults", ".", "environment", "||", "Rudy", "::", "DEFAULT_ENVIRONMENT", "default_rol", "=", "@@config", ".", "defaults", ".", "role", "||", "Rudy", "::", "DEFAULT_ROLE", "@@global", ".", "environment", "==", "default_env", "&&", "@@global", ".", "role", "==", "default_rol", "end" ]
Returns true if this is the default machine environment and role
[ "Returns", "true", "if", "this", "is", "the", "default", "machine", "environment", "and", "role" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/huxtable.rb#L352-L356
train
stereocat/expectacle
lib/expectacle/thrower_base_params.rb
Expectacle.ThrowerBase.check_embed_envvar
def check_embed_envvar(param) return unless param =~ /<%=\s*ENV\[[\'\"]?(.+)[\'\"]\]?\s*%>/ envvar_name = Regexp.last_match(1) if !ENV.key?(envvar_name) @logger.error "Variable name: #{envvar_name} is not found in ENV" elsif ENV[envvar_name] =~ /^\s*$/ @logger.warn "Env var: #{envvar_name} exists, but null string" end end
ruby
def check_embed_envvar(param) return unless param =~ /<%=\s*ENV\[[\'\"]?(.+)[\'\"]\]?\s*%>/ envvar_name = Regexp.last_match(1) if !ENV.key?(envvar_name) @logger.error "Variable name: #{envvar_name} is not found in ENV" elsif ENV[envvar_name] =~ /^\s*$/ @logger.warn "Env var: #{envvar_name} exists, but null string" end end
[ "def", "check_embed_envvar", "(", "param", ")", "return", "unless", "param", "=~", "/", "\\s", "\\[", "\\'", "\\\"", "\\'", "\\\"", "\\]", "\\s", "/", "envvar_name", "=", "Regexp", ".", "last_match", "(", "1", ")", "if", "!", "ENV", ".", "key?", "(", "envvar_name", ")", "@logger", ".", "error", "\"Variable name: #{envvar_name} is not found in ENV\"", "elsif", "ENV", "[", "envvar_name", "]", "=~", "/", "\\s", "/", "@logger", ".", "warn", "\"Env var: #{envvar_name} exists, but null string\"", "end", "end" ]
Error checking of environment variable to embed @param param [String] Embedding target command
[ "Error", "checking", "of", "environment", "variable", "to", "embed" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_params.rb#L86-L94
train
stereocat/expectacle
lib/expectacle/thrower_base_params.rb
Expectacle.ThrowerBase.embed_var
def embed_var(param) check_embed_envvar(param) erb = ERB.new(param) erb.result(binding) end
ruby
def embed_var(param) check_embed_envvar(param) erb = ERB.new(param) erb.result(binding) end
[ "def", "embed_var", "(", "param", ")", "check_embed_envvar", "(", "param", ")", "erb", "=", "ERB", ".", "new", "(", "param", ")", "erb", ".", "result", "(", "binding", ")", "end" ]
Embedding environment variable to parameter @param param [String] Embedding target command @return [String] Embedded command
[ "Embedding", "environment", "variable", "to", "parameter" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_params.rb#L99-L103
train
spox/actionpool
lib/actionpool/pool.rb
ActionPool.Pool.fill_pool
def fill_pool threads = [] if(@open) @lock.synchronize do required = min - size if(required > 0) required.times do thread = ActionPool::Thread.new(:pool => self, :respond_thread => @respond_to, :a_timeout => @action_timeout, :t_timeout => @thread_timeout, :logger => @logger, :autostart => false) @threads << thread threads << thread end end end end threads.each{|t|t.start} threads end
ruby
def fill_pool threads = [] if(@open) @lock.synchronize do required = min - size if(required > 0) required.times do thread = ActionPool::Thread.new(:pool => self, :respond_thread => @respond_to, :a_timeout => @action_timeout, :t_timeout => @thread_timeout, :logger => @logger, :autostart => false) @threads << thread threads << thread end end end end threads.each{|t|t.start} threads end
[ "def", "fill_pool", "threads", "=", "[", "]", "if", "(", "@open", ")", "@lock", ".", "synchronize", "do", "required", "=", "min", "-", "size", "if", "(", "required", ">", "0", ")", "required", ".", "times", "do", "thread", "=", "ActionPool", "::", "Thread", ".", "new", "(", ":pool", "=>", "self", ",", ":respond_thread", "=>", "@respond_to", ",", ":a_timeout", "=>", "@action_timeout", ",", ":t_timeout", "=>", "@thread_timeout", ",", ":logger", "=>", "@logger", ",", ":autostart", "=>", "false", ")", "@threads", "<<", "thread", "threads", "<<", "thread", "end", "end", "end", "end", "threads", ".", "each", "{", "|", "t", "|", "t", ".", "start", "}", "threads", "end" ]
Fills the pool with the minimum number of threads Returns array of created threads
[ "Fills", "the", "pool", "with", "the", "minimum", "number", "of", "threads", "Returns", "array", "of", "created", "threads" ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/pool.rb#L82-L100
train
spox/actionpool
lib/actionpool/pool.rb
ActionPool.Pool.flush
def flush mon = Splib::Monitor.new @threads.size.times{ queue{ mon.wait } } @queue.wait_empty sleep(0.01) mon.broadcast end
ruby
def flush mon = Splib::Monitor.new @threads.size.times{ queue{ mon.wait } } @queue.wait_empty sleep(0.01) mon.broadcast end
[ "def", "flush", "mon", "=", "Splib", "::", "Monitor", ".", "new", "@threads", ".", "size", ".", "times", "{", "queue", "{", "mon", ".", "wait", "}", "}", "@queue", ".", "wait_empty", "sleep", "(", "0.01", ")", "mon", ".", "broadcast", "end" ]
Flush the thread pool. Mainly used for forcibly resizing the pool if existing threads have a long thread life waiting for input.
[ "Flush", "the", "thread", "pool", ".", "Mainly", "used", "for", "forcibly", "resizing", "the", "pool", "if", "existing", "threads", "have", "a", "long", "thread", "life", "waiting", "for", "input", "." ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/pool.rb#L277-L283
train
spox/actionpool
lib/actionpool/pool.rb
ActionPool.Pool.resize
def resize @logger.info("Pool is being resized to stated maximum: #{max}") until(size <= max) do t = nil t = @threads.find{|x|x.waiting?} t = @threads.shift unless t t.stop end flush nil end
ruby
def resize @logger.info("Pool is being resized to stated maximum: #{max}") until(size <= max) do t = nil t = @threads.find{|x|x.waiting?} t = @threads.shift unless t t.stop end flush nil end
[ "def", "resize", "@logger", ".", "info", "(", "\"Pool is being resized to stated maximum: #{max}\"", ")", "until", "(", "size", "<=", "max", ")", "do", "t", "=", "nil", "t", "=", "@threads", ".", "find", "{", "|", "x", "|", "x", ".", "waiting?", "}", "t", "=", "@threads", ".", "shift", "unless", "t", "t", ".", "stop", "end", "flush", "nil", "end" ]
Resize the pool
[ "Resize", "the", "pool" ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/pool.rb#L302-L312
train
stereocat/expectacle
lib/expectacle/thrower_base.rb
Expectacle.ThrowerBase.open_interactive_process
def open_interactive_process(spawn_cmd) @logger.info "Begin spawn: #{spawn_cmd}" PTY.spawn(spawn_cmd) do |reader, writer, _pid| @enable_mode = false @reader = reader @writer = writer @writer.sync = true yield end end
ruby
def open_interactive_process(spawn_cmd) @logger.info "Begin spawn: #{spawn_cmd}" PTY.spawn(spawn_cmd) do |reader, writer, _pid| @enable_mode = false @reader = reader @writer = writer @writer.sync = true yield end end
[ "def", "open_interactive_process", "(", "spawn_cmd", ")", "@logger", ".", "info", "\"Begin spawn: #{spawn_cmd}\"", "PTY", ".", "spawn", "(", "spawn_cmd", ")", "do", "|", "reader", ",", "writer", ",", "_pid", "|", "@enable_mode", "=", "false", "@reader", "=", "reader", "@writer", "=", "writer", "@writer", ".", "sync", "=", "true", "yield", "end", "end" ]
Spawn interactive process @yield [] Operations for interactive process
[ "Spawn", "interactive", "process" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base.rb#L77-L86
train
stereocat/expectacle
lib/expectacle/thrower_base.rb
Expectacle.ThrowerBase.do_on_interactive_process
def do_on_interactive_process until @reader.closed? || @reader.eof? @reader.expect(expect_regexp, @timeout) do |match| yield match end end rescue Errno::EIO => error # on linux, PTY raises Errno::EIO when spawned process closed. @logger.debug "PTY raises Errno::EIO, #{error.message}" end
ruby
def do_on_interactive_process until @reader.closed? || @reader.eof? @reader.expect(expect_regexp, @timeout) do |match| yield match end end rescue Errno::EIO => error # on linux, PTY raises Errno::EIO when spawned process closed. @logger.debug "PTY raises Errno::EIO, #{error.message}" end
[ "def", "do_on_interactive_process", "until", "@reader", ".", "closed?", "||", "@reader", ".", "eof?", "@reader", ".", "expect", "(", "expect_regexp", ",", "@timeout", ")", "do", "|", "match", "|", "yield", "match", "end", "end", "rescue", "Errno", "::", "EIO", "=>", "error", "@logger", ".", "debug", "\"PTY raises Errno::EIO, #{error.message}\"", "end" ]
Search prompt and send command, while process is opened @yield [match] Send operations when found prompt @yieldparam match [String] Expect matches string (prompt)
[ "Search", "prompt", "and", "send", "command", "while", "process", "is", "opened" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base.rb#L108-L117
train
mileszim/webpurify-gem
lib/web_purify/methods/image_filters.rb
WebPurify.ImageFilters.imgcheck
def imgcheck(imgurl, options={}) params = { :method => WebPurify::Constants.methods[:imgcheck], :imgurl => imgurl } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:imgid] end
ruby
def imgcheck(imgurl, options={}) params = { :method => WebPurify::Constants.methods[:imgcheck], :imgurl => imgurl } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:imgid] end
[ "def", "imgcheck", "(", "imgurl", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":imgcheck", "]", ",", ":imgurl", "=>", "imgurl", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "image_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":imgid", "]", "end" ]
Check for existence of prohibited image content @param imgurl [String] URL of the image to be moderated @param options [Hash] Options hash, used to set additional parameters @return [String] Image ID that is used to return results to the callback function
[ "Check", "for", "existence", "of", "prohibited", "image", "content" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/image_filters.rb#L13-L20
train
mileszim/webpurify-gem
lib/web_purify/methods/image_filters.rb
WebPurify.ImageFilters.imgstatus
def imgstatus(imgid, options={}) params = { :method => WebPurify::Constants.methods[:imgstatus], :imgid => imgid } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:status] end
ruby
def imgstatus(imgid, options={}) params = { :method => WebPurify::Constants.methods[:imgstatus], :imgid => imgid } parsed = WebPurify::Request.query(image_request_base, @query_base, params.merge(options)) return parsed[:status] end
[ "def", "imgstatus", "(", "imgid", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":imgstatus", "]", ",", ":imgid", "=>", "imgid", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "image_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":status", "]", "end" ]
Return status of image moderation @param imgid [String] ID of the image being moderated @param options [Hash] Options hash, used to set additional parameters @return [String] Status of image moderation
[ "Return", "status", "of", "image", "moderation" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/image_filters.rb#L28-L35
train
mileszim/webpurify-gem
lib/web_purify/methods/image_filters.rb
WebPurify.ImageFilters.imgaccount
def imgaccount params = { :method => WebPurify::Constants.methods[:imgaccount] } parsed = WebPurify::Request.query(image_request_base, @query_base, params) return parsed[:remaining].to_i end
ruby
def imgaccount params = { :method => WebPurify::Constants.methods[:imgaccount] } parsed = WebPurify::Request.query(image_request_base, @query_base, params) return parsed[:remaining].to_i end
[ "def", "imgaccount", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":imgaccount", "]", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "image_request_base", ",", "@query_base", ",", "params", ")", "return", "parsed", "[", ":remaining", "]", ".", "to_i", "end" ]
Return number of image submissions remaining on license @return [Integer] Number of image submissions remaining
[ "Return", "number", "of", "image", "submissions", "remaining", "on", "license" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/image_filters.rb#L41-L47
train
cryptape/ruby-devp2p
lib/devp2p/utils.rb
DEVp2p.Utils.sxor
def sxor(s1, s2) raise ArgumentError, "strings must have equal size" unless s1.size == s2.size s1.bytes.zip(s2.bytes).map {|a, b| (a ^ b).chr }.join end
ruby
def sxor(s1, s2) raise ArgumentError, "strings must have equal size" unless s1.size == s2.size s1.bytes.zip(s2.bytes).map {|a, b| (a ^ b).chr }.join end
[ "def", "sxor", "(", "s1", ",", "s2", ")", "raise", "ArgumentError", ",", "\"strings must have equal size\"", "unless", "s1", ".", "size", "==", "s2", ".", "size", "s1", ".", "bytes", ".", "zip", "(", "s2", ".", "bytes", ")", ".", "map", "{", "|", "a", ",", "b", "|", "(", "a", "^", "b", ")", ".", "chr", "}", ".", "join", "end" ]
String xor.
[ "String", "xor", "." ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/utils.rb#L61-L65
train
stjernstrom/capistrano_colors
lib/capistrano_colors/configuration.rb
Capistrano.Configuration.colorize
def colorize(options) if options.class == Array options.each do |opt| Capistrano::Logger.add_color_matcher( opt ) end else Capistrano::Logger.add_color_matcher( options ) end end
ruby
def colorize(options) if options.class == Array options.each do |opt| Capistrano::Logger.add_color_matcher( opt ) end else Capistrano::Logger.add_color_matcher( options ) end end
[ "def", "colorize", "(", "options", ")", "if", "options", ".", "class", "==", "Array", "options", ".", "each", "do", "|", "opt", "|", "Capistrano", "::", "Logger", ".", "add_color_matcher", "(", "opt", ")", "end", "else", "Capistrano", "::", "Logger", ".", "add_color_matcher", "(", "options", ")", "end", "end" ]
Add custom colormatchers Passing a hash or a array of hashes with custom colormatchers. Add the following to your deploy.rb or in your ~/.caprc == Example: require 'capistrano_colors' capistrano_color_matchers = [ { :match => /command finished/, :color => :hide, :prio => 10, :prepend => "$$$" }, { :match => /executing command/, :color => :blue, :prio => 10, :attribute => :underscore, :timestamp => true }, { :match => /^transaction: commit$/, :color => :magenta, :prio => 10, :attribute => :blink }, { :match => /git/, :color => :white, :prio => 20, :attribute => :reverse }, ] colorize( capistrano_color_matchers ) You can call colorize multiple time with either a hash or an array of hashes multiple times. == Colors: :color can have the following values: * :hide (hides the row completely) * :none * :black * :red * :green * :yellow * :blue * :magenta * :cyan * :white == Attributes: :attribute can have the following values: * :bright * :dim * :underscore * :blink * :reverse * :hidden == Text alterations :prepend gives static text to be prepended to the output :replace replaces the matched text in the output :timestamp adds the current time before the output
[ "Add", "custom", "colormatchers" ]
7b44a2c6d504ccd3db29998e8245b918609f0b08
https://github.com/stjernstrom/capistrano_colors/blob/7b44a2c6d504ccd3db29998e8245b918609f0b08/lib/capistrano_colors/configuration.rb#L58-L68
train
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.start
def start *args return self if attached? or running? @pid = ::Process.spawn Nutcracker.executable, *command Process.detach(@pid) sleep 2 raise "Nutcracker failed to start" unless running? Kernel.at_exit { kill if running? } self end
ruby
def start *args return self if attached? or running? @pid = ::Process.spawn Nutcracker.executable, *command Process.detach(@pid) sleep 2 raise "Nutcracker failed to start" unless running? Kernel.at_exit { kill if running? } self end
[ "def", "start", "*", "args", "return", "self", "if", "attached?", "or", "running?", "@pid", "=", "::", "Process", ".", "spawn", "Nutcracker", ".", "executable", ",", "*", "command", "Process", ".", "detach", "(", "@pid", ")", "sleep", "2", "raise", "\"Nutcracker failed to start\"", "unless", "running?", "Kernel", ".", "at_exit", "{", "kill", "if", "running?", "}", "self", "end" ]
Initialize a new Nutcracker process wrappper @param [Hash] options @option options [String] :config_file (conf/nutcracker.yaml) path to nutcracker's configuration file @option options [String] :stats_uri Nutcracker stats URI - tcp://localhost:22222 @option options [String] :max_memory use fixed max memory size ( ignore server configuration ) @option options [Array] :args ([]) array with additional command line arguments launching the Nutcracker service
[ "Initialize", "a", "new", "Nutcracker", "process", "wrappper" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L51-L59
train
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.use
def use plugin, *args Nutcracker.const_get(plugin.to_s.capitalize).start(self,*args) end
ruby
def use plugin, *args Nutcracker.const_get(plugin.to_s.capitalize).start(self,*args) end
[ "def", "use", "plugin", ",", "*", "args", "Nutcracker", ".", "const_get", "(", "plugin", ".", "to_s", ".", "capitalize", ")", ".", "start", "(", "self", ",", "*", "args", ")", "end" ]
Syntactic sugar for initialize plugins
[ "Syntactic", "sugar", "for", "initialize", "plugins" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L92-L94
train
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.overview
def overview data = { :clusters => [], :config => config } stats.each do |cluster_name, cluster_data| # Setting global server attributes ( like hostname, version etc...) unless cluster_data.is_a? Hash data[cluster_name] = cluster_data next end #next unless redis? cluster_name # skip memcached clusters aliases = node_aliases cluster_name cluster = { nodes: [], name: cluster_name } cluster_data.each do |node, node_value| # Adding node if node_value.kind_of? Hash node_data = cluster_data[node] node = aliases[node] || node url = ( node =~ /redis\:\/\// ) ? node : "redis://#{node}" info = redis_info(url, config[cluster_name]["redis_auth"]) cluster[:nodes] << { server_url: url, info: info, running: info.any? }.merge(node_data) else # Cluster attribute cluster[node] = node_value end end data[:clusters].push cluster end data end
ruby
def overview data = { :clusters => [], :config => config } stats.each do |cluster_name, cluster_data| # Setting global server attributes ( like hostname, version etc...) unless cluster_data.is_a? Hash data[cluster_name] = cluster_data next end #next unless redis? cluster_name # skip memcached clusters aliases = node_aliases cluster_name cluster = { nodes: [], name: cluster_name } cluster_data.each do |node, node_value| # Adding node if node_value.kind_of? Hash node_data = cluster_data[node] node = aliases[node] || node url = ( node =~ /redis\:\/\// ) ? node : "redis://#{node}" info = redis_info(url, config[cluster_name]["redis_auth"]) cluster[:nodes] << { server_url: url, info: info, running: info.any? }.merge(node_data) else # Cluster attribute cluster[node] = node_value end end data[:clusters].push cluster end data end
[ "def", "overview", "data", "=", "{", ":clusters", "=>", "[", "]", ",", ":config", "=>", "config", "}", "stats", ".", "each", "do", "|", "cluster_name", ",", "cluster_data", "|", "unless", "cluster_data", ".", "is_a?", "Hash", "data", "[", "cluster_name", "]", "=", "cluster_data", "next", "end", "aliases", "=", "node_aliases", "cluster_name", "cluster", "=", "{", "nodes", ":", "[", "]", ",", "name", ":", "cluster_name", "}", "cluster_data", ".", "each", "do", "|", "node", ",", "node_value", "|", "if", "node_value", ".", "kind_of?", "Hash", "node_data", "=", "cluster_data", "[", "node", "]", "node", "=", "aliases", "[", "node", "]", "||", "node", "url", "=", "(", "node", "=~", "/", "\\:", "\\/", "\\/", "/", ")", "?", "node", ":", "\"redis://#{node}\"", "info", "=", "redis_info", "(", "url", ",", "config", "[", "cluster_name", "]", "[", "\"redis_auth\"", "]", ")", "cluster", "[", ":nodes", "]", "<<", "{", "server_url", ":", "url", ",", "info", ":", "info", ",", "running", ":", "info", ".", "any?", "}", ".", "merge", "(", "node_data", ")", "else", "cluster", "[", "node", "]", "=", "node_value", "end", "end", "data", "[", ":clusters", "]", ".", "push", "cluster", "end", "data", "end" ]
Returns hash with server and node statistics See example.json @ project root to get details about the structure
[ "Returns", "hash", "with", "server", "and", "node", "statistics", "See", "example", ".", "json" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L98-L129
train
kontera-technologies/nutcracker
lib/nutcracker.rb
Nutcracker.Wrapper.redis_info
def redis_info url, password begin r = Redis.new url: url, password: password info = r.info.merge 'dbsize' => r.dbsize rescue Exception => e STDERR.puts "[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - " + "#{url.inspect} (using password #{password.inspect}): #{e.message}\n#{e.backtrace.join("\n")}" return {} end begin info['maxmemory'] = @options.fetch(:max_memory) { r.config(:get, 'maxmemory')['maxmemory'] } rescue Exception info['maxmemory'] = info['used_memory_rss'] end r.quit { 'connections' => info['connected_clients'].to_i, 'used_memory' => info['used_memory'].to_f, 'used_memory_rss' => info['used_memory_rss'].to_f, 'fragmentation' => info['mem_fragmentation_ratio'].to_f, 'expired_keys' => info['expired_keys'].to_i, 'evicted_keys' => info['evicted_keys'].to_i, 'hits' => info['keyspace_hits'].to_i, 'misses' => info['keyspace_misses'].to_i, 'keys' => info['dbsize'].to_i, 'max_memory' => info['maxmemory'].to_i, 'hit_ratio' => 0 }.tap {|d| d['hit_ratio'] = d['hits'].to_f / (d['hits']+d['misses']).to_f if d['hits'] > 0 } end
ruby
def redis_info url, password begin r = Redis.new url: url, password: password info = r.info.merge 'dbsize' => r.dbsize rescue Exception => e STDERR.puts "[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - " + "#{url.inspect} (using password #{password.inspect}): #{e.message}\n#{e.backtrace.join("\n")}" return {} end begin info['maxmemory'] = @options.fetch(:max_memory) { r.config(:get, 'maxmemory')['maxmemory'] } rescue Exception info['maxmemory'] = info['used_memory_rss'] end r.quit { 'connections' => info['connected_clients'].to_i, 'used_memory' => info['used_memory'].to_f, 'used_memory_rss' => info['used_memory_rss'].to_f, 'fragmentation' => info['mem_fragmentation_ratio'].to_f, 'expired_keys' => info['expired_keys'].to_i, 'evicted_keys' => info['evicted_keys'].to_i, 'hits' => info['keyspace_hits'].to_i, 'misses' => info['keyspace_misses'].to_i, 'keys' => info['dbsize'].to_i, 'max_memory' => info['maxmemory'].to_i, 'hit_ratio' => 0 }.tap {|d| d['hit_ratio'] = d['hits'].to_f / (d['hits']+d['misses']).to_f if d['hits'] > 0 } end
[ "def", "redis_info", "url", ",", "password", "begin", "r", "=", "Redis", ".", "new", "url", ":", "url", ",", "password", ":", "password", "info", "=", "r", ".", "info", ".", "merge", "'dbsize'", "=>", "r", ".", "dbsize", "rescue", "Exception", "=>", "e", "STDERR", ".", "puts", "\"[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - \"", "+", "\"#{url.inspect} (using password #{password.inspect}): #{e.message}\\n#{e.backtrace.join(\"\\n\")}\"", "return", "{", "}", "end", "begin", "info", "[", "'maxmemory'", "]", "=", "@options", ".", "fetch", "(", ":max_memory", ")", "{", "r", ".", "config", "(", ":get", ",", "'maxmemory'", ")", "[", "'maxmemory'", "]", "}", "rescue", "Exception", "info", "[", "'maxmemory'", "]", "=", "info", "[", "'used_memory_rss'", "]", "end", "r", ".", "quit", "{", "'connections'", "=>", "info", "[", "'connected_clients'", "]", ".", "to_i", ",", "'used_memory'", "=>", "info", "[", "'used_memory'", "]", ".", "to_f", ",", "'used_memory_rss'", "=>", "info", "[", "'used_memory_rss'", "]", ".", "to_f", ",", "'fragmentation'", "=>", "info", "[", "'mem_fragmentation_ratio'", "]", ".", "to_f", ",", "'expired_keys'", "=>", "info", "[", "'expired_keys'", "]", ".", "to_i", ",", "'evicted_keys'", "=>", "info", "[", "'evicted_keys'", "]", ".", "to_i", ",", "'hits'", "=>", "info", "[", "'keyspace_hits'", "]", ".", "to_i", ",", "'misses'", "=>", "info", "[", "'keyspace_misses'", "]", ".", "to_i", ",", "'keys'", "=>", "info", "[", "'dbsize'", "]", ".", "to_i", ",", "'max_memory'", "=>", "info", "[", "'maxmemory'", "]", ".", "to_i", ",", "'hit_ratio'", "=>", "0", "}", ".", "tap", "{", "|", "d", "|", "d", "[", "'hit_ratio'", "]", "=", "d", "[", "'hits'", "]", ".", "to_f", "/", "(", "d", "[", "'hits'", "]", "+", "d", "[", "'misses'", "]", ")", ".", "to_f", "if", "d", "[", "'hits'", "]", ">", "0", "}", "end" ]
Returns hash with information about a given Redis
[ "Returns", "hash", "with", "information", "about", "a", "given", "Redis" ]
c02ccd38b5a2a105b4874af7bef5c5f95526bbad
https://github.com/kontera-technologies/nutcracker/blob/c02ccd38b5a2a105b4874af7bef5c5f95526bbad/lib/nutcracker.rb#L142-L173
train
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.check
def check(text, options={}) params = { :method => WebPurify::Constants.methods[:check], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found]=='1' end
ruby
def check(text, options={}) params = { :method => WebPurify::Constants.methods[:check], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found]=='1' end
[ "def", "check", "(", "text", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":check", "]", ",", ":text", "=>", "text", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":found", "]", "==", "'1'", "end" ]
Check for existence of profanity @param text [String] Text to test for profanity @param options [Hash] Options hash, used to set additional parameters @return [Boolean] True if text contains profanity, false if not
[ "Check", "for", "existence", "of", "profanity" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L13-L20
train
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.check_count
def check_count(text, options={}) params = { :method => WebPurify::Constants.methods[:check_count], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found].to_i end
ruby
def check_count(text, options={}) params = { :method => WebPurify::Constants.methods[:check_count], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:found].to_i end
[ "def", "check_count", "(", "text", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":check_count", "]", ",", ":text", "=>", "text", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":found", "]", ".", "to_i", "end" ]
Check for existence of profanity and return number of profane words found @param text [String] Text to test for profanity @param options [Hash] Options hash, used to set additional parameters @return [Integer] The number of profane words found in text
[ "Check", "for", "existence", "of", "profanity", "and", "return", "number", "of", "profane", "words", "found" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L28-L35
train
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.replace
def replace(text, symbol, options={}) params = { :method => WebPurify::Constants.methods[:replace], :text => text, :replacesymbol => symbol } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:text] end
ruby
def replace(text, symbol, options={}) params = { :method => WebPurify::Constants.methods[:replace], :text => text, :replacesymbol => symbol } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) return parsed[:text] end
[ "def", "replace", "(", "text", ",", "symbol", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":replace", "]", ",", ":text", "=>", "text", ",", ":replacesymbol", "=>", "symbol", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "return", "parsed", "[", ":text", "]", "end" ]
Replace any matched profanity with provided symbol @param text [String] Text to test for profanity @param symbol [String] The symbol to replace each character of matched profanity @param options [Hash] Options hash, used to set additional parameters @return [String] The original text, replaced with the provided symbol
[ "Replace", "any", "matched", "profanity", "with", "provided", "symbol" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L44-L52
train
mileszim/webpurify-gem
lib/web_purify/methods/text_filters.rb
WebPurify.TextFilters.return
def return(text, options={}) params = { :method => WebPurify::Constants.methods[:return], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) if parsed[:expletive].is_a?(String) return [] << parsed[:expletive] else return parsed.fetch(:expletive, []) end end
ruby
def return(text, options={}) params = { :method => WebPurify::Constants.methods[:return], :text => text } parsed = WebPurify::Request.query(text_request_base, @query_base, params.merge(options)) if parsed[:expletive].is_a?(String) return [] << parsed[:expletive] else return parsed.fetch(:expletive, []) end end
[ "def", "return", "(", "text", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":return", "]", ",", ":text", "=>", "text", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ".", "merge", "(", "options", ")", ")", "if", "parsed", "[", ":expletive", "]", ".", "is_a?", "(", "String", ")", "return", "[", "]", "<<", "parsed", "[", ":expletive", "]", "else", "return", "parsed", ".", "fetch", "(", ":expletive", ",", "[", "]", ")", "end", "end" ]
Return an array of matched profanity @param text [String] Text to test for profanity @param options [Hash] Options hash, used to set additional parameters @return [Array] The array of matched profane words
[ "Return", "an", "array", "of", "matched", "profanity" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/text_filters.rb#L60-L71
train
solutious/rudy
lib/rudy/aws/ec2/group.rb
Rudy::AWS.EC2::Group.to_s
def to_s(with_title=false) lines = [liner_note] (self.addresses || {}).each_pair do |address,rules| lines << "%18s -> %s" % [address.to_s, rules.collect { |p| p.to_s}.join(', ')] end lines.join($/) end
ruby
def to_s(with_title=false) lines = [liner_note] (self.addresses || {}).each_pair do |address,rules| lines << "%18s -> %s" % [address.to_s, rules.collect { |p| p.to_s}.join(', ')] end lines.join($/) end
[ "def", "to_s", "(", "with_title", "=", "false", ")", "lines", "=", "[", "liner_note", "]", "(", "self", ".", "addresses", "||", "{", "}", ")", ".", "each_pair", "do", "|", "address", ",", "rules", "|", "lines", "<<", "\"%18s -> %s\"", "%", "[", "address", ".", "to_s", ",", "rules", ".", "collect", "{", "|", "p", "|", "p", ".", "to_s", "}", ".", "join", "(", "', '", ")", "]", "end", "lines", ".", "join", "(", "$/", ")", "end" ]
Print info about a security group * +group+ is a Rudy::AWS::EC2::Group object
[ "Print", "info", "about", "a", "security", "group" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/aws/ec2/group.rb#L37-L43
train
spox/actionpool
lib/actionpool/thread.rb
ActionPool.Thread.start_thread
def start_thread begin @logger.info("New pool thread is starting (#{self})") until(@kill) do begin @action = nil if(@pool.size > @pool.min && !@thread_timeout.zero?) Timeout::timeout(@thread_timeout) do @action = @pool.action end else @action = @pool.action end run(@action[0], @action[1]) unless @action.nil? rescue Timeout::Error @kill = true rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom end end rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') retry rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom ensure @logger.info("Pool thread is shutting down (#{self})") @pool.remove(self) end end
ruby
def start_thread begin @logger.info("New pool thread is starting (#{self})") until(@kill) do begin @action = nil if(@pool.size > @pool.min && !@thread_timeout.zero?) Timeout::timeout(@thread_timeout) do @action = @pool.action end else @action = @pool.action end run(@action[0], @action[1]) unless @action.nil? rescue Timeout::Error @kill = true rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom end end rescue Retimeout @logger.warn('Thread was woken up to reset thread timeout') retry rescue Wakeup @logger.info("Thread #{::Thread.current} was woken up.") rescue Exception => boom @logger.error("Pool thread caught an exception: #{boom}\n#{boom.backtrace.join("\n")}") @respond_to.raise boom ensure @logger.info("Pool thread is shutting down (#{self})") @pool.remove(self) end end
[ "def", "start_thread", "begin", "@logger", ".", "info", "(", "\"New pool thread is starting (#{self})\"", ")", "until", "(", "@kill", ")", "do", "begin", "@action", "=", "nil", "if", "(", "@pool", ".", "size", ">", "@pool", ".", "min", "&&", "!", "@thread_timeout", ".", "zero?", ")", "Timeout", "::", "timeout", "(", "@thread_timeout", ")", "do", "@action", "=", "@pool", ".", "action", "end", "else", "@action", "=", "@pool", ".", "action", "end", "run", "(", "@action", "[", "0", "]", ",", "@action", "[", "1", "]", ")", "unless", "@action", ".", "nil?", "rescue", "Timeout", "::", "Error", "@kill", "=", "true", "rescue", "Wakeup", "@logger", ".", "info", "(", "\"Thread #{::Thread.current} was woken up.\"", ")", "rescue", "Retimeout", "@logger", ".", "warn", "(", "'Thread was woken up to reset thread timeout'", ")", "rescue", "Exception", "=>", "boom", "@logger", ".", "error", "(", "\"Pool thread caught an exception: #{boom}\\n#{boom.backtrace.join(\"\\n\")}\"", ")", "@respond_to", ".", "raise", "boom", "end", "end", "rescue", "Retimeout", "@logger", ".", "warn", "(", "'Thread was woken up to reset thread timeout'", ")", "retry", "rescue", "Wakeup", "@logger", ".", "info", "(", "\"Thread #{::Thread.current} was woken up.\"", ")", "rescue", "Exception", "=>", "boom", "@logger", ".", "error", "(", "\"Pool thread caught an exception: #{boom}\\n#{boom.backtrace.join(\"\\n\")}\"", ")", "@respond_to", ".", "raise", "boom", "ensure", "@logger", ".", "info", "(", "\"Pool thread is shutting down (#{self})\"", ")", "@pool", ".", "remove", "(", "self", ")", "end", "end" ]
Start our thread
[ "Start", "our", "thread" ]
e7f1398d5ffa32654af5b0321771330ce85e2182
https://github.com/spox/actionpool/blob/e7f1398d5ffa32654af5b0321771330ce85e2182/lib/actionpool/thread.rb#L120-L157
train
dkd/paymill-ruby
lib/paymill/subscription.rb
Paymill.Subscription.parse_timestamps
def parse_timestamps super @next_capture_at = Time.at(next_capture_at) if next_capture_at @canceled_at = Time.at(canceled_at) if canceled_at @trial_start = Time.at(trial_start) if trial_start @trial_end = Time.at(trial_end) if trial_end end
ruby
def parse_timestamps super @next_capture_at = Time.at(next_capture_at) if next_capture_at @canceled_at = Time.at(canceled_at) if canceled_at @trial_start = Time.at(trial_start) if trial_start @trial_end = Time.at(trial_end) if trial_end end
[ "def", "parse_timestamps", "super", "@next_capture_at", "=", "Time", ".", "at", "(", "next_capture_at", ")", "if", "next_capture_at", "@canceled_at", "=", "Time", ".", "at", "(", "canceled_at", ")", "if", "canceled_at", "@trial_start", "=", "Time", ".", "at", "(", "trial_start", ")", "if", "trial_start", "@trial_end", "=", "Time", ".", "at", "(", "trial_end", ")", "if", "trial_end", "end" ]
Parses UNIX timestamps and creates Time objects
[ "Parses", "UNIX", "timestamps", "and", "creates", "Time", "objects" ]
4dd177faf1e5c08dae0c66fe493ccce535c9c97d
https://github.com/dkd/paymill-ruby/blob/4dd177faf1e5c08dae0c66fe493ccce535c9c97d/lib/paymill/subscription.rb#L10-L16
train
tobiasfeistmantl/LeSSL
lib/le_ssl/dns.rb
LeSSL.DNS.challenge_record_valid?
def challenge_record_valid?(domain, key) record = challenge_record(domain) return record && record.data == key end
ruby
def challenge_record_valid?(domain, key) record = challenge_record(domain) return record && record.data == key end
[ "def", "challenge_record_valid?", "(", "domain", ",", "key", ")", "record", "=", "challenge_record", "(", "domain", ")", "return", "record", "&&", "record", ".", "data", "==", "key", "end" ]
Checks if the TXT record for a domain is valid.
[ "Checks", "if", "the", "TXT", "record", "for", "a", "domain", "is", "valid", "." ]
7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba
https://github.com/tobiasfeistmantl/LeSSL/blob/7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba/lib/le_ssl/dns.rb#L9-L12
train
nofxx/yamg
lib/yamg/splash.rb
YAMG.Splash.splash_composite
def splash_composite max = size.min / 9 assets.each do |over| other = MiniMagick::Image.open(File.join(src, over)) other.resize(max) if other.dimensions.max >= max self.img = compose(other, over) end end
ruby
def splash_composite max = size.min / 9 assets.each do |over| other = MiniMagick::Image.open(File.join(src, over)) other.resize(max) if other.dimensions.max >= max self.img = compose(other, over) end end
[ "def", "splash_composite", "max", "=", "size", ".", "min", "/", "9", "assets", ".", "each", "do", "|", "over", "|", "other", "=", "MiniMagick", "::", "Image", ".", "open", "(", "File", ".", "join", "(", "src", ",", "over", ")", ")", "other", ".", "resize", "(", "max", ")", "if", "other", ".", "dimensions", ".", "max", ">=", "max", "self", ".", "img", "=", "compose", "(", "other", ",", "over", ")", "end", "end" ]
Composite 9 gravity
[ "Composite", "9", "gravity" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/splash.rb#L60-L67
train
nofxx/yamg
lib/yamg/splash.rb
YAMG.Splash.image
def image(out = nil) splash_start splash_composite return img unless out FileUtils.mkdir_p File.dirname(out) img.write(out) rescue Errno::ENOENT YAMG.puts_and_exit("Path not found '#{out}'") end
ruby
def image(out = nil) splash_start splash_composite return img unless out FileUtils.mkdir_p File.dirname(out) img.write(out) rescue Errno::ENOENT YAMG.puts_and_exit("Path not found '#{out}'") end
[ "def", "image", "(", "out", "=", "nil", ")", "splash_start", "splash_composite", "return", "img", "unless", "out", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "out", ")", "img", ".", "write", "(", "out", ")", "rescue", "Errno", "::", "ENOENT", "YAMG", ".", "puts_and_exit", "(", "\"Path not found '#{out}'\"", ")", "end" ]
Outputs instance or writes image to disk
[ "Outputs", "instance", "or", "writes", "image", "to", "disk" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/splash.rb#L72-L80
train
tumblr/collins_client
lib/collins/client.rb
Collins.Client.manage_process
def manage_process name = nil name = @managed_process if name.nil? if name then begin Collins.const_get(name).new(self).run rescue Exception => e raise CollinsError.new(e.message) end else raise CollinsError.new("No managed process specified") end end
ruby
def manage_process name = nil name = @managed_process if name.nil? if name then begin Collins.const_get(name).new(self).run rescue Exception => e raise CollinsError.new(e.message) end else raise CollinsError.new("No managed process specified") end end
[ "def", "manage_process", "name", "=", "nil", "name", "=", "@managed_process", "if", "name", ".", "nil?", "if", "name", "then", "begin", "Collins", ".", "const_get", "(", "name", ")", ".", "new", "(", "self", ")", ".", "run", "rescue", "Exception", "=>", "e", "raise", "CollinsError", ".", "new", "(", "e", ".", "message", ")", "end", "else", "raise", "CollinsError", ".", "new", "(", "\"No managed process specified\"", ")", "end", "end" ]
Create a collins client instance @param [Hash] options host, username and password are required @option options [String] :host a scheme, hostname and port (e.g. https://hostname) @option options [Logger] :logger a logger to use, one is created if none is specified @option options [Fixnum] :timeout (10) timeout in seconds to wait for a response @option options [String] :username username for authentication @option options [String] :password password for authentication @option options [String] :managed_process see {#manage_process} @option options [Boolean] :strict (false) see {#strict} Interact with a collins managed process @param [String] name Name of process @raise [CollinsError] if no managed process is specified/found @return [Collins::ManagedState::Mixin] see mixin for more information
[ "Create", "a", "collins", "client", "instance" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/client.rb#L64-L75
train
scottwillson/tabular
lib/tabular/row.rb
Tabular.Row.[]=
def []=(key, value) if columns.key?(key) @array[columns.index(key)] = value else @array << value columns << key end hash[key] = value end
ruby
def []=(key, value) if columns.key?(key) @array[columns.index(key)] = value else @array << value columns << key end hash[key] = value end
[ "def", "[]=", "(", "key", ",", "value", ")", "if", "columns", ".", "key?", "(", "key", ")", "@array", "[", "columns", ".", "index", "(", "key", ")", "]", "=", "value", "else", "@array", "<<", "value", "columns", "<<", "key", "end", "hash", "[", "key", "]", "=", "value", "end" ]
Set cell value. Adds cell to end of Row and adds new Column if there is no Column for +key_
[ "Set", "cell", "value", ".", "Adds", "cell", "to", "end", "of", "Row", "and", "adds", "new", "Column", "if", "there", "is", "no", "Column", "for", "+", "key_" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/row.rb#L42-L50
train
Dynamit/referee
lib/referee/codegenerator.rb
Referee.CodeGenerator.create_dictionary_representation
def create_dictionary_representation dict = { storyboards: [], table_cells: [], collection_cells: [], view_controllers: [], segues: [], prefix: @config.prefix } @project.resources.each do |group| dict[:storyboards] << group.storyboard dict[:table_cells] += group.table_cells dict[:collection_cells] += group.collection_cells dict[:view_controllers] += group.view_controllers dict[:segues] += group.segues end # Build up flags. dict[:has_table_cells] = (dict[:table_cells].count > 0) dict[:has_collection_cells] = (dict[:collection_cells].count > 0) dict[:has_segues] = (dict[:segues].count > 0) dict end
ruby
def create_dictionary_representation dict = { storyboards: [], table_cells: [], collection_cells: [], view_controllers: [], segues: [], prefix: @config.prefix } @project.resources.each do |group| dict[:storyboards] << group.storyboard dict[:table_cells] += group.table_cells dict[:collection_cells] += group.collection_cells dict[:view_controllers] += group.view_controllers dict[:segues] += group.segues end # Build up flags. dict[:has_table_cells] = (dict[:table_cells].count > 0) dict[:has_collection_cells] = (dict[:collection_cells].count > 0) dict[:has_segues] = (dict[:segues].count > 0) dict end
[ "def", "create_dictionary_representation", "dict", "=", "{", "storyboards", ":", "[", "]", ",", "table_cells", ":", "[", "]", ",", "collection_cells", ":", "[", "]", ",", "view_controllers", ":", "[", "]", ",", "segues", ":", "[", "]", ",", "prefix", ":", "@config", ".", "prefix", "}", "@project", ".", "resources", ".", "each", "do", "|", "group", "|", "dict", "[", ":storyboards", "]", "<<", "group", ".", "storyboard", "dict", "[", ":table_cells", "]", "+=", "group", ".", "table_cells", "dict", "[", ":collection_cells", "]", "+=", "group", ".", "collection_cells", "dict", "[", ":view_controllers", "]", "+=", "group", ".", "view_controllers", "dict", "[", ":segues", "]", "+=", "group", ".", "segues", "end", "dict", "[", ":has_table_cells", "]", "=", "(", "dict", "[", ":table_cells", "]", ".", "count", ">", "0", ")", "dict", "[", ":has_collection_cells", "]", "=", "(", "dict", "[", ":collection_cells", "]", ".", "count", ">", "0", ")", "dict", "[", ":has_segues", "]", "=", "(", "dict", "[", ":segues", "]", ".", "count", ">", "0", ")", "dict", "end" ]
Converts the resources into a Mustache-compatible template dictionary.
[ "Converts", "the", "resources", "into", "a", "Mustache", "-", "compatible", "template", "dictionary", "." ]
58189bf841d0195f7f2236262a649c67cfc92bf1
https://github.com/Dynamit/referee/blob/58189bf841d0195f7f2236262a649c67cfc92bf1/lib/referee/codegenerator.rb#L51-L73
train
nofxx/yamg
lib/yamg/screenshot.rb
YAMG.Screenshot.work
def work(path) out = "#{path}/#{@name}.png" @fetcher.fetch(output: out, width: @size[0], height: @size[1], dpi: @dpi) rescue Screencap::Error puts "Fail to capture screenshot #{@url}" end
ruby
def work(path) out = "#{path}/#{@name}.png" @fetcher.fetch(output: out, width: @size[0], height: @size[1], dpi: @dpi) rescue Screencap::Error puts "Fail to capture screenshot #{@url}" end
[ "def", "work", "(", "path", ")", "out", "=", "\"#{path}/#{@name}.png\"", "@fetcher", ".", "fetch", "(", "output", ":", "out", ",", "width", ":", "@size", "[", "0", "]", ",", "height", ":", "@size", "[", "1", "]", ",", "dpi", ":", "@dpi", ")", "rescue", "Screencap", "::", "Error", "puts", "\"Fail to capture screenshot #{@url}\"", "end" ]
Take the screenshot Do we need pixel depth??
[ "Take", "the", "screenshot", "Do", "we", "need", "pixel", "depth??" ]
0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4
https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/screenshot.rb#L27-L32
train
scottwillson/tabular
lib/tabular/columns.rb
Tabular.Columns.<<
def <<(key) column = Column.new(@table, self, key) return if is_blank?(column.key) || key?(key) @column_indexes[column.key] = @columns.size @column_indexes[@columns.size] = column @columns_by_key[column.key] = column @columns << column end
ruby
def <<(key) column = Column.new(@table, self, key) return if is_blank?(column.key) || key?(key) @column_indexes[column.key] = @columns.size @column_indexes[@columns.size] = column @columns_by_key[column.key] = column @columns << column end
[ "def", "<<", "(", "key", ")", "column", "=", "Column", ".", "new", "(", "@table", ",", "self", ",", "key", ")", "return", "if", "is_blank?", "(", "column", ".", "key", ")", "||", "key?", "(", "key", ")", "@column_indexes", "[", "column", ".", "key", "]", "=", "@columns", ".", "size", "@column_indexes", "[", "@columns", ".", "size", "]", "=", "column", "@columns_by_key", "[", "column", ".", "key", "]", "=", "column", "@columns", "<<", "column", "end" ]
Add a new Column with +key+
[ "Add", "a", "new", "Column", "with", "+", "key", "+" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/columns.rb#L77-L85
train
NoRedInk/elm_sprockets
lib/elm_sprockets/processor.rb
ElmSprockets.Processor.add_elm_dependencies
def add_elm_dependencies(filepath, context) # Turn e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStoreAPI.js.elm # into just ~/NoRedInk/app/assets/javascripts/ dirname = context.pathname.to_s.gsub Regexp.new(context.logical_path + ".+$"), "" File.read(filepath).each_line do |line| # e.g. `import Quiz.QuestionStore exposing (..)` match = line.match(/^import\s+([^\s]+)/) next unless match # e.g. Quiz.QuestionStore module_name = match.captures[0] # e.g. Quiz/QuestionStore dependency_logical_name = module_name.tr(".", "/") # e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStore.elm dependency_filepath = dirname + dependency_logical_name + ".elm" # If we don't find the dependency in our filesystem, assume it's because # it comes in through a third-party package rather than our sources. next unless File.file? dependency_filepath context.depend_on dependency_logical_name add_elm_dependencies dependency_filepath, context end end
ruby
def add_elm_dependencies(filepath, context) # Turn e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStoreAPI.js.elm # into just ~/NoRedInk/app/assets/javascripts/ dirname = context.pathname.to_s.gsub Regexp.new(context.logical_path + ".+$"), "" File.read(filepath).each_line do |line| # e.g. `import Quiz.QuestionStore exposing (..)` match = line.match(/^import\s+([^\s]+)/) next unless match # e.g. Quiz.QuestionStore module_name = match.captures[0] # e.g. Quiz/QuestionStore dependency_logical_name = module_name.tr(".", "/") # e.g. ~/NoRedInk/app/assets/javascripts/Quiz/QuestionStore.elm dependency_filepath = dirname + dependency_logical_name + ".elm" # If we don't find the dependency in our filesystem, assume it's because # it comes in through a third-party package rather than our sources. next unless File.file? dependency_filepath context.depend_on dependency_logical_name add_elm_dependencies dependency_filepath, context end end
[ "def", "add_elm_dependencies", "(", "filepath", ",", "context", ")", "dirname", "=", "context", ".", "pathname", ".", "to_s", ".", "gsub", "Regexp", ".", "new", "(", "context", ".", "logical_path", "+", "\".+$\"", ")", ",", "\"\"", "File", ".", "read", "(", "filepath", ")", ".", "each_line", "do", "|", "line", "|", "match", "=", "line", ".", "match", "(", "/", "\\s", "\\s", "/", ")", "next", "unless", "match", "module_name", "=", "match", ".", "captures", "[", "0", "]", "dependency_logical_name", "=", "module_name", ".", "tr", "(", "\".\"", ",", "\"/\"", ")", "dependency_filepath", "=", "dirname", "+", "dependency_logical_name", "+", "\".elm\"", "next", "unless", "File", ".", "file?", "dependency_filepath", "context", ".", "depend_on", "dependency_logical_name", "add_elm_dependencies", "dependency_filepath", ",", "context", "end", "end" ]
Add all Elm modules imported in the target file as dependencies, then recursively do the same for each of those dependent modules.
[ "Add", "all", "Elm", "modules", "imported", "in", "the", "target", "file", "as", "dependencies", "then", "recursively", "do", "the", "same", "for", "each", "of", "those", "dependent", "modules", "." ]
de697ff703d9904e48eee1a55202a8892eeefcc1
https://github.com/NoRedInk/elm_sprockets/blob/de697ff703d9904e48eee1a55202a8892eeefcc1/lib/elm_sprockets/processor.rb#L32-L59
train
tumblr/collins_client
lib/collins/api.rb
Collins.Api.trace
def trace(progname = nil, &block) if logger.respond_to?(:trace) then logger.trace(progname, &block) else logger.debug(progname, &block) end end
ruby
def trace(progname = nil, &block) if logger.respond_to?(:trace) then logger.trace(progname, &block) else logger.debug(progname, &block) end end
[ "def", "trace", "(", "progname", "=", "nil", ",", "&", "block", ")", "if", "logger", ".", "respond_to?", "(", ":trace", ")", "then", "logger", ".", "trace", "(", "progname", ",", "&", "block", ")", "else", "logger", ".", "debug", "(", "progname", ",", "&", "block", ")", "end", "end" ]
Provides a safe wrapper for our monkeypatched logger If the provided logger responds to a trace method, use that method. Otherwise fallback to using the debug method.
[ "Provides", "a", "safe", "wrapper", "for", "our", "monkeypatched", "logger" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/api.rb#L94-L100
train
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.surl
def surl(service) service_url = @env == :stable ? API_URL : SANDBOX_API_URL service_url = service_url + "/" + service service_url.gsub!('www', 'usercontent') if service.to_s == 'image' service_url end
ruby
def surl(service) service_url = @env == :stable ? API_URL : SANDBOX_API_URL service_url = service_url + "/" + service service_url.gsub!('www', 'usercontent') if service.to_s == 'image' service_url end
[ "def", "surl", "(", "service", ")", "service_url", "=", "@env", "==", ":stable", "?", "API_URL", ":", "SANDBOX_API_URL", "service_url", "=", "service_url", "+", "\"/\"", "+", "service", "service_url", ".", "gsub!", "(", "'www'", ",", "'usercontent'", ")", "if", "service", ".", "to_s", "==", "'image'", "service_url", "end" ]
Return the URL of a Freebase service @param [String] service the service @return [String] the url of the service
[ "Return", "the", "URL", "of", "a", "Freebase", "service" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L79-L84
train
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.get
def get(url, params={}, options={}) FreebaseAPI.logger.debug("GET #{url}") params[:key] = @key if @key options = { format: options[:format], query: params } options.merge!(@proxy_options) response = self.class.get(url, options) handle_response(response) end
ruby
def get(url, params={}, options={}) FreebaseAPI.logger.debug("GET #{url}") params[:key] = @key if @key options = { format: options[:format], query: params } options.merge!(@proxy_options) response = self.class.get(url, options) handle_response(response) end
[ "def", "get", "(", "url", ",", "params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "FreebaseAPI", ".", "logger", ".", "debug", "(", "\"GET #{url}\"", ")", "params", "[", ":key", "]", "=", "@key", "if", "@key", "options", "=", "{", "format", ":", "options", "[", ":format", "]", ",", "query", ":", "params", "}", "options", ".", "merge!", "(", "@proxy_options", ")", "response", "=", "self", ".", "class", ".", "get", "(", "url", ",", "options", ")", "handle_response", "(", "response", ")", "end" ]
Make a GET request @param [String] url the url to request @param [Hash] params the params of the request @return the request response
[ "Make", "a", "GET", "request" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L91-L98
train
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.handle_response
def handle_response(response) case response.code when 200..299 response else if response.request.format == :json raise FreebaseAPI::ServiceError.new(response['error']) else raise FreebaseAPI::NetError.new('code' => response.code, 'message' => response.response.message) end end end
ruby
def handle_response(response) case response.code when 200..299 response else if response.request.format == :json raise FreebaseAPI::ServiceError.new(response['error']) else raise FreebaseAPI::NetError.new('code' => response.code, 'message' => response.response.message) end end end
[ "def", "handle_response", "(", "response", ")", "case", "response", ".", "code", "when", "200", "..", "299", "response", "else", "if", "response", ".", "request", ".", "format", "==", ":json", "raise", "FreebaseAPI", "::", "ServiceError", ".", "new", "(", "response", "[", "'error'", "]", ")", "else", "raise", "FreebaseAPI", "::", "NetError", ".", "new", "(", "'code'", "=>", "response", ".", "code", ",", "'message'", "=>", "response", ".", "response", ".", "message", ")", "end", "end", "end" ]
Handle the response If success, return the response body If failure, raise an error
[ "Handle", "the", "response" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L104-L115
train
PerfectMemory/freebase-api
lib/freebase_api/session.rb
FreebaseAPI.Session.get_proxy_options
def get_proxy_options(url=nil) options = {} if url = url || ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy'] proxy_uri = URI.parse(url) options[:http_proxyaddr] = proxy_uri.host options[:http_proxyport] = proxy_uri.port options[:http_proxyuser] = proxy_uri.user options[:http_proxypass] = proxy_uri.password end options end
ruby
def get_proxy_options(url=nil) options = {} if url = url || ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy'] proxy_uri = URI.parse(url) options[:http_proxyaddr] = proxy_uri.host options[:http_proxyport] = proxy_uri.port options[:http_proxyuser] = proxy_uri.user options[:http_proxypass] = proxy_uri.password end options end
[ "def", "get_proxy_options", "(", "url", "=", "nil", ")", "options", "=", "{", "}", "if", "url", "=", "url", "||", "ENV", "[", "'HTTPS_PROXY'", "]", "||", "ENV", "[", "'https_proxy'", "]", "||", "ENV", "[", "'HTTP_PROXY'", "]", "||", "ENV", "[", "'http_proxy'", "]", "proxy_uri", "=", "URI", ".", "parse", "(", "url", ")", "options", "[", ":http_proxyaddr", "]", "=", "proxy_uri", ".", "host", "options", "[", ":http_proxyport", "]", "=", "proxy_uri", ".", "port", "options", "[", ":http_proxyuser", "]", "=", "proxy_uri", ".", "user", "options", "[", ":http_proxypass", "]", "=", "proxy_uri", ".", "password", "end", "options", "end" ]
Get the proxy options for HTTParty @return [Hash] the proxy options
[ "Get", "the", "proxy", "options", "for", "HTTParty" ]
fb9065cafce5a77d73a6c44de14bdcf4bca54be3
https://github.com/PerfectMemory/freebase-api/blob/fb9065cafce5a77d73a6c44de14bdcf4bca54be3/lib/freebase_api/session.rb#L120-L130
train
scottwillson/tabular
lib/tabular/column.rb
Tabular.Column.precision
def precision @precision ||= cells.map(&:to_f).map { |n| n.round(3) }.map { |n| n.to_s.split(".").last.gsub(/0+$/, "").length }.max end
ruby
def precision @precision ||= cells.map(&:to_f).map { |n| n.round(3) }.map { |n| n.to_s.split(".").last.gsub(/0+$/, "").length }.max end
[ "def", "precision", "@precision", "||=", "cells", ".", "map", "(", "&", ":to_f", ")", ".", "map", "{", "|", "n", "|", "n", ".", "round", "(", "3", ")", "}", ".", "map", "{", "|", "n", "|", "n", ".", "to_s", ".", "split", "(", "\".\"", ")", ".", "last", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "length", "}", ".", "max", "end" ]
Number of zeros to the right of the decimal point. Useful for formtting time data.
[ "Number", "of", "zeros", "to", "the", "right", "of", "the", "decimal", "point", ".", "Useful", "for", "formtting", "time", "data", "." ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/column.rb#L39-L41
train
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.apply_patch
def apply_patch(operations, node) i = 0 operations.sort_by {|operation| i += 1; [-operation.priority, i] }.each do |operation| case operation when ::Markdiff::Operations::AddChildOperation operation.target_node.add_child(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeHrefOperation operation.target_node["data-before-href"] = operation.target_node["href"] operation.target_node["href"] = operation.after_href mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeTagNameOperation operation.target_node["data-before-tag-name"] = operation.target_node.name operation.target_node.name = operation.after_tag_name mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddPreviousSiblingOperation operation.target_node.add_previous_sibling(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) if operation.target_node.name != "li" && operation.target_node.name != "tr" mark_top_level_node_as_changed(operation.target_node.parent) when ::Markdiff::Operations::RemoveOperation operation.target_node.replace(operation.inserted_node) if operation.target_node != operation.inserted_node mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::TextDiffOperation parent = operation.target_node.parent operation.target_node.replace(operation.inserted_node) mark_li_or_tr_as_changed(parent) mark_top_level_node_as_changed(parent) end end node end
ruby
def apply_patch(operations, node) i = 0 operations.sort_by {|operation| i += 1; [-operation.priority, i] }.each do |operation| case operation when ::Markdiff::Operations::AddChildOperation operation.target_node.add_child(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeHrefOperation operation.target_node["data-before-href"] = operation.target_node["href"] operation.target_node["href"] = operation.after_href mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddDataBeforeTagNameOperation operation.target_node["data-before-tag-name"] = operation.target_node.name operation.target_node.name = operation.after_tag_name mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::AddPreviousSiblingOperation operation.target_node.add_previous_sibling(operation.inserted_node) mark_li_or_tr_as_changed(operation.target_node) if operation.target_node.name != "li" && operation.target_node.name != "tr" mark_top_level_node_as_changed(operation.target_node.parent) when ::Markdiff::Operations::RemoveOperation operation.target_node.replace(operation.inserted_node) if operation.target_node != operation.inserted_node mark_li_or_tr_as_changed(operation.target_node) mark_top_level_node_as_changed(operation.target_node) when ::Markdiff::Operations::TextDiffOperation parent = operation.target_node.parent operation.target_node.replace(operation.inserted_node) mark_li_or_tr_as_changed(parent) mark_top_level_node_as_changed(parent) end end node end
[ "def", "apply_patch", "(", "operations", ",", "node", ")", "i", "=", "0", "operations", ".", "sort_by", "{", "|", "operation", "|", "i", "+=", "1", ";", "[", "-", "operation", ".", "priority", ",", "i", "]", "}", ".", "each", "do", "|", "operation", "|", "case", "operation", "when", "::", "Markdiff", "::", "Operations", "::", "AddChildOperation", "operation", ".", "target_node", ".", "add_child", "(", "operation", ".", "inserted_node", ")", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeHrefOperation", "operation", ".", "target_node", "[", "\"data-before-href\"", "]", "=", "operation", ".", "target_node", "[", "\"href\"", "]", "operation", ".", "target_node", "[", "\"href\"", "]", "=", "operation", ".", "after_href", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeTagNameOperation", "operation", ".", "target_node", "[", "\"data-before-tag-name\"", "]", "=", "operation", ".", "target_node", ".", "name", "operation", ".", "target_node", ".", "name", "=", "operation", ".", "after_tag_name", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "AddPreviousSiblingOperation", "operation", ".", "target_node", ".", "add_previous_sibling", "(", "operation", ".", "inserted_node", ")", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "if", "operation", ".", "target_node", ".", "name", "!=", "\"li\"", "&&", "operation", ".", "target_node", ".", "name", "!=", "\"tr\"", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ".", "parent", ")", "when", "::", "Markdiff", "::", "Operations", "::", "RemoveOperation", "operation", ".", "target_node", ".", "replace", "(", "operation", ".", "inserted_node", ")", "if", "operation", ".", "target_node", "!=", "operation", ".", "inserted_node", "mark_li_or_tr_as_changed", "(", "operation", ".", "target_node", ")", "mark_top_level_node_as_changed", "(", "operation", ".", "target_node", ")", "when", "::", "Markdiff", "::", "Operations", "::", "TextDiffOperation", "parent", "=", "operation", ".", "target_node", ".", "parent", "operation", ".", "target_node", ".", "replace", "(", "operation", ".", "inserted_node", ")", "mark_li_or_tr_as_changed", "(", "parent", ")", "mark_top_level_node_as_changed", "(", "parent", ")", "end", "end", "node", "end" ]
Apply a given patch to a given node @param [Array<Markdiff::Operations::Base>] operations @param [Nokogiri::XML::Node] node @return [Nokogiri::XML::Node] Converted node
[ "Apply", "a", "given", "patch", "to", "a", "given", "node" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L16-L50
train
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.create_patch
def create_patch(before_node, after_node) if before_node.to_html == after_node.to_html [] else create_patch_from_children(before_node, after_node) end end
ruby
def create_patch(before_node, after_node) if before_node.to_html == after_node.to_html [] else create_patch_from_children(before_node, after_node) end end
[ "def", "create_patch", "(", "before_node", ",", "after_node", ")", "if", "before_node", ".", "to_html", "==", "after_node", ".", "to_html", "[", "]", "else", "create_patch_from_children", "(", "before_node", ",", "after_node", ")", "end", "end" ]
Creates a patch from given two nodes @param [Nokogiri::XML::Node] before_node @param [Nokogiri::XML::Node] after_node @return [Array<Markdiff::Operations::Base>] operations
[ "Creates", "a", "patch", "from", "given", "two", "nodes" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L56-L62
train
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.render
def render(before_string, after_string) before_node = ::Nokogiri::HTML.fragment(before_string) after_node = ::Nokogiri::HTML.fragment(after_string) patch = create_patch(before_node, after_node) apply_patch(patch, before_node) end
ruby
def render(before_string, after_string) before_node = ::Nokogiri::HTML.fragment(before_string) after_node = ::Nokogiri::HTML.fragment(after_string) patch = create_patch(before_node, after_node) apply_patch(patch, before_node) end
[ "def", "render", "(", "before_string", ",", "after_string", ")", "before_node", "=", "::", "Nokogiri", "::", "HTML", ".", "fragment", "(", "before_string", ")", "after_node", "=", "::", "Nokogiri", "::", "HTML", ".", "fragment", "(", "after_string", ")", "patch", "=", "create_patch", "(", "before_node", ",", "after_node", ")", "apply_patch", "(", "patch", ",", "before_node", ")", "end" ]
Utility method to do both creating and applying a patch @param [String] before_string @param [String] after_string @return [Nokogiri::XML::Node] Converted node
[ "Utility", "method", "to", "do", "both", "creating", "and", "applying", "a", "patch" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L68-L73
train
r7kamura/markdiff
lib/markdiff/differ.rb
Markdiff.Differ.create_patch_from_children
def create_patch_from_children(before_node, after_node) operations = [] identity_map = {} inverted_identity_map = {} ::Diff::LCS.sdiff(before_node.children.map(&:to_s), after_node.children.map(&:to_s)).each do |element| type, before, after = *element if type == "=" before_child = before_node.children[before[0]] after_child = after_node.children[after[0]] identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end # Partial matching before_node.children.each do |before_child| if identity_map[before_child] next end after_node.children.each do |after_child| case when identity_map[before_child] break when inverted_identity_map[after_child] when before_child.text? if after_child.text? identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations << ::Markdiff::Operations::TextDiffOperation.new(target_node: before_child, after_node: after_child) end when before_child.name == after_child.name if before_child.attributes == after_child.attributes identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) elsif detect_href_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeHrefOperation.new(after_href: after_child["href"], target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) end when detect_heading_level_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeTagNameOperation.new(after_tag_name: after_child.name, target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end end before_node.children.each do |before_child| unless identity_map[before_child] operations << ::Markdiff::Operations::RemoveOperation.new(target_node: before_child) end end after_node.children.each do |after_child| unless inverted_identity_map[after_child] right_node = after_child.next_sibling loop do case when inverted_identity_map[right_node] operations << ::Markdiff::Operations::AddPreviousSiblingOperation.new(inserted_node: after_child, target_node: inverted_identity_map[right_node]) break when right_node.nil? operations << ::Markdiff::Operations::AddChildOperation.new(inserted_node: after_child, target_node: before_node) break else right_node = right_node.next_sibling end end end end operations end
ruby
def create_patch_from_children(before_node, after_node) operations = [] identity_map = {} inverted_identity_map = {} ::Diff::LCS.sdiff(before_node.children.map(&:to_s), after_node.children.map(&:to_s)).each do |element| type, before, after = *element if type == "=" before_child = before_node.children[before[0]] after_child = after_node.children[after[0]] identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end # Partial matching before_node.children.each do |before_child| if identity_map[before_child] next end after_node.children.each do |after_child| case when identity_map[before_child] break when inverted_identity_map[after_child] when before_child.text? if after_child.text? identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations << ::Markdiff::Operations::TextDiffOperation.new(target_node: before_child, after_node: after_child) end when before_child.name == after_child.name if before_child.attributes == after_child.attributes identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) elsif detect_href_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeHrefOperation.new(after_href: after_child["href"], target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child operations += create_patch(before_child, after_child) end when detect_heading_level_difference(before_child, after_child) operations << ::Markdiff::Operations::AddDataBeforeTagNameOperation.new(after_tag_name: after_child.name, target_node: before_child) identity_map[before_child] = after_child inverted_identity_map[after_child] = before_child end end end before_node.children.each do |before_child| unless identity_map[before_child] operations << ::Markdiff::Operations::RemoveOperation.new(target_node: before_child) end end after_node.children.each do |after_child| unless inverted_identity_map[after_child] right_node = after_child.next_sibling loop do case when inverted_identity_map[right_node] operations << ::Markdiff::Operations::AddPreviousSiblingOperation.new(inserted_node: after_child, target_node: inverted_identity_map[right_node]) break when right_node.nil? operations << ::Markdiff::Operations::AddChildOperation.new(inserted_node: after_child, target_node: before_node) break else right_node = right_node.next_sibling end end end end operations end
[ "def", "create_patch_from_children", "(", "before_node", ",", "after_node", ")", "operations", "=", "[", "]", "identity_map", "=", "{", "}", "inverted_identity_map", "=", "{", "}", "::", "Diff", "::", "LCS", ".", "sdiff", "(", "before_node", ".", "children", ".", "map", "(", "&", ":to_s", ")", ",", "after_node", ".", "children", ".", "map", "(", "&", ":to_s", ")", ")", ".", "each", "do", "|", "element", "|", "type", ",", "before", ",", "after", "=", "*", "element", "if", "type", "==", "\"=\"", "before_child", "=", "before_node", ".", "children", "[", "before", "[", "0", "]", "]", "after_child", "=", "after_node", ".", "children", "[", "after", "[", "0", "]", "]", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "end", "end", "before_node", ".", "children", ".", "each", "do", "|", "before_child", "|", "if", "identity_map", "[", "before_child", "]", "next", "end", "after_node", ".", "children", ".", "each", "do", "|", "after_child", "|", "case", "when", "identity_map", "[", "before_child", "]", "break", "when", "inverted_identity_map", "[", "after_child", "]", "when", "before_child", ".", "text?", "if", "after_child", ".", "text?", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "TextDiffOperation", ".", "new", "(", "target_node", ":", "before_child", ",", "after_node", ":", "after_child", ")", "end", "when", "before_child", ".", "name", "==", "after_child", ".", "name", "if", "before_child", ".", "attributes", "==", "after_child", ".", "attributes", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "operations", "+=", "create_patch", "(", "before_child", ",", "after_child", ")", "elsif", "detect_href_difference", "(", "before_child", ",", "after_child", ")", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeHrefOperation", ".", "new", "(", "after_href", ":", "after_child", "[", "\"href\"", "]", ",", "target_node", ":", "before_child", ")", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "operations", "+=", "create_patch", "(", "before_child", ",", "after_child", ")", "end", "when", "detect_heading_level_difference", "(", "before_child", ",", "after_child", ")", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddDataBeforeTagNameOperation", ".", "new", "(", "after_tag_name", ":", "after_child", ".", "name", ",", "target_node", ":", "before_child", ")", "identity_map", "[", "before_child", "]", "=", "after_child", "inverted_identity_map", "[", "after_child", "]", "=", "before_child", "end", "end", "end", "before_node", ".", "children", ".", "each", "do", "|", "before_child", "|", "unless", "identity_map", "[", "before_child", "]", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "RemoveOperation", ".", "new", "(", "target_node", ":", "before_child", ")", "end", "end", "after_node", ".", "children", ".", "each", "do", "|", "after_child", "|", "unless", "inverted_identity_map", "[", "after_child", "]", "right_node", "=", "after_child", ".", "next_sibling", "loop", "do", "case", "when", "inverted_identity_map", "[", "right_node", "]", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddPreviousSiblingOperation", ".", "new", "(", "inserted_node", ":", "after_child", ",", "target_node", ":", "inverted_identity_map", "[", "right_node", "]", ")", "break", "when", "right_node", ".", "nil?", "operations", "<<", "::", "Markdiff", "::", "Operations", "::", "AddChildOperation", ".", "new", "(", "inserted_node", ":", "after_child", ",", "target_node", ":", "before_node", ")", "break", "else", "right_node", "=", "right_node", ".", "next_sibling", "end", "end", "end", "end", "operations", "end" ]
1. Create identity map and collect patches from descendants 1-1. Detect exact-matched nodes 1-2. Detect partial-matched nodes and recursively walk through its children 2. Create remove operations from identity map 3. Create insert operations from identity map 4. Return operations as a patch @param [Nokogiri::XML::Node] before_node @param [Nokogiri::XML::Node] after_node @return [Array<Markdiff::Operations::Base>] operations
[ "1", ".", "Create", "identity", "map", "and", "collect", "patches", "from", "descendants", "1", "-", "1", ".", "Detect", "exact", "-", "matched", "nodes", "1", "-", "2", ".", "Detect", "partial", "-", "matched", "nodes", "and", "recursively", "walk", "through", "its", "children", "2", ".", "Create", "remove", "operations", "from", "identity", "map", "3", ".", "Create", "insert", "operations", "from", "identity", "map", "4", ".", "Return", "operations", "as", "a", "patch" ]
399fdff986771424186df65c8b25ed03b7b12305
https://github.com/r7kamura/markdiff/blob/399fdff986771424186df65c8b25ed03b7b12305/lib/markdiff/differ.rb#L87-L162
train
scottwillson/tabular
lib/tabular/table.rb
Tabular.Table.delete_blank_columns!
def delete_blank_columns!(*options) exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| if rows.all? { |row| is_blank?(row[key]) || is_zero?(row[key]) } # rubocop:disable Style/IfUnlessModifier delete_column key end end end
ruby
def delete_blank_columns!(*options) exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| if rows.all? { |row| is_blank?(row[key]) || is_zero?(row[key]) } # rubocop:disable Style/IfUnlessModifier delete_column key end end end
[ "def", "delete_blank_columns!", "(", "*", "options", ")", "exceptions", "=", "extract_exceptions", "(", "options", ")", "(", "columns", ".", "map", "(", "&", ":key", ")", "-", "exceptions", ")", ".", "each", "do", "|", "key", "|", "if", "rows", ".", "all?", "{", "|", "row", "|", "is_blank?", "(", "row", "[", "key", "]", ")", "||", "is_zero?", "(", "row", "[", "key", "]", ")", "}", "delete_column", "key", "end", "end", "end" ]
Remove all columns that only contain a blank string, zero, or nil
[ "Remove", "all", "columns", "that", "only", "contain", "a", "blank", "string", "zero", "or", "nil" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/table.rb#L78-L86
train
scottwillson/tabular
lib/tabular/table.rb
Tabular.Table.delete_homogenous_columns!
def delete_homogenous_columns!(*options) return if rows.size < 2 exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| value = rows.first[key] delete_column key if rows.all? { |row| row[key] == value } end end
ruby
def delete_homogenous_columns!(*options) return if rows.size < 2 exceptions = extract_exceptions(options) (columns.map(&:key) - exceptions).each do |key| value = rows.first[key] delete_column key if rows.all? { |row| row[key] == value } end end
[ "def", "delete_homogenous_columns!", "(", "*", "options", ")", "return", "if", "rows", ".", "size", "<", "2", "exceptions", "=", "extract_exceptions", "(", "options", ")", "(", "columns", ".", "map", "(", "&", ":key", ")", "-", "exceptions", ")", ".", "each", "do", "|", "key", "|", "value", "=", "rows", ".", "first", "[", "key", "]", "delete_column", "key", "if", "rows", ".", "all?", "{", "|", "row", "|", "row", "[", "key", "]", "==", "value", "}", "end", "end" ]
Remove all columns that contain the same value in all rows
[ "Remove", "all", "columns", "that", "contain", "the", "same", "value", "in", "all", "rows" ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/table.rb#L89-L98
train
scottwillson/tabular
lib/tabular/table.rb
Tabular.Table.strip!
def strip! rows.each do |row| columns.each do |column| value = row[column.key] if value.respond_to?(:strip) row[column.key] = value.strip elsif value.is_a?(Float) row[column.key] = strip_decimal(value) end end end end
ruby
def strip! rows.each do |row| columns.each do |column| value = row[column.key] if value.respond_to?(:strip) row[column.key] = value.strip elsif value.is_a?(Float) row[column.key] = strip_decimal(value) end end end end
[ "def", "strip!", "rows", ".", "each", "do", "|", "row", "|", "columns", ".", "each", "do", "|", "column", "|", "value", "=", "row", "[", "column", ".", "key", "]", "if", "value", ".", "respond_to?", "(", ":strip", ")", "row", "[", "column", ".", "key", "]", "=", "value", ".", "strip", "elsif", "value", ".", "is_a?", "(", "Float", ")", "row", "[", "column", ".", "key", "]", "=", "strip_decimal", "(", "value", ")", "end", "end", "end", "end" ]
Remove preceding and trailing whitespace from all cells. By default, Table does not strip whitespace from cells.
[ "Remove", "preceding", "and", "trailing", "whitespace", "from", "all", "cells", ".", "By", "default", "Table", "does", "not", "strip", "whitespace", "from", "cells", "." ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/table.rb#L109-L120
train
tumblr/collins_client
lib/collins/asset.rb
Collins.Asset.gateway_address
def gateway_address pool = "default" address = addresses.select{|a| a.pool == pool}.map{|a| a.gateway}.first return address if address if addresses.length > 0 then addresses.first.gateway else nil end end
ruby
def gateway_address pool = "default" address = addresses.select{|a| a.pool == pool}.map{|a| a.gateway}.first return address if address if addresses.length > 0 then addresses.first.gateway else nil end end
[ "def", "gateway_address", "pool", "=", "\"default\"", "address", "=", "addresses", ".", "select", "{", "|", "a", "|", "a", ".", "pool", "==", "pool", "}", ".", "map", "{", "|", "a", "|", "a", ".", "gateway", "}", ".", "first", "return", "address", "if", "address", "if", "addresses", ".", "length", ">", "0", "then", "addresses", ".", "first", ".", "gateway", "else", "nil", "end", "end" ]
Return the gateway address for the specified pool, or the first gateway @note If there is no address in the specified pool, the gateway of the first usable address is used, which may not be desired. @param [String] pool The address pool to find a gateway on @return [String] Gateway address, or nil
[ "Return", "the", "gateway", "address", "for", "the", "specified", "pool", "or", "the", "first", "gateway" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/asset.rb#L172-L180
train
tumblr/collins_client
lib/collins/util.rb
Collins.Util.deep_copy_hash
def deep_copy_hash hash require_that(hash.is_a?(Hash), "deep_copy_hash requires a hash be specified, got #{hash.class}") Marshal.load Marshal.dump(hash) end
ruby
def deep_copy_hash hash require_that(hash.is_a?(Hash), "deep_copy_hash requires a hash be specified, got #{hash.class}") Marshal.load Marshal.dump(hash) end
[ "def", "deep_copy_hash", "hash", "require_that", "(", "hash", ".", "is_a?", "(", "Hash", ")", ",", "\"deep_copy_hash requires a hash be specified, got #{hash.class}\"", ")", "Marshal", ".", "load", "Marshal", ".", "dump", "(", "hash", ")", "end" ]
Create a deep copy of a hash This is useful for copying a hash that will be mutated @note All keys and values must be serializable, Proc for instance will fail @param [Hash] hash the hash to copy @return [Hash]
[ "Create", "a", "deep", "copy", "of", "a", "hash" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L28-L31
train
tumblr/collins_client
lib/collins/util.rb
Collins.Util.require_non_empty
def require_non_empty value, message, return_value = false guard_value = if return_value == true then value elsif return_value != false then return_value else false end if value.is_a?(String) then require_that(!value.strip.empty?, message, guard_value) elsif value.respond_to?(:empty?) then require_that(!value.empty?, message, guard_value) else require_that(!value.nil?, message, guard_value) end end
ruby
def require_non_empty value, message, return_value = false guard_value = if return_value == true then value elsif return_value != false then return_value else false end if value.is_a?(String) then require_that(!value.strip.empty?, message, guard_value) elsif value.respond_to?(:empty?) then require_that(!value.empty?, message, guard_value) else require_that(!value.nil?, message, guard_value) end end
[ "def", "require_non_empty", "value", ",", "message", ",", "return_value", "=", "false", "guard_value", "=", "if", "return_value", "==", "true", "then", "value", "elsif", "return_value", "!=", "false", "then", "return_value", "else", "false", "end", "if", "value", ".", "is_a?", "(", "String", ")", "then", "require_that", "(", "!", "value", ".", "strip", ".", "empty?", ",", "message", ",", "guard_value", ")", "elsif", "value", ".", "respond_to?", "(", ":empty?", ")", "then", "require_that", "(", "!", "value", ".", "empty?", ",", "message", ",", "guard_value", ")", "else", "require_that", "(", "!", "value", ".", "nil?", ",", "message", ",", "guard_value", ")", "end", "end" ]
Require that a value not be empty If the value is a string, ensure that once stripped it's not empty. If the value responds to `:empty?`, ensure that it's not. Otherwise ensure the value isn't nil. @param [Object] value the value to check @param [String] message the exception message to use if the value is empty @param [Boolean,Object] return_value If true, returns value. If not false, returns the object @raise [ExpectationFailedError] if the value is empty @return [NilClass,Object] NilClass, or respecting return_value
[ "Require", "that", "a", "value", "not", "be", "empty" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L43-L58
train
tumblr/collins_client
lib/collins/util.rb
Collins.Util.require_that
def require_that guard, message, return_guard = false if not guard then raise ExpectationFailedError.new(message) end if return_guard == true then guard elsif return_guard != false then return_guard end end
ruby
def require_that guard, message, return_guard = false if not guard then raise ExpectationFailedError.new(message) end if return_guard == true then guard elsif return_guard != false then return_guard end end
[ "def", "require_that", "guard", ",", "message", ",", "return_guard", "=", "false", "if", "not", "guard", "then", "raise", "ExpectationFailedError", ".", "new", "(", "message", ")", "end", "if", "return_guard", "==", "true", "then", "guard", "elsif", "return_guard", "!=", "false", "then", "return_guard", "end", "end" ]
Require that a guard condition passes Simply checks that the guard is truthy, and throws an error otherwise @see #require_non_empty
[ "Require", "that", "a", "guard", "condition", "passes" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L64-L73
train
tumblr/collins_client
lib/collins/util.rb
Collins.Util.get_asset_or_tag
def get_asset_or_tag asset_or_tag asset = case asset_or_tag when Collins::Asset then asset_or_tag when String then Collins::Asset.new(asset_or_tag) when Symbol then Collins::Asset.new(asset_or_tag.to_s) else error_message = "Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}" raise ExpectationFailedError.new(error_message) end if asset.nil? || asset.tag.nil? then raise ExpectationFailedError.new("Empty asset tag, but a tag is required") end asset end
ruby
def get_asset_or_tag asset_or_tag asset = case asset_or_tag when Collins::Asset then asset_or_tag when String then Collins::Asset.new(asset_or_tag) when Symbol then Collins::Asset.new(asset_or_tag.to_s) else error_message = "Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}" raise ExpectationFailedError.new(error_message) end if asset.nil? || asset.tag.nil? then raise ExpectationFailedError.new("Empty asset tag, but a tag is required") end asset end
[ "def", "get_asset_or_tag", "asset_or_tag", "asset", "=", "case", "asset_or_tag", "when", "Collins", "::", "Asset", "then", "asset_or_tag", "when", "String", "then", "Collins", "::", "Asset", ".", "new", "(", "asset_or_tag", ")", "when", "Symbol", "then", "Collins", "::", "Asset", ".", "new", "(", "asset_or_tag", ".", "to_s", ")", "else", "error_message", "=", "\"Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}\"", "raise", "ExpectationFailedError", ".", "new", "(", "error_message", ")", "end", "if", "asset", ".", "nil?", "||", "asset", ".", "tag", ".", "nil?", "then", "raise", "ExpectationFailedError", ".", "new", "(", "\"Empty asset tag, but a tag is required\"", ")", "end", "asset", "end" ]
Resolve an asset from a string tag or collins asset @note This is perhaps the only collins specific method in Util @param [Collins::Asset,String,Symbol] asset_or_tag @return [Collins::Asset] a collins asset @raise [ExpectationFailedError] if asset\_or\_tag isn't valid
[ "Resolve", "an", "asset", "from", "a", "string", "tag", "or", "collins", "asset" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L80-L94
train
tumblr/collins_client
lib/collins/util.rb
Collins.Util.symbolize_hash
def symbolize_hash hash, options = {} return {} if (hash.nil? or hash.empty?) (raise ExpectationFailedError.new("symbolize_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase.to_sym : k.to_s.to_sym if v.is_a?(Hash) then result[key] = symbolize_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
ruby
def symbolize_hash hash, options = {} return {} if (hash.nil? or hash.empty?) (raise ExpectationFailedError.new("symbolize_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase.to_sym : k.to_s.to_sym if v.is_a?(Hash) then result[key] = symbolize_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
[ "def", "symbolize_hash", "hash", ",", "options", "=", "{", "}", "return", "{", "}", "if", "(", "hash", ".", "nil?", "or", "hash", ".", "empty?", ")", "(", "raise", "ExpectationFailedError", ".", "new", "(", "\"symbolize_hash called without a hash\"", ")", ")", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "hash", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "k", ",", "v", ")", "|", "key", "=", "options", "[", ":downcase", "]", "?", "k", ".", "to_s", ".", "downcase", ".", "to_sym", ":", "k", ".", "to_s", ".", "to_sym", "if", "v", ".", "is_a?", "(", "Hash", ")", "then", "result", "[", "key", "]", "=", "symbolize_hash", "(", "v", ")", "elsif", "v", ".", "is_a?", "(", "Regexp", ")", "&&", "options", "[", ":rewrite_regex", "]", "then", "result", "[", "key", "]", "=", "v", ".", "inspect", "[", "1", "..", "-", "2", "]", "else", "result", "[", "key", "]", "=", "v", "end", "result", "end", "end" ]
Given a hash, rewrite keys to symbols @param [Hash] hash the hash to symbolize @param [Hash] options specify how to process the hash @option options [Boolean] :rewrite_regex if the value is a regex and this is true, convert it to a string @option options [Boolean] :downcase if true, downcase the keys as well @raise [ExpectationFailedError] if hash is not a hash
[ "Given", "a", "hash", "rewrite", "keys", "to", "symbols" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L103-L117
train
tumblr/collins_client
lib/collins/util.rb
Collins.Util.stringify_hash
def stringify_hash hash, options = {} (raise ExpectationFailedError.new("stringify_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase : k.to_s if v.is_a?(Hash) then result[key] = stringify_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
ruby
def stringify_hash hash, options = {} (raise ExpectationFailedError.new("stringify_hash called without a hash")) unless hash.is_a?(Hash) hash.inject({}) do |result, (k,v)| key = options[:downcase] ? k.to_s.downcase : k.to_s if v.is_a?(Hash) then result[key] = stringify_hash(v) elsif v.is_a?(Regexp) && options[:rewrite_regex] then result[key] = v.inspect[1..-2] else result[key] = v end result end end
[ "def", "stringify_hash", "hash", ",", "options", "=", "{", "}", "(", "raise", "ExpectationFailedError", ".", "new", "(", "\"stringify_hash called without a hash\"", ")", ")", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "hash", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "k", ",", "v", ")", "|", "key", "=", "options", "[", ":downcase", "]", "?", "k", ".", "to_s", ".", "downcase", ":", "k", ".", "to_s", "if", "v", ".", "is_a?", "(", "Hash", ")", "then", "result", "[", "key", "]", "=", "stringify_hash", "(", "v", ")", "elsif", "v", ".", "is_a?", "(", "Regexp", ")", "&&", "options", "[", ":rewrite_regex", "]", "then", "result", "[", "key", "]", "=", "v", ".", "inspect", "[", "1", "..", "-", "2", "]", "else", "result", "[", "key", "]", "=", "v", "end", "result", "end", "end" ]
Given a hash, convert all keys to strings @see #symbolize_hash
[ "Given", "a", "hash", "convert", "all", "keys", "to", "strings" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/util.rb#L121-L134
train
todesking/okura
lib/okura.rb
Okura.Tagger.parse
def parse str chars=str.split(//) nodes=Nodes.new(chars.length+2,@mat) nodes.add(0,Node.mk_bos_eos) nodes.add(chars.length+1,Node.mk_bos_eos) str.length.times{|i| @dic.possible_words(str,i).each{|w| nodes.add(i+1,Node.new(w)) } } nodes end
ruby
def parse str chars=str.split(//) nodes=Nodes.new(chars.length+2,@mat) nodes.add(0,Node.mk_bos_eos) nodes.add(chars.length+1,Node.mk_bos_eos) str.length.times{|i| @dic.possible_words(str,i).each{|w| nodes.add(i+1,Node.new(w)) } } nodes end
[ "def", "parse", "str", "chars", "=", "str", ".", "split", "(", "/", "/", ")", "nodes", "=", "Nodes", ".", "new", "(", "chars", ".", "length", "+", "2", ",", "@mat", ")", "nodes", ".", "add", "(", "0", ",", "Node", ".", "mk_bos_eos", ")", "nodes", ".", "add", "(", "chars", ".", "length", "+", "1", ",", "Node", ".", "mk_bos_eos", ")", "str", ".", "length", ".", "times", "{", "|", "i", "|", "@dic", ".", "possible_words", "(", "str", ",", "i", ")", ".", "each", "{", "|", "w", "|", "nodes", ".", "add", "(", "i", "+", "1", ",", "Node", ".", "new", "(", "w", ")", ")", "}", "}", "nodes", "end" ]
-> Nodes
[ "-", ">", "Nodes" ]
4e34ae7a9316bec92e06e74cadb28677f8730299
https://github.com/todesking/okura/blob/4e34ae7a9316bec92e06e74cadb28677f8730299/lib/okura.rb#L22-L33
train
todesking/okura
lib/okura.rb
Okura.UnkDic.define
def define type_name,left,right,cost type=@char_types.named type_name (@templates[type_name]||=[]).push Word.new '',left,right,cost end
ruby
def define type_name,left,right,cost type=@char_types.named type_name (@templates[type_name]||=[]).push Word.new '',left,right,cost end
[ "def", "define", "type_name", ",", "left", ",", "right", ",", "cost", "type", "=", "@char_types", ".", "named", "type_name", "(", "@templates", "[", "type_name", "]", "||=", "[", "]", ")", ".", "push", "Word", ".", "new", "''", ",", "left", ",", "right", ",", "cost", "end" ]
String -> Feature -> Feature -> Integer ->
[ "String", "-", ">", "Feature", "-", ">", "Feature", "-", ">", "Integer", "-", ">" ]
4e34ae7a9316bec92e06e74cadb28677f8730299
https://github.com/todesking/okura/blob/4e34ae7a9316bec92e06e74cadb28677f8730299/lib/okura.rb#L373-L376
train
scottwillson/tabular
lib/tabular/keys.rb
Tabular.Keys.key_to_sym
def key_to_sym(key) case key when Column key.key when String key.to_sym else key end end
ruby
def key_to_sym(key) case key when Column key.key when String key.to_sym else key end end
[ "def", "key_to_sym", "(", "key", ")", "case", "key", "when", "Column", "key", ".", "key", "when", "String", "key", ".", "to_sym", "else", "key", "end", "end" ]
Return Symbol for +key+. Translate Column and String. Return +key+ unmodified for anything else.
[ "Return", "Symbol", "for", "+", "key", "+", ".", "Translate", "Column", "and", "String", ".", "Return", "+", "key", "+", "unmodified", "for", "anything", "else", "." ]
a479a0d55e91eb286f16adbfe43f97d69abbbe08
https://github.com/scottwillson/tabular/blob/a479a0d55e91eb286f16adbfe43f97d69abbbe08/lib/tabular/keys.rb#L6-L15
train
tobiasfeistmantl/LeSSL
lib/le_ssl/manager.rb
LeSSL.Manager.authorize_for_domain
def authorize_for_domain(domain, options={}) authorization = client.authorize(domain: domain) # Default challenge is via HTTP # but the developer can also use # a DNS TXT record to authorize. if options[:challenge] == :dns challenge = authorization.dns01 unless options[:skip_puts] puts "====================================================================" puts "Record:" puts puts " - Name: #{challenge.record_name}.#{domain}" puts " - Type: #{challenge.record_type}" puts " - Value: #{challenge.record_content}" puts puts "Create the record; Wait a minute (or two); Request for verification!" puts "====================================================================" end # With this option the dns verification is # done automatically. LeSSL waits until a # valid record on your DNS servers was found # and requests a verification. # # CAUTION! This is a blocking the thread! if options[:automatic_verification] dns = begin if ns = options[:custom_nameservers] LeSSL::DNS.new(ns) else LeSSL::DNS.new end end puts puts 'Wait until the TXT record was set...' # Wait with verification until the # challenge record is valid. while dns.challenge_record_invalid?(domain, challenge.record_content) puts 'DNS record not valid' if options[:verbose] sleep(2) # Wait 2 seconds end puts 'Valid TXT record found. Continue with verification...' return request_verification(challenge) else return challenge end else challenge = authorization.http01 file_name = Rails.root.join('public', challenge.filename) dir = File.dirname(Rails.root.join('public', challenge.filename)) FileUtils.mkdir_p(dir) File.write(file_name, challenge.file_content) return challenge.verify_status end end
ruby
def authorize_for_domain(domain, options={}) authorization = client.authorize(domain: domain) # Default challenge is via HTTP # but the developer can also use # a DNS TXT record to authorize. if options[:challenge] == :dns challenge = authorization.dns01 unless options[:skip_puts] puts "====================================================================" puts "Record:" puts puts " - Name: #{challenge.record_name}.#{domain}" puts " - Type: #{challenge.record_type}" puts " - Value: #{challenge.record_content}" puts puts "Create the record; Wait a minute (or two); Request for verification!" puts "====================================================================" end # With this option the dns verification is # done automatically. LeSSL waits until a # valid record on your DNS servers was found # and requests a verification. # # CAUTION! This is a blocking the thread! if options[:automatic_verification] dns = begin if ns = options[:custom_nameservers] LeSSL::DNS.new(ns) else LeSSL::DNS.new end end puts puts 'Wait until the TXT record was set...' # Wait with verification until the # challenge record is valid. while dns.challenge_record_invalid?(domain, challenge.record_content) puts 'DNS record not valid' if options[:verbose] sleep(2) # Wait 2 seconds end puts 'Valid TXT record found. Continue with verification...' return request_verification(challenge) else return challenge end else challenge = authorization.http01 file_name = Rails.root.join('public', challenge.filename) dir = File.dirname(Rails.root.join('public', challenge.filename)) FileUtils.mkdir_p(dir) File.write(file_name, challenge.file_content) return challenge.verify_status end end
[ "def", "authorize_for_domain", "(", "domain", ",", "options", "=", "{", "}", ")", "authorization", "=", "client", ".", "authorize", "(", "domain", ":", "domain", ")", "if", "options", "[", ":challenge", "]", "==", ":dns", "challenge", "=", "authorization", ".", "dns01", "unless", "options", "[", ":skip_puts", "]", "puts", "\"====================================================================\"", "puts", "\"Record:\"", "puts", "puts", "\" - Name: #{challenge.record_name}.#{domain}\"", "puts", "\" - Type: #{challenge.record_type}\"", "puts", "\" - Value: #{challenge.record_content}\"", "puts", "puts", "\"Create the record; Wait a minute (or two); Request for verification!\"", "puts", "\"====================================================================\"", "end", "if", "options", "[", ":automatic_verification", "]", "dns", "=", "begin", "if", "ns", "=", "options", "[", ":custom_nameservers", "]", "LeSSL", "::", "DNS", ".", "new", "(", "ns", ")", "else", "LeSSL", "::", "DNS", ".", "new", "end", "end", "puts", "puts", "'Wait until the TXT record was set...'", "while", "dns", ".", "challenge_record_invalid?", "(", "domain", ",", "challenge", ".", "record_content", ")", "puts", "'DNS record not valid'", "if", "options", "[", ":verbose", "]", "sleep", "(", "2", ")", "end", "puts", "'Valid TXT record found. Continue with verification...'", "return", "request_verification", "(", "challenge", ")", "else", "return", "challenge", "end", "else", "challenge", "=", "authorization", ".", "http01", "file_name", "=", "Rails", ".", "root", ".", "join", "(", "'public'", ",", "challenge", ".", "filename", ")", "dir", "=", "File", ".", "dirname", "(", "Rails", ".", "root", ".", "join", "(", "'public'", ",", "challenge", ".", "filename", ")", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "File", ".", "write", "(", "file_name", ",", "challenge", ".", "file_content", ")", "return", "challenge", ".", "verify_status", "end", "end" ]
Authorize the client for a domain name. Challenge options: - HTTP (default and recommended) - DNS
[ "Authorize", "the", "client", "for", "a", "domain", "name", "." ]
7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba
https://github.com/tobiasfeistmantl/LeSSL/blob/7ef8b39d1ebe47534424c9c12dc6d82b54dfe8ba/lib/le_ssl/manager.rb#L25-L90
train
tumblr/collins_client
lib/collins/asset_client.rb
Collins.AssetClient.method_missing
def method_missing meth, *args, &block if @client.respond_to?(meth) then method_parameters = @client.class.instance_method(meth).parameters asset_idx = method_parameters.find_index do |item| item[1] == :asset_or_tag end if asset_idx.nil? then @client.send(meth, *args, &block) else args_with_asset = args.insert(asset_idx, @tag) logger.debug("Doing #{meth}(#{args_with_asset.join(',')}) for #{@tag}") @client.send(meth, *args_with_asset, &block) end else super end end
ruby
def method_missing meth, *args, &block if @client.respond_to?(meth) then method_parameters = @client.class.instance_method(meth).parameters asset_idx = method_parameters.find_index do |item| item[1] == :asset_or_tag end if asset_idx.nil? then @client.send(meth, *args, &block) else args_with_asset = args.insert(asset_idx, @tag) logger.debug("Doing #{meth}(#{args_with_asset.join(',')}) for #{@tag}") @client.send(meth, *args_with_asset, &block) end else super end end
[ "def", "method_missing", "meth", ",", "*", "args", ",", "&", "block", "if", "@client", ".", "respond_to?", "(", "meth", ")", "then", "method_parameters", "=", "@client", ".", "class", ".", "instance_method", "(", "meth", ")", ".", "parameters", "asset_idx", "=", "method_parameters", ".", "find_index", "do", "|", "item", "|", "item", "[", "1", "]", "==", ":asset_or_tag", "end", "if", "asset_idx", ".", "nil?", "then", "@client", ".", "send", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "else", "args_with_asset", "=", "args", ".", "insert", "(", "asset_idx", ",", "@tag", ")", "logger", ".", "debug", "(", "\"Doing #{meth}(#{args_with_asset.join(',')}) for #{@tag}\"", ")", "@client", ".", "send", "(", "meth", ",", "*", "args_with_asset", ",", "&", "block", ")", "end", "else", "super", "end", "end" ]
Fill in the missing asset parameter on the dynamic method if needed If {Collins::Client} responds to the method, and the method requires an `asset_or_tag`, we insert the asset specified during initialization into the args array. If the method does not require an `asset_or_tag`, we simply proxy the method call as is. If {Collins::Client} does not respond to the method, we defer to `super`. @example collins_client.get('some_tag') # => returns that asset collins_client.with_asset('some_tag').get # => returns that same asset @note this method should never be called directly
[ "Fill", "in", "the", "missing", "asset", "parameter", "on", "the", "dynamic", "method", "if", "needed" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/asset_client.rb#L33-L49
train
JDHeiskell/filebound_client
lib/filebound_client.rb
FileboundClient.Client.get
def get(url, query_params = nil) JSON.parse(perform('get', url, query: query_params), symbolize_names: true, quirks_mode: true) end
ruby
def get(url, query_params = nil) JSON.parse(perform('get', url, query: query_params), symbolize_names: true, quirks_mode: true) end
[ "def", "get", "(", "url", ",", "query_params", "=", "nil", ")", "JSON", ".", "parse", "(", "perform", "(", "'get'", ",", "url", ",", "query", ":", "query_params", ")", ",", "symbolize_names", ":", "true", ",", "quirks_mode", ":", "true", ")", "end" ]
Initializes the client with the supplied Connection @param [Connection] connection the logged in Connection @return [FileboundClient::Client] an instance of FileboundClient::Client Executes a GET request on the current Filebound client session expecting JSON in the body of the response @param [String] url the resource url to request @param [Hash] query_params the optional query parameters to pass to the GET request @return [Hash] the JSON parsed hash of the response body
[ "Initializes", "the", "client", "with", "the", "supplied", "Connection" ]
cbaa56412ede796b4f088470b2b8e6dca1164d39
https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client.rb#L44-L46
train
tumblr/collins_client
lib/collins/option.rb
Collins.Option.or_else
def or_else *default if empty? then res = if block_given? then yield else default.first end if res.is_a?(Option) then res else ::Collins::Option(res) end else self end end
ruby
def or_else *default if empty? then res = if block_given? then yield else default.first end if res.is_a?(Option) then res else ::Collins::Option(res) end else self end end
[ "def", "or_else", "*", "default", "if", "empty?", "then", "res", "=", "if", "block_given?", "then", "yield", "else", "default", ".", "first", "end", "if", "res", ".", "is_a?", "(", "Option", ")", "then", "res", "else", "::", "Collins", "::", "Option", "(", "res", ")", "end", "else", "self", "end", "end" ]
Return this `Option` if non-empty, otherwise return the result of evaluating the default @example Option(nil).or_else { "foo" } == Some("foo") @return [Option<Object>]
[ "Return", "this", "Option", "if", "non", "-", "empty", "otherwise", "return", "the", "result", "of", "evaluating", "the", "default" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/option.rb#L71-L86
train
tumblr/collins_client
lib/collins/option.rb
Collins.Option.map
def map &block if empty? then None.new else Some.new(block.call(get)) end end
ruby
def map &block if empty? then None.new else Some.new(block.call(get)) end end
[ "def", "map", "&", "block", "if", "empty?", "then", "None", ".", "new", "else", "Some", ".", "new", "(", "block", ".", "call", "(", "get", ")", ")", "end", "end" ]
If the option value is defined, apply the specified block to that value @example Option("15").map{|i| i.to_i}.get == 15 @yieldparam [Object] block The current value @yieldreturn [Object] The new value @return [Option<Object>] Optional value
[ "If", "the", "option", "value", "is", "defined", "apply", "the", "specified", "block", "to", "that", "value" ]
e9a58d0f0123232fe3784c8bce1f46dfb12c1637
https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/option.rb#L111-L117
train