id
int32
0
24.9k
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
22,000
ynab/ynab-sdk-ruby
lib/ynab/api/scheduled_transactions_api.rb
YNAB.ScheduledTransactionsApi.get_scheduled_transaction_by_id
def get_scheduled_transaction_by_id(budget_id, scheduled_transaction_id, opts = {}) data, _status_code, _headers = get_scheduled_transaction_by_id_with_http_info(budget_id, scheduled_transaction_id, opts) data end
ruby
def get_scheduled_transaction_by_id(budget_id, scheduled_transaction_id, opts = {}) data, _status_code, _headers = get_scheduled_transaction_by_id_with_http_info(budget_id, scheduled_transaction_id, opts) data end
[ "def", "get_scheduled_transaction_by_id", "(", "budget_id", ",", "scheduled_transaction_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_scheduled_transaction_by_id_with_http_info", "(", "budget_id", ",", "scheduled_transaction_id", ",", "opts", ")", "data", "end" ]
Single scheduled transaction Returns a single scheduled transaction @param budget_id The id of the budget (\"last-used\" can also be used to specify the last used budget) @param scheduled_transaction_id The id of the scheduled transaction @param [Hash] opts the optional parameters @return [ScheduledTransactionResponse]
[ "Single", "scheduled", "transaction", "Returns", "a", "single", "scheduled", "transaction" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/scheduled_transactions_api.rb#L28-L31
22,001
ynab/ynab-sdk-ruby
lib/ynab/api/scheduled_transactions_api.rb
YNAB.ScheduledTransactionsApi.get_scheduled_transactions
def get_scheduled_transactions(budget_id, opts = {}) data, _status_code, _headers = get_scheduled_transactions_with_http_info(budget_id, opts) data end
ruby
def get_scheduled_transactions(budget_id, opts = {}) data, _status_code, _headers = get_scheduled_transactions_with_http_info(budget_id, opts) data end
[ "def", "get_scheduled_transactions", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_scheduled_transactions_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List scheduled transactions Returns all scheduled transactions @param budget_id The id of the budget (\"last-used\" can also be used to specify the last used budget) @param [Hash] opts the optional parameters @return [ScheduledTransactionsResponse]
[ "List", "scheduled", "transactions", "Returns", "all", "scheduled", "transactions" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/scheduled_transactions_api.rb#L85-L88
22,002
pioz/chess
lib/chess/gnuchess.rb
Chess.Gnuchess.gnuchess_move
def gnuchess_move pipe = IO.popen('gnuchess -x', 'r+') begin pipe.puts('depth 1') pipe.puts('manual') self.coord_moves.each do |m| pipe.puts(m) end pipe.puts('go') while line = pipe.gets raise IllegalMoveError if line.include?('Invalid move') match = line.match(/My move is : ([a-h][1-8][a-h][1-8][rkbq]?)/) return match[1] if match end ensure pipe.puts('quit') pipe.close end return moves end
ruby
def gnuchess_move pipe = IO.popen('gnuchess -x', 'r+') begin pipe.puts('depth 1') pipe.puts('manual') self.coord_moves.each do |m| pipe.puts(m) end pipe.puts('go') while line = pipe.gets raise IllegalMoveError if line.include?('Invalid move') match = line.match(/My move is : ([a-h][1-8][a-h][1-8][rkbq]?)/) return match[1] if match end ensure pipe.puts('quit') pipe.close end return moves end
[ "def", "gnuchess_move", "pipe", "=", "IO", ".", "popen", "(", "'gnuchess -x'", ",", "'r+'", ")", "begin", "pipe", ".", "puts", "(", "'depth 1'", ")", "pipe", ".", "puts", "(", "'manual'", ")", "self", ".", "coord_moves", ".", "each", "do", "|", "m", "|", "pipe", ".", "puts", "(", "m", ")", "end", "pipe", ".", "puts", "(", "'go'", ")", "while", "line", "=", "pipe", ".", "gets", "raise", "IllegalMoveError", "if", "line", ".", "include?", "(", "'Invalid move'", ")", "match", "=", "line", ".", "match", "(", "/", "/", ")", "return", "match", "[", "1", "]", "if", "match", "end", "ensure", "pipe", ".", "puts", "(", "'quit'", ")", "pipe", ".", "close", "end", "return", "moves", "end" ]
Returns the next move calculated by Gnuchess. @return [String] Returns the short algebraic chess notation of the move.
[ "Returns", "the", "next", "move", "calculated", "by", "Gnuchess", "." ]
80744d1f351d45ecece8058e208c0f381a0569f5
https://github.com/pioz/chess/blob/80744d1f351d45ecece8058e208c0f381a0569f5/lib/chess/gnuchess.rb#L18-L37
22,003
ynab/ynab-sdk-ruby
lib/ynab/api/payees_api.rb
YNAB.PayeesApi.get_payee_by_id
def get_payee_by_id(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_payee_by_id_with_http_info(budget_id, payee_id, opts) data end
ruby
def get_payee_by_id(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_payee_by_id_with_http_info(budget_id, payee_id, opts) data end
[ "def", "get_payee_by_id", "(", "budget_id", ",", "payee_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payee_by_id_with_http_info", "(", "budget_id", ",", "payee_id", ",", "opts", ")", "data", "end" ]
Single payee Returns single payee @param budget_id The id of the budget (\"last-used\" can also be used to specify the last used budget) @param payee_id The id of the payee @param [Hash] opts the optional parameters @return [PayeeResponse]
[ "Single", "payee", "Returns", "single", "payee" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payees_api.rb#L28-L31
22,004
ynab/ynab-sdk-ruby
lib/ynab/api/payees_api.rb
YNAB.PayeesApi.get_payees
def get_payees(budget_id, opts = {}) data, _status_code, _headers = get_payees_with_http_info(budget_id, opts) data end
ruby
def get_payees(budget_id, opts = {}) data, _status_code, _headers = get_payees_with_http_info(budget_id, opts) data end
[ "def", "get_payees", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payees_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List payees Returns all payees @param budget_id The id of the budget (\"last-used\" can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [PayeesResponse]
[ "List", "payees", "Returns", "all", "payees" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payees_api.rb#L86-L89
22,005
r7kamura/jdoc
lib/jdoc/resource.rb
Jdoc.Resource.links
def links @links ||= @schema.links.map do |link| if link.method && link.href Link.new(link) end end.compact end
ruby
def links @links ||= @schema.links.map do |link| if link.method && link.href Link.new(link) end end.compact end
[ "def", "links", "@links", "||=", "@schema", ".", "links", ".", "map", "do", "|", "link", "|", "if", "link", ".", "method", "&&", "link", ".", "href", "Link", ".", "new", "(", "link", ")", "end", "end", ".", "compact", "end" ]
Defined to change uniqueness in Hash key Defined to change uniqueness in Hash key
[ "Defined", "to", "change", "uniqueness", "in", "Hash", "key", "Defined", "to", "change", "uniqueness", "in", "Hash", "key" ]
42fb0d063313bf6b8eae39ddd8bc1e55381d2890
https://github.com/r7kamura/jdoc/blob/42fb0d063313bf6b8eae39ddd8bc1e55381d2890/lib/jdoc/resource.rb#L59-L65
22,006
propublica/daybreak
lib/daybreak/db.rb
Daybreak.DB.hash_default
def hash_default(_, key) if @default != nil value = @default.respond_to?(:call) ? @default.call(key) : @default @journal << [key, value] @table[key] = value end end
ruby
def hash_default(_, key) if @default != nil value = @default.respond_to?(:call) ? @default.call(key) : @default @journal << [key, value] @table[key] = value end end
[ "def", "hash_default", "(", "_", ",", "key", ")", "if", "@default", "!=", "nil", "value", "=", "@default", ".", "respond_to?", "(", ":call", ")", "?", "@default", ".", "call", "(", "key", ")", ":", "@default", "@journal", "<<", "[", "key", ",", "value", "]", "@table", "[", "key", "]", "=", "value", "end", "end" ]
The block used in @table for new records
[ "The", "block", "used", "in" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/db.rb#L274-L280
22,007
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.clear
def clear flush with_tmpfile do |path, file| file.write(@format.header) file.close # Clear replaces the database file like a compactification does with_flock(File::LOCK_EX) do File.rename(path, @file) end end open end
ruby
def clear flush with_tmpfile do |path, file| file.write(@format.header) file.close # Clear replaces the database file like a compactification does with_flock(File::LOCK_EX) do File.rename(path, @file) end end open end
[ "def", "clear", "flush", "with_tmpfile", "do", "|", "path", ",", "file", "|", "file", ".", "write", "(", "@format", ".", "header", ")", "file", ".", "close", "# Clear replaces the database file like a compactification does", "with_flock", "(", "File", "::", "LOCK_EX", ")", "do", "File", ".", "rename", "(", "path", ",", "@file", ")", "end", "end", "open", "end" ]
Clear the database log and yield
[ "Clear", "the", "database", "log", "and", "yield" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L51-L62
22,008
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.compact
def compact load with_tmpfile do |path, file| # Compactified database has the same size -> return return self if @pos == file.write(dump(yield, @format.header)) with_flock(File::LOCK_EX) do # Database was replaced (cleared or compactified) in the meantime if @pos != nil # Append changed journal records if the database changed during compactification file.write(read) file.close File.rename(path, @file) end end end open replay end
ruby
def compact load with_tmpfile do |path, file| # Compactified database has the same size -> return return self if @pos == file.write(dump(yield, @format.header)) with_flock(File::LOCK_EX) do # Database was replaced (cleared or compactified) in the meantime if @pos != nil # Append changed journal records if the database changed during compactification file.write(read) file.close File.rename(path, @file) end end end open replay end
[ "def", "compact", "load", "with_tmpfile", "do", "|", "path", ",", "file", "|", "# Compactified database has the same size -> return", "return", "self", "if", "@pos", "==", "file", ".", "write", "(", "dump", "(", "yield", ",", "@format", ".", "header", ")", ")", "with_flock", "(", "File", "::", "LOCK_EX", ")", "do", "# Database was replaced (cleared or compactified) in the meantime", "if", "@pos", "!=", "nil", "# Append changed journal records if the database changed during compactification", "file", ".", "write", "(", "read", ")", "file", ".", "close", "File", ".", "rename", "(", "path", ",", "@file", ")", "end", "end", "end", "open", "replay", "end" ]
Compact the logfile to represent the in-memory state
[ "Compact", "the", "logfile", "to", "represent", "the", "in", "-", "memory", "state" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L65-L82
22,009
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.open
def open @fd.close if @fd @fd = File.open(@file, 'ab+') @fd.advise(:sequential) if @fd.respond_to? :advise stat = @fd.stat @inode = stat.ino write(@format.header) if stat.size == 0 @pos = nil end
ruby
def open @fd.close if @fd @fd = File.open(@file, 'ab+') @fd.advise(:sequential) if @fd.respond_to? :advise stat = @fd.stat @inode = stat.ino write(@format.header) if stat.size == 0 @pos = nil end
[ "def", "open", "@fd", ".", "close", "if", "@fd", "@fd", "=", "File", ".", "open", "(", "@file", ",", "'ab+'", ")", "@fd", ".", "advise", "(", ":sequential", ")", "if", "@fd", ".", "respond_to?", ":advise", "stat", "=", "@fd", ".", "stat", "@inode", "=", "stat", ".", "ino", "write", "(", "@format", ".", "header", ")", "if", "stat", ".", "size", "==", "0", "@pos", "=", "nil", "end" ]
Open or reopen file
[ "Open", "or", "reopen", "file" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L98-L106
22,010
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.read
def read with_flock(File::LOCK_SH) do # File was opened unless @pos @fd.pos = 0 @format.read_header(@fd) @size = 0 @emit.call(nil) else @fd.pos = @pos end buf = @fd.read @pos = @fd.pos buf end end
ruby
def read with_flock(File::LOCK_SH) do # File was opened unless @pos @fd.pos = 0 @format.read_header(@fd) @size = 0 @emit.call(nil) else @fd.pos = @pos end buf = @fd.read @pos = @fd.pos buf end end
[ "def", "read", "with_flock", "(", "File", "::", "LOCK_SH", ")", "do", "# File was opened", "unless", "@pos", "@fd", ".", "pos", "=", "0", "@format", ".", "read_header", "(", "@fd", ")", "@size", "=", "0", "@emit", ".", "call", "(", "nil", ")", "else", "@fd", ".", "pos", "=", "@pos", "end", "buf", "=", "@fd", ".", "read", "@pos", "=", "@fd", ".", "pos", "buf", "end", "end" ]
Read new file content
[ "Read", "new", "file", "content" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L109-L124
22,011
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.dump
def dump(records, dump = '') # each is faster than inject records.each do |record| record[1] = @serializer.dump(record.last) dump << @format.dump(record) end dump end
ruby
def dump(records, dump = '') # each is faster than inject records.each do |record| record[1] = @serializer.dump(record.last) dump << @format.dump(record) end dump end
[ "def", "dump", "(", "records", ",", "dump", "=", "''", ")", "# each is faster than inject", "records", ".", "each", "do", "|", "record", "|", "record", "[", "1", "]", "=", "@serializer", ".", "dump", "(", "record", ".", "last", ")", "dump", "<<", "@format", ".", "dump", "(", "record", ")", "end", "dump", "end" ]
Return database dump as string
[ "Return", "database", "dump", "as", "string" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L127-L134
22,012
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.write
def write(dump) with_flock(File::LOCK_EX) do @fd.write(dump) # Flush to make sure the file is really updated @fd.flush end @pos = @fd.pos if @pos && @fd.pos == @pos + dump.bytesize end
ruby
def write(dump) with_flock(File::LOCK_EX) do @fd.write(dump) # Flush to make sure the file is really updated @fd.flush end @pos = @fd.pos if @pos && @fd.pos == @pos + dump.bytesize end
[ "def", "write", "(", "dump", ")", "with_flock", "(", "File", "::", "LOCK_EX", ")", "do", "@fd", ".", "write", "(", "dump", ")", "# Flush to make sure the file is really updated", "@fd", ".", "flush", "end", "@pos", "=", "@fd", ".", "pos", "if", "@pos", "&&", "@fd", ".", "pos", "==", "@pos", "+", "dump", ".", "bytesize", "end" ]
Write data to output stream and advance @pos
[ "Write", "data", "to", "output", "stream", "and", "advance" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L164-L171
22,013
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.with_flock
def with_flock(mode) return yield if @locked begin loop do # HACK: JRuby returns false if the process is already hold by the same process # see https://github.com/jruby/jruby/issues/496 Thread.pass until @fd.flock(mode) # Check if database was replaced (cleared or compactified) in the meantime # break if not stat = @fd.stat break if stat.nlink > 0 && stat.ino == @inode open end @locked = true yield ensure @fd.flock(File::LOCK_UN) @locked = false end end
ruby
def with_flock(mode) return yield if @locked begin loop do # HACK: JRuby returns false if the process is already hold by the same process # see https://github.com/jruby/jruby/issues/496 Thread.pass until @fd.flock(mode) # Check if database was replaced (cleared or compactified) in the meantime # break if not stat = @fd.stat break if stat.nlink > 0 && stat.ino == @inode open end @locked = true yield ensure @fd.flock(File::LOCK_UN) @locked = false end end
[ "def", "with_flock", "(", "mode", ")", "return", "yield", "if", "@locked", "begin", "loop", "do", "# HACK: JRuby returns false if the process is already hold by the same process", "# see https://github.com/jruby/jruby/issues/496", "Thread", ".", "pass", "until", "@fd", ".", "flock", "(", "mode", ")", "# Check if database was replaced (cleared or compactified) in the meantime", "# break if not", "stat", "=", "@fd", ".", "stat", "break", "if", "stat", ".", "nlink", ">", "0", "&&", "stat", ".", "ino", "==", "@inode", "open", "end", "@locked", "=", "true", "yield", "ensure", "@fd", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "@locked", "=", "false", "end", "end" ]
Block with file lock
[ "Block", "with", "file", "lock" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L174-L193
22,014
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.with_tmpfile
def with_tmpfile path = [@file, $$.to_s(36), Thread.current.object_id.to_s(36)].join file = File.open(path, 'wb') yield(path, file) ensure file.close unless file.closed? File.unlink(path) if File.exists?(path) end
ruby
def with_tmpfile path = [@file, $$.to_s(36), Thread.current.object_id.to_s(36)].join file = File.open(path, 'wb') yield(path, file) ensure file.close unless file.closed? File.unlink(path) if File.exists?(path) end
[ "def", "with_tmpfile", "path", "=", "[", "@file", ",", "$$", ".", "to_s", "(", "36", ")", ",", "Thread", ".", "current", ".", "object_id", ".", "to_s", "(", "36", ")", "]", ".", "join", "file", "=", "File", ".", "open", "(", "path", ",", "'wb'", ")", "yield", "(", "path", ",", "file", ")", "ensure", "file", ".", "close", "unless", "file", ".", "closed?", "File", ".", "unlink", "(", "path", ")", "if", "File", ".", "exists?", "(", "path", ")", "end" ]
Open temporary file and pass it to the block
[ "Open", "temporary", "file", "and", "pass", "it", "to", "the", "block" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L196-L203
22,015
propublica/daybreak
lib/daybreak/format.rb
Daybreak.Format.read_header
def read_header(input) raise 'Not a Daybreak database' if input.read(MAGIC.bytesize) != MAGIC ver = input.read(2).unpack('n').first raise "Expected database version #{VERSION}, got #{ver}" if ver != VERSION end
ruby
def read_header(input) raise 'Not a Daybreak database' if input.read(MAGIC.bytesize) != MAGIC ver = input.read(2).unpack('n').first raise "Expected database version #{VERSION}, got #{ver}" if ver != VERSION end
[ "def", "read_header", "(", "input", ")", "raise", "'Not a Daybreak database'", "if", "input", ".", "read", "(", "MAGIC", ".", "bytesize", ")", "!=", "MAGIC", "ver", "=", "input", ".", "read", "(", "2", ")", ".", "unpack", "(", "'n'", ")", ".", "first", "raise", "\"Expected database version #{VERSION}, got #{ver}\"", "if", "ver", "!=", "VERSION", "end" ]
Read database header from input stream @param [#read] input the input stream @return void
[ "Read", "database", "header", "from", "input", "stream" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/format.rb#L10-L14
22,016
propublica/daybreak
lib/daybreak/format.rb
Daybreak.Format.dump
def dump(record) data = if record.size == 1 [record[0].bytesize, DELETE].pack('NN') << record[0] else [record[0].bytesize, record[1].bytesize].pack('NN') << record[0] << record[1] end data << crc32(data) end
ruby
def dump(record) data = if record.size == 1 [record[0].bytesize, DELETE].pack('NN') << record[0] else [record[0].bytesize, record[1].bytesize].pack('NN') << record[0] << record[1] end data << crc32(data) end
[ "def", "dump", "(", "record", ")", "data", "=", "if", "record", ".", "size", "==", "1", "[", "record", "[", "0", "]", ".", "bytesize", ",", "DELETE", "]", ".", "pack", "(", "'NN'", ")", "<<", "record", "[", "0", "]", "else", "[", "record", "[", "0", "]", ".", "bytesize", ",", "record", "[", "1", "]", ".", "bytesize", "]", ".", "pack", "(", "'NN'", ")", "<<", "record", "[", "0", "]", "<<", "record", "[", "1", "]", "end", "data", "<<", "crc32", "(", "data", ")", "end" ]
Serialize record and return string @param [Array] record an array with [key, value] or [key] if the record is deleted @return [String] serialized record
[ "Serialize", "record", "and", "return", "string" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/format.rb#L25-L33
22,017
propublica/daybreak
lib/daybreak/format.rb
Daybreak.Format.parse
def parse(buf) n, count = 0, 0 while n < buf.size key_size, value_size = buf[n, 8].unpack('NN') data_size = key_size + 8 data_size += value_size if value_size != DELETE data = buf[n, data_size] n += data_size raise 'CRC mismatch: your data might be corrupted!' unless buf[n, 4] == crc32(data) n += 4 yield(value_size == DELETE ? [data[8, key_size]] : [data[8, key_size], data[8 + key_size, value_size]]) count += 1 end count end
ruby
def parse(buf) n, count = 0, 0 while n < buf.size key_size, value_size = buf[n, 8].unpack('NN') data_size = key_size + 8 data_size += value_size if value_size != DELETE data = buf[n, data_size] n += data_size raise 'CRC mismatch: your data might be corrupted!' unless buf[n, 4] == crc32(data) n += 4 yield(value_size == DELETE ? [data[8, key_size]] : [data[8, key_size], data[8 + key_size, value_size]]) count += 1 end count end
[ "def", "parse", "(", "buf", ")", "n", ",", "count", "=", "0", ",", "0", "while", "n", "<", "buf", ".", "size", "key_size", ",", "value_size", "=", "buf", "[", "n", ",", "8", "]", ".", "unpack", "(", "'NN'", ")", "data_size", "=", "key_size", "+", "8", "data_size", "+=", "value_size", "if", "value_size", "!=", "DELETE", "data", "=", "buf", "[", "n", ",", "data_size", "]", "n", "+=", "data_size", "raise", "'CRC mismatch: your data might be corrupted!'", "unless", "buf", "[", "n", ",", "4", "]", "==", "crc32", "(", "data", ")", "n", "+=", "4", "yield", "(", "value_size", "==", "DELETE", "?", "[", "data", "[", "8", ",", "key_size", "]", "]", ":", "[", "data", "[", "8", ",", "key_size", "]", ",", "data", "[", "8", "+", "key_size", ",", "value_size", "]", "]", ")", "count", "+=", "1", "end", "count", "end" ]
Deserialize records from buffer, and yield them. @param [String] buf the buffer to read from @yield [Array] blk deserialized record [key, value] or [key] if the record is deleted @return [Fixnum] number of records
[ "Deserialize", "records", "from", "buffer", "and", "yield", "them", "." ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/format.rb#L39-L53
22,018
ronin-ruby/ronin
lib/ronin/url.rb
Ronin.URL.query_string
def query_string params = {} self.query_params.each do |param| params[param.name] = param.value end return ::URI::QueryParams.dump(params) end
ruby
def query_string params = {} self.query_params.each do |param| params[param.name] = param.value end return ::URI::QueryParams.dump(params) end
[ "def", "query_string", "params", "=", "{", "}", "self", ".", "query_params", ".", "each", "do", "|", "param", "|", "params", "[", "param", ".", "name", "]", "=", "param", ".", "value", "end", "return", "::", "URI", "::", "QueryParams", ".", "dump", "(", "params", ")", "end" ]
Dumps the URL query params into a URI query string. @return [String] The URI query string. @since 1.0.0 @api public
[ "Dumps", "the", "URL", "query", "params", "into", "a", "URI", "query", "string", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/url.rb#L418-L426
22,019
ronin-ruby/ronin
lib/ronin/url.rb
Ronin.URL.query_string=
def query_string=(query) self.query_params.clear ::URI::QueryParams.parse(query).each do |name,value| self.query_params.new( :name => URLQueryParamName.first_or_new(:name => name), :value => value ) end return query end
ruby
def query_string=(query) self.query_params.clear ::URI::QueryParams.parse(query).each do |name,value| self.query_params.new( :name => URLQueryParamName.first_or_new(:name => name), :value => value ) end return query end
[ "def", "query_string", "=", "(", "query", ")", "self", ".", "query_params", ".", "clear", "::", "URI", "::", "QueryParams", ".", "parse", "(", "query", ")", ".", "each", "do", "|", "name", ",", "value", "|", "self", ".", "query_params", ".", "new", "(", ":name", "=>", "URLQueryParamName", ".", "first_or_new", "(", ":name", "=>", "name", ")", ",", ":value", "=>", "value", ")", "end", "return", "query", "end" ]
Sets the query params of the URL. @param [String] query The query string to parse. @return [String] The given query string. @since 1.0.0 @api public
[ "Sets", "the", "query", "params", "of", "the", "URL", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/url.rb#L441-L452
22,020
ronin-ruby/ronin
lib/ronin/url.rb
Ronin.URL.to_uri
def to_uri # map the URL scheme to a URI class url_class = SCHEMES.fetch(self.scheme.name,::URI::Generic) host = if self.host_name self.host_name.address end port = if self.port self.port.number end query = unless self.query_params.empty? self.query_string end # build the URI return url_class.build( :scheme => self.scheme.name, :host => host, :port => port, :path => self.path, :query => query, :fragment => self.fragment ) end
ruby
def to_uri # map the URL scheme to a URI class url_class = SCHEMES.fetch(self.scheme.name,::URI::Generic) host = if self.host_name self.host_name.address end port = if self.port self.port.number end query = unless self.query_params.empty? self.query_string end # build the URI return url_class.build( :scheme => self.scheme.name, :host => host, :port => port, :path => self.path, :query => query, :fragment => self.fragment ) end
[ "def", "to_uri", "# map the URL scheme to a URI class", "url_class", "=", "SCHEMES", ".", "fetch", "(", "self", ".", "scheme", ".", "name", ",", "::", "URI", "::", "Generic", ")", "host", "=", "if", "self", ".", "host_name", "self", ".", "host_name", ".", "address", "end", "port", "=", "if", "self", ".", "port", "self", ".", "port", ".", "number", "end", "query", "=", "unless", "self", ".", "query_params", ".", "empty?", "self", ".", "query_string", "end", "# build the URI", "return", "url_class", ".", "build", "(", ":scheme", "=>", "self", ".", "scheme", ".", "name", ",", ":host", "=>", "host", ",", ":port", "=>", "port", ",", ":path", "=>", "self", ".", "path", ",", ":query", "=>", "query", ",", ":fragment", "=>", "self", ".", "fragment", ")", "end" ]
Builds a URI object from the URL. @return [URI::HTTP, URI::HTTPS] The URI object created from the URL attributes. @since 1.0.0 @api public
[ "Builds", "a", "URI", "object", "from", "the", "URL", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/url.rb#L464-L488
22,021
ronin-ruby/ronin
lib/ronin/host_name.rb
Ronin.HostName.lookup!
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) ips = begin resolver.getaddresses(self.address) rescue [] end ips.map! do |addr| IPAddress.first_or_create( :address => addr, :host_names => [self] ) end return ips end
ruby
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) ips = begin resolver.getaddresses(self.address) rescue [] end ips.map! do |addr| IPAddress.first_or_create( :address => addr, :host_names => [self] ) end return ips end
[ "def", "lookup!", "(", "nameserver", "=", "nil", ")", "resolver", "=", "Resolv", ".", "resolver", "(", "nameserver", ")", "ips", "=", "begin", "resolver", ".", "getaddresses", "(", "self", ".", "address", ")", "rescue", "[", "]", "end", "ips", ".", "map!", "do", "|", "addr", "|", "IPAddress", ".", "first_or_create", "(", ":address", "=>", "addr", ",", ":host_names", "=>", "[", "self", "]", ")", "end", "return", "ips", "end" ]
Looks up all IP Addresses for the host name. @param [String] nameserver The optional nameserver to query. @return [Array<IPAddress>] The IP Addresses for the host name. @since 1.0.0 @api public
[ "Looks", "up", "all", "IP", "Addresses", "for", "the", "host", "name", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/host_name.rb#L218-L234
22,022
ronin-ruby/ronin
lib/ronin/campaign.rb
Ronin.Campaign.target!
def target!(addr) unless (address = Address.first(:address => addr)) raise("unknown address #{addr.dump}") end return Target.first_or_create(:campaign => self, :address => address) end
ruby
def target!(addr) unless (address = Address.first(:address => addr)) raise("unknown address #{addr.dump}") end return Target.first_or_create(:campaign => self, :address => address) end
[ "def", "target!", "(", "addr", ")", "unless", "(", "address", "=", "Address", ".", "first", "(", ":address", "=>", "addr", ")", ")", "raise", "(", "\"unknown address #{addr.dump}\"", ")", "end", "return", "Target", ".", "first_or_create", "(", ":campaign", "=>", "self", ",", ":address", "=>", "address", ")", "end" ]
Adds an address to the campaign. @param [String] addr The address that will be targeted. @return [Target] The new target of the campaign. @raise [RuntimeError] The given address could not be found. @since 1.0.0 @api public
[ "Adds", "an", "address", "to", "the", "campaign", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/campaign.rb#L120-L126
22,023
ronin-ruby/ronin
lib/ronin/ip_address.rb
Ronin.IPAddress.lookup!
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) hosts = begin resolver.getnames(self.address.to_s) rescue [] end hosts.map! do |name| HostName.first_or_create( :address => name, :ip_addresses => [self] ) end return hosts end
ruby
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) hosts = begin resolver.getnames(self.address.to_s) rescue [] end hosts.map! do |name| HostName.first_or_create( :address => name, :ip_addresses => [self] ) end return hosts end
[ "def", "lookup!", "(", "nameserver", "=", "nil", ")", "resolver", "=", "Resolv", ".", "resolver", "(", "nameserver", ")", "hosts", "=", "begin", "resolver", ".", "getnames", "(", "self", ".", "address", ".", "to_s", ")", "rescue", "[", "]", "end", "hosts", ".", "map!", "do", "|", "name", "|", "HostName", ".", "first_or_create", "(", ":address", "=>", "name", ",", ":ip_addresses", "=>", "[", "self", "]", ")", "end", "return", "hosts", "end" ]
Performs a reverse lookup on the IP address. @param [String] nameserver Optional nameserver to query. @return [Array<HostName>] The host-names associated with the IP Address. @since 1.0.0 @api public
[ "Performs", "a", "reverse", "lookup", "on", "the", "IP", "address", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/ip_address.rb#L236-L252
22,024
ronin-ruby/ronin
lib/ronin/repository.rb
Ronin.Repository.find_script
def find_script(sub_path) paths = @script_dirs.map { |dir| File.join(dir,sub_path) } return script_paths.first(:path => paths) end
ruby
def find_script(sub_path) paths = @script_dirs.map { |dir| File.join(dir,sub_path) } return script_paths.first(:path => paths) end
[ "def", "find_script", "(", "sub_path", ")", "paths", "=", "@script_dirs", ".", "map", "{", "|", "dir", "|", "File", ".", "join", "(", "dir", ",", "sub_path", ")", "}", "return", "script_paths", ".", "first", "(", ":path", "=>", "paths", ")", "end" ]
Finds a cached script. @param [String] sub_path The sub-path within the repository to search for. @return [Script::Path, nil] The matching script path. @since 1.1.0 @api private
[ "Finds", "a", "cached", "script", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/repository.rb#L550-L554
22,025
ronin-ruby/ronin
lib/ronin/repository.rb
Ronin.Repository.update!
def update! local_repo = Pullr::LocalRepository.new( :path => self.path, :scm => self.scm ) # only update if we have a repository local_repo.update(self.uri) # re-initialize the metadata initialize_metadata # save the repository if save # syncs the cached files of the repository sync_scripts! end yield self if block_given? return self end
ruby
def update! local_repo = Pullr::LocalRepository.new( :path => self.path, :scm => self.scm ) # only update if we have a repository local_repo.update(self.uri) # re-initialize the metadata initialize_metadata # save the repository if save # syncs the cached files of the repository sync_scripts! end yield self if block_given? return self end
[ "def", "update!", "local_repo", "=", "Pullr", "::", "LocalRepository", ".", "new", "(", ":path", "=>", "self", ".", "path", ",", ":scm", "=>", "self", ".", "scm", ")", "# only update if we have a repository", "local_repo", ".", "update", "(", "self", ".", "uri", ")", "# re-initialize the metadata", "initialize_metadata", "# save the repository", "if", "save", "# syncs the cached files of the repository", "sync_scripts!", "end", "yield", "self", "if", "block_given?", "return", "self", "end" ]
Updates the repository, reloads it's metadata and syncs the cached files of the repository. @yield [repo] If a block is given, it will be passed after the repository has been updated. @yieldparam [Repository] repo The updated repository. @return [Repository] The updated repository. @since 1.0.0 @api private
[ "Updates", "the", "repository", "reloads", "it", "s", "metadata", "and", "syncs", "the", "cached", "files", "of", "the", "repository", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/repository.rb#L646-L666
22,026
ronin-ruby/ronin
lib/ronin/repository.rb
Ronin.Repository.uninstall!
def uninstall! deactivate! FileUtils.rm_rf(self.path) if self.installed? # destroy any cached files first clean_scripts! # remove the repository from the database destroy if saved? yield self if block_given? return self end
ruby
def uninstall! deactivate! FileUtils.rm_rf(self.path) if self.installed? # destroy any cached files first clean_scripts! # remove the repository from the database destroy if saved? yield self if block_given? return self end
[ "def", "uninstall!", "deactivate!", "FileUtils", ".", "rm_rf", "(", "self", ".", "path", ")", "if", "self", ".", "installed?", "# destroy any cached files first", "clean_scripts!", "# remove the repository from the database", "destroy", "if", "saved?", "yield", "self", "if", "block_given?", "return", "self", "end" ]
Deletes the contents of the repository. @yield [repo] If a block is given, it will be passed the repository after it's contents have been deleted. @yieldparam [Repository] repo The deleted repository. @return [Repository] The deleted repository. @since 1.0.0 @api private
[ "Deletes", "the", "contents", "of", "the", "repository", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/repository.rb#L685-L698
22,027
ronin-ruby/ronin
lib/ronin/password.rb
Ronin.Password.digest
def digest(algorithm,options={}) digest_class = begin Digest.const_get(algorithm.to_s.upcase) rescue LoadError raise(ArgumentError,"Unknown Digest algorithm #{algorithm}") end hash = digest_class.new if options[:prepend_salt] hash << options[:prepend_salt].to_s end hash << self.clear_text if options[:append_salt] hash << options[:append_salt].to_s end return hash.hexdigest end
ruby
def digest(algorithm,options={}) digest_class = begin Digest.const_get(algorithm.to_s.upcase) rescue LoadError raise(ArgumentError,"Unknown Digest algorithm #{algorithm}") end hash = digest_class.new if options[:prepend_salt] hash << options[:prepend_salt].to_s end hash << self.clear_text if options[:append_salt] hash << options[:append_salt].to_s end return hash.hexdigest end
[ "def", "digest", "(", "algorithm", ",", "options", "=", "{", "}", ")", "digest_class", "=", "begin", "Digest", ".", "const_get", "(", "algorithm", ".", "to_s", ".", "upcase", ")", "rescue", "LoadError", "raise", "(", "ArgumentError", ",", "\"Unknown Digest algorithm #{algorithm}\"", ")", "end", "hash", "=", "digest_class", ".", "new", "if", "options", "[", ":prepend_salt", "]", "hash", "<<", "options", "[", ":prepend_salt", "]", ".", "to_s", "end", "hash", "<<", "self", ".", "clear_text", "if", "options", "[", ":append_salt", "]", "hash", "<<", "options", "[", ":append_salt", "]", ".", "to_s", "end", "return", "hash", ".", "hexdigest", "end" ]
Hashes the password. @param [Symbol, String] algorithm The digest algorithm to use. @param [Hash] options Additional options. @option options [String] :prepend_salt The salt data to prepend to the password. @option options [String] :append_salt The salt data to append to the password. @return [String] The hex-digest of the hashed password. @raise [ArgumentError] Unknown Digest algorithm. @example pass = Password.new(:clear_text => 'secret') pass.digest(:sha1) # => "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4" pass.digest(:sha1, :prepend_salt => "A\x90\x00") # => "e2817656a48c49f24839ccf9295b389d8f985904" pass.digest(:sha1, :append_salt => "BBBB") # => "aa6ca21e446d425fc044bbb26e950a788444a5b8" @since 1.0.0 @api public
[ "Hashes", "the", "password", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/password.rb#L100-L120
22,028
ronin-ruby/ronin
lib/ronin/mac_address.rb
Ronin.MACAddress.to_i
def to_i self.address.split(':').inject(0) do |bits,char| bits = ((bits << 8) | char.hex) end end
ruby
def to_i self.address.split(':').inject(0) do |bits,char| bits = ((bits << 8) | char.hex) end end
[ "def", "to_i", "self", ".", "address", ".", "split", "(", "':'", ")", ".", "inject", "(", "0", ")", "do", "|", "bits", ",", "char", "|", "bits", "=", "(", "(", "bits", "<<", "8", ")", "|", "char", ".", "hex", ")", "end", "end" ]
Converts the MAC address to an Integer. @return [Integer] The network representation of the MAC address. @since 1.0.0 @api public
[ "Converts", "the", "MAC", "address", "to", "an", "Integer", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/mac_address.rb#L104-L108
22,029
SeanNieuwoudt/plugg
lib/plugg.rb
Plugg.Dispatcher.start
def start(paths, params = {}) @registry = [] paths.each do |path| if path[-1] == '/' path.chop! end Dir["#{path}/*.rb"].each do |f| require File.expand_path(f) begin instance = Object.const_get(File.basename(f, '.rb')).new # `before` event callback if instance.respond_to?(:before) instance.send(:before) end # `setup` method if instance.respond_to?(:setup) instance.send(:setup, params) end @registry.push(instance) rescue Exception => e puts "#{f} Plugg Initialization Exception: #{e}" end end end end
ruby
def start(paths, params = {}) @registry = [] paths.each do |path| if path[-1] == '/' path.chop! end Dir["#{path}/*.rb"].each do |f| require File.expand_path(f) begin instance = Object.const_get(File.basename(f, '.rb')).new # `before` event callback if instance.respond_to?(:before) instance.send(:before) end # `setup` method if instance.respond_to?(:setup) instance.send(:setup, params) end @registry.push(instance) rescue Exception => e puts "#{f} Plugg Initialization Exception: #{e}" end end end end
[ "def", "start", "(", "paths", ",", "params", "=", "{", "}", ")", "@registry", "=", "[", "]", "paths", ".", "each", "do", "|", "path", "|", "if", "path", "[", "-", "1", "]", "==", "'/'", "path", ".", "chop!", "end", "Dir", "[", "\"#{path}/*.rb\"", "]", ".", "each", "do", "|", "f", "|", "require", "File", ".", "expand_path", "(", "f", ")", "begin", "instance", "=", "Object", ".", "const_get", "(", "File", ".", "basename", "(", "f", ",", "'.rb'", ")", ")", ".", "new", "# `before` event callback", "if", "instance", ".", "respond_to?", "(", ":before", ")", "instance", ".", "send", "(", ":before", ")", "end", "# `setup` method", "if", "instance", ".", "respond_to?", "(", ":setup", ")", "instance", ".", "send", "(", ":setup", ",", "params", ")", "end", "@registry", ".", "push", "(", "instance", ")", "rescue", "Exception", "=>", "e", "puts", "\"#{f} Plugg Initialization Exception: #{e}\"", "end", "end", "end", "end" ]
Assign a path where plugins should be loaded from @param mixed path @param hash params @return void
[ "Assign", "a", "path", "where", "plugins", "should", "be", "loaded", "from" ]
f078d76aa17aa651f4c89ba39553a5436e98384b
https://github.com/SeanNieuwoudt/plugg/blob/f078d76aa17aa651f4c89ba39553a5436e98384b/lib/plugg.rb#L126-L158
22,030
SeanNieuwoudt/plugg
lib/plugg.rb
Plugg.Dispatcher.on
def on(method, *args, &block) if [:initialize, :before, :setup, :after].include? method raise "#{method} should not be called directly" end buffer = [] # Container for the response buffer threads = [] # Container for the execution threads @registry.each do |s| if s.respond_to?(method.to_sym, false) threads << Thread.new do responder = DispatchResponder.new(s) responder.trap(@timeout) do if s.method(method.to_sym).arity == 0 s.send(method, &block) else s.send(method, *args, &block) end end responder.finalize buffer << responder.to_h end end end threads.map(&:join) buffer end
ruby
def on(method, *args, &block) if [:initialize, :before, :setup, :after].include? method raise "#{method} should not be called directly" end buffer = [] # Container for the response buffer threads = [] # Container for the execution threads @registry.each do |s| if s.respond_to?(method.to_sym, false) threads << Thread.new do responder = DispatchResponder.new(s) responder.trap(@timeout) do if s.method(method.to_sym).arity == 0 s.send(method, &block) else s.send(method, *args, &block) end end responder.finalize buffer << responder.to_h end end end threads.map(&:join) buffer end
[ "def", "on", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "[", ":initialize", ",", ":before", ",", ":setup", ",", ":after", "]", ".", "include?", "method", "raise", "\"#{method} should not be called directly\"", "end", "buffer", "=", "[", "]", "# Container for the response buffer ", "threads", "=", "[", "]", "# Container for the execution threads", "@registry", ".", "each", "do", "|", "s", "|", "if", "s", ".", "respond_to?", "(", "method", ".", "to_sym", ",", "false", ")", "threads", "<<", "Thread", ".", "new", "do", "responder", "=", "DispatchResponder", ".", "new", "(", "s", ")", "responder", ".", "trap", "(", "@timeout", ")", "do", "if", "s", ".", "method", "(", "method", ".", "to_sym", ")", ".", "arity", "==", "0", "s", ".", "send", "(", "method", ",", "block", ")", "else", "s", ".", "send", "(", "method", ",", "args", ",", "block", ")", "end", "end", "responder", ".", "finalize", "buffer", "<<", "responder", ".", "to_h", "end", "end", "end", "threads", ".", "map", "(", ":join", ")", "buffer", "end" ]
Initialize the dispatcher instance with a default timeout of 5s @return void Loop through all services and fire off the supported messages @param string method @return void
[ "Initialize", "the", "dispatcher", "instance", "with", "a", "default", "timeout", "of", "5s" ]
f078d76aa17aa651f4c89ba39553a5436e98384b
https://github.com/SeanNieuwoudt/plugg/blob/f078d76aa17aa651f4c89ba39553a5436e98384b/lib/plugg.rb#L182-L214
22,031
shunhikita/action_messenger
lib/action_messenger/base.rb
ActionMessenger.Base.message_to_slack
def message_to_slack(channel:, options: {}) @caller_method_name = caller[0][/`([^']*)'/, 1] options = apply_defaults(options) message = nil ActiveSupport::Notifications.instrument('message_to_slack.action_messenger', channel: channel, body: options[:text]) do message = slack_client.message(channel, options) end message ensure self.deliveries << DeliveryLog.new(__method__, channel, message) end
ruby
def message_to_slack(channel:, options: {}) @caller_method_name = caller[0][/`([^']*)'/, 1] options = apply_defaults(options) message = nil ActiveSupport::Notifications.instrument('message_to_slack.action_messenger', channel: channel, body: options[:text]) do message = slack_client.message(channel, options) end message ensure self.deliveries << DeliveryLog.new(__method__, channel, message) end
[ "def", "message_to_slack", "(", "channel", ":", ",", "options", ":", "{", "}", ")", "@caller_method_name", "=", "caller", "[", "0", "]", "[", "/", "/", ",", "1", "]", "options", "=", "apply_defaults", "(", "options", ")", "message", "=", "nil", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'message_to_slack.action_messenger'", ",", "channel", ":", "channel", ",", "body", ":", "options", "[", ":text", "]", ")", "do", "message", "=", "slack_client", ".", "message", "(", "channel", ",", "options", ")", "end", "message", "ensure", "self", ".", "deliveries", "<<", "DeliveryLog", ".", "new", "(", "__method__", ",", "channel", ",", "message", ")", "end" ]
message to slack @param [String] channel slack channel. ex. #general @param [Hash] options Slack API Request Options ex. https://api.slack.com/methods/chat.postMessage ex. message_to_slack(channel: '#general', options: {text: 'sample'})
[ "message", "to", "slack" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/base.rb#L51-L61
22,032
shunhikita/action_messenger
lib/action_messenger/base.rb
ActionMessenger.Base.upload_file_to_slack
def upload_file_to_slack(channels: ,file: ,options: {}) upload_file = nil ActiveSupport::Notifications.instrument('upload_file_to_slack.action_messenger', channels: channels) do upload_file = slack_client.upload_file(channels, file, options) end upload_file ensure self.deliveries << DeliveryLog.new(__method__, channels, upload_file) end
ruby
def upload_file_to_slack(channels: ,file: ,options: {}) upload_file = nil ActiveSupport::Notifications.instrument('upload_file_to_slack.action_messenger', channels: channels) do upload_file = slack_client.upload_file(channels, file, options) end upload_file ensure self.deliveries << DeliveryLog.new(__method__, channels, upload_file) end
[ "def", "upload_file_to_slack", "(", "channels", ":", ",", "file", ":", ",", "options", ":", "{", "}", ")", "upload_file", "=", "nil", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'upload_file_to_slack.action_messenger'", ",", "channels", ":", "channels", ")", "do", "upload_file", "=", "slack_client", ".", "upload_file", "(", "channels", ",", "file", ",", "options", ")", "end", "upload_file", "ensure", "self", ".", "deliveries", "<<", "DeliveryLog", ".", "new", "(", "__method__", ",", "channels", ",", "upload_file", ")", "end" ]
upload file to slack @param [String] channels slack channel ex. #general, #hoge @param [Faraday::UploadIO] file upload file ex. Faraday::UploadIO.new('/path/to/sample.jpg', 'image/jpg') @param [Hash] options
[ "upload", "file", "to", "slack" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/base.rb#L70-L78
22,033
tdak/worldcatapi
lib/worldcatapi/sru_search_response.rb
WORLDCATAPI.SruSearchResponse.extract_multiple
def extract_multiple(record, field, tag) a = Array.new record.fields(field).each do |field| a.push field[tag] end return a end
ruby
def extract_multiple(record, field, tag) a = Array.new record.fields(field).each do |field| a.push field[tag] end return a end
[ "def", "extract_multiple", "(", "record", ",", "field", ",", "tag", ")", "a", "=", "Array", ".", "new", "record", ".", "fields", "(", "field", ")", ".", "each", "do", "|", "field", "|", "a", ".", "push", "field", "[", "tag", "]", "end", "return", "a", "end" ]
Extract Multiple fields for record
[ "Extract", "Multiple", "fields", "for", "record" ]
ed6d0cb849e86a032dc84741a5d169da19b8e385
https://github.com/tdak/worldcatapi/blob/ed6d0cb849e86a032dc84741a5d169da19b8e385/lib/worldcatapi/sru_search_response.rb#L60-L66
22,034
conduit/conduit-braintree
lib/conduit/braintree/actions/base.rb
Conduit::Driver::Braintree.Base.perform
def perform body = perform_action parser = parser_class.new(body) Conduit::ApiResponse.new(raw_response: @raw_response, body: body, parser: parser) rescue Braintree::NotFoundError => error report_braintree_exceptions(error) rescue ArgumentError => error respond_with_error(error.message) rescue Braintree::BraintreeError => error report_braintree_exceptions(error) rescue Net::ReadTimeout, Net::OpenTimeout, Errno::ETIMEDOUT respond_with_error("Braintree timeout") end
ruby
def perform body = perform_action parser = parser_class.new(body) Conduit::ApiResponse.new(raw_response: @raw_response, body: body, parser: parser) rescue Braintree::NotFoundError => error report_braintree_exceptions(error) rescue ArgumentError => error respond_with_error(error.message) rescue Braintree::BraintreeError => error report_braintree_exceptions(error) rescue Net::ReadTimeout, Net::OpenTimeout, Errno::ETIMEDOUT respond_with_error("Braintree timeout") end
[ "def", "perform", "body", "=", "perform_action", "parser", "=", "parser_class", ".", "new", "(", "body", ")", "Conduit", "::", "ApiResponse", ".", "new", "(", "raw_response", ":", "@raw_response", ",", "body", ":", "body", ",", "parser", ":", "parser", ")", "rescue", "Braintree", "::", "NotFoundError", "=>", "error", "report_braintree_exceptions", "(", "error", ")", "rescue", "ArgumentError", "=>", "error", "respond_with_error", "(", "error", ".", "message", ")", "rescue", "Braintree", "::", "BraintreeError", "=>", "error", "report_braintree_exceptions", "(", "error", ")", "rescue", "Net", "::", "ReadTimeout", ",", "Net", "::", "OpenTimeout", ",", "Errno", "::", "ETIMEDOUT", "respond_with_error", "(", "\"Braintree timeout\"", ")", "end" ]
Performs the request, with mocking if requested
[ "Performs", "the", "request", "with", "mocking", "if", "requested" ]
67fd15ac223eb3118da5fe75177e9e6e42430504
https://github.com/conduit/conduit-braintree/blob/67fd15ac223eb3118da5fe75177e9e6e42430504/lib/conduit/braintree/actions/base.rb#L23-L35
22,035
daanforever/settingson
app/models/concerns/settingson/base.rb
Settingson::Base.ClassMethods.defaults
def defaults @__defaults = Settingson::Store::Default.new( klass: self ) if block_given? Rails.application.config.after_initialize do yield @__defaults end end @__defaults end
ruby
def defaults @__defaults = Settingson::Store::Default.new( klass: self ) if block_given? Rails.application.config.after_initialize do yield @__defaults end end @__defaults end
[ "def", "defaults", "@__defaults", "=", "Settingson", "::", "Store", "::", "Default", ".", "new", "(", "klass", ":", "self", ")", "if", "block_given?", "Rails", ".", "application", ".", "config", ".", "after_initialize", "do", "yield", "@__defaults", "end", "end", "@__defaults", "end" ]
Settings.defaults do |default| default.server.host = 'host' default.server.port = 80 end
[ "Settings", ".", "defaults", "do", "|default|", "default", ".", "server", ".", "host", "=", "host", "default", ".", "server", ".", "port", "=", "80", "end" ]
a3aa6ace98479841b6c9a6f3af7ed01a6cd7269e
https://github.com/daanforever/settingson/blob/a3aa6ace98479841b6c9a6f3af7ed01a6cd7269e/app/models/concerns/settingson/base.rb#L26-L36
22,036
ianpurvis/police_state
lib/police_state/transition_helpers.rb
PoliceState.TransitionHelpers.attribute_transitioning?
def attribute_transitioning?(attr, options={}) options = _transform_options_for_attribute(attr, options) attribute_changed?(attr, options) end
ruby
def attribute_transitioning?(attr, options={}) options = _transform_options_for_attribute(attr, options) attribute_changed?(attr, options) end
[ "def", "attribute_transitioning?", "(", "attr", ",", "options", "=", "{", "}", ")", "options", "=", "_transform_options_for_attribute", "(", "attr", ",", "options", ")", "attribute_changed?", "(", "attr", ",", "options", ")", "end" ]
Returns +true+ if +attribute+ is currently transitioning but not saved, otherwise +false+. You can specify origin and destination states using the +:from+ and +:to+ options. If +attribute+ is an +ActiveRecord::Enum+, these may be specified as either symbol or their native enum value. model = Model.new(status: :complete) # => #<Model:0x007fa94844d088 @status=:complete> model.status_transitioning? # => true model.status_transitioning?(from: nil) # => true model.status_transitioning?(to: :complete) # => true model.status_transitioning?(to: "complete") # => true model.status_transitioning?(from: nil, to: :complete) # => true
[ "Returns", "+", "true", "+", "if", "+", "attribute", "+", "is", "currently", "transitioning", "but", "not", "saved", "otherwise", "+", "false", "+", "." ]
d827e74a0b2eb2a698a018d5367fb63c49b6b699
https://github.com/ianpurvis/police_state/blob/d827e74a0b2eb2a698a018d5367fb63c49b6b699/lib/police_state/transition_helpers.rb#L54-L57
22,037
shunhikita/action_messenger
lib/action_messenger/message_delivery.rb
ActionMessenger.MessageDelivery.deliver_now!
def deliver_now! messenger.handle_exceptions do ActiveSupport::Notifications.instrument('deliver_now!.action_messenger', method_name: method_name, args: args) do if args.present? messenger.public_send(method_name, *args) else messenger.public_send(method_name) end end end end
ruby
def deliver_now! messenger.handle_exceptions do ActiveSupport::Notifications.instrument('deliver_now!.action_messenger', method_name: method_name, args: args) do if args.present? messenger.public_send(method_name, *args) else messenger.public_send(method_name) end end end end
[ "def", "deliver_now!", "messenger", ".", "handle_exceptions", "do", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'deliver_now!.action_messenger'", ",", "method_name", ":", "method_name", ",", "args", ":", "args", ")", "do", "if", "args", ".", "present?", "messenger", ".", "public_send", "(", "method_name", ",", "args", ")", "else", "messenger", ".", "public_send", "(", "method_name", ")", "end", "end", "end", "end" ]
send a message now
[ "send", "a", "message", "now" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/message_delivery.rb#L15-L25
22,038
shunhikita/action_messenger
lib/action_messenger/message_delivery.rb
ActionMessenger.MessageDelivery.deliver_later!
def deliver_later! ActionMessenger::MessageDeliveryJob.perform_later(self.class.name, 'deliver_now!', messenger_class.to_s, method_name.to_s, *args) end
ruby
def deliver_later! ActionMessenger::MessageDeliveryJob.perform_later(self.class.name, 'deliver_now!', messenger_class.to_s, method_name.to_s, *args) end
[ "def", "deliver_later!", "ActionMessenger", "::", "MessageDeliveryJob", ".", "perform_later", "(", "self", ".", "class", ".", "name", ",", "'deliver_now!'", ",", "messenger_class", ".", "to_s", ",", "method_name", ".", "to_s", ",", "args", ")", "end" ]
send a message asynchronously
[ "send", "a", "message", "asynchronously" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/message_delivery.rb#L28-L30
22,039
ateamlunchbox/graphql_grpc
lib/graphql_grpc/proxy.rb
GraphqlGrpc.Proxy.map_functions
def map_functions(stub_services) return @function_map unless @function_map.empty? stub_services.keys.each do |service_name| stub = @services[service_name] = stub_services[service_name] stub.class.to_s.gsub('::Stub', '::Service').constantize.rpc_descs.values.each do |d| next if d.name.to_sym == :Healthcheck grpc_func = ::GraphqlGrpc::Function.new(service_name, stub, d) if @function_map.key?(grpc_func.name) sn = @function_map[grpc_func.name].service_name STDERR.puts "Skipping method #{grpc_func.name}; it was already defined on #{sn}" # raise ConfigurationError, "#{grpc_func.name} was already defined on #{sn}." end @function_map[grpc_func.name] = grpc_func end end @function_map end
ruby
def map_functions(stub_services) return @function_map unless @function_map.empty? stub_services.keys.each do |service_name| stub = @services[service_name] = stub_services[service_name] stub.class.to_s.gsub('::Stub', '::Service').constantize.rpc_descs.values.each do |d| next if d.name.to_sym == :Healthcheck grpc_func = ::GraphqlGrpc::Function.new(service_name, stub, d) if @function_map.key?(grpc_func.name) sn = @function_map[grpc_func.name].service_name STDERR.puts "Skipping method #{grpc_func.name}; it was already defined on #{sn}" # raise ConfigurationError, "#{grpc_func.name} was already defined on #{sn}." end @function_map[grpc_func.name] = grpc_func end end @function_map end
[ "def", "map_functions", "(", "stub_services", ")", "return", "@function_map", "unless", "@function_map", ".", "empty?", "stub_services", ".", "keys", ".", "each", "do", "|", "service_name", "|", "stub", "=", "@services", "[", "service_name", "]", "=", "stub_services", "[", "service_name", "]", "stub", ".", "class", ".", "to_s", ".", "gsub", "(", "'::Stub'", ",", "'::Service'", ")", ".", "constantize", ".", "rpc_descs", ".", "values", ".", "each", "do", "|", "d", "|", "next", "if", "d", ".", "name", ".", "to_sym", "==", ":Healthcheck", "grpc_func", "=", "::", "GraphqlGrpc", "::", "Function", ".", "new", "(", "service_name", ",", "stub", ",", "d", ")", "if", "@function_map", ".", "key?", "(", "grpc_func", ".", "name", ")", "sn", "=", "@function_map", "[", "grpc_func", ".", "name", "]", ".", "service_name", "STDERR", ".", "puts", "\"Skipping method #{grpc_func.name}; it was already defined on #{sn}\"", "# raise ConfigurationError, \"#{grpc_func.name} was already defined on #{sn}.\"", "end", "@function_map", "[", "grpc_func", ".", "name", "]", "=", "grpc_func", "end", "end", "@function_map", "end" ]
Add to the function_map by inspecting each service for the RPCs it provides.
[ "Add", "to", "the", "function_map", "by", "inspecting", "each", "service", "for", "the", "RPCs", "it", "provides", "." ]
dfb51f32457584007ea03895d12f4e089f3a4946
https://github.com/ateamlunchbox/graphql_grpc/blob/dfb51f32457584007ea03895d12f4e089f3a4946/lib/graphql_grpc/proxy.rb#L85-L103
22,040
ateamlunchbox/graphql_grpc
lib/graphql_grpc/function.rb
GraphqlGrpc.Function.arg
def arg(params) rpc_desc.input.decode_json(params.reject { |k, _v| k == :selections }.to_json) end
ruby
def arg(params) rpc_desc.input.decode_json(params.reject { |k, _v| k == :selections }.to_json) end
[ "def", "arg", "(", "params", ")", "rpc_desc", ".", "input", ".", "decode_json", "(", "params", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", "==", ":selections", "}", ".", "to_json", ")", "end" ]
Build arguments to a func
[ "Build", "arguments", "to", "a", "func" ]
dfb51f32457584007ea03895d12f4e089f3a4946
https://github.com/ateamlunchbox/graphql_grpc/blob/dfb51f32457584007ea03895d12f4e089f3a4946/lib/graphql_grpc/function.rb#L108-L110
22,041
conduit/conduit-braintree
lib/conduit/braintree/actions/update_credit_card.rb
Conduit::Driver::Braintree.UpdateCreditCard.whitelist_options
def whitelist_options @options[:options] ||= {}.tap do |h| h[:verify_card] = @options.fetch(:verify_card, true) @options.delete(:verify_card) if @options.key?(:verification_merchant_account_id) h[:verification_merchant_account_id] = @options.delete(:verification_merchant_account_id) end end super end
ruby
def whitelist_options @options[:options] ||= {}.tap do |h| h[:verify_card] = @options.fetch(:verify_card, true) @options.delete(:verify_card) if @options.key?(:verification_merchant_account_id) h[:verification_merchant_account_id] = @options.delete(:verification_merchant_account_id) end end super end
[ "def", "whitelist_options", "@options", "[", ":options", "]", "||=", "{", "}", ".", "tap", "do", "|", "h", "|", "h", "[", ":verify_card", "]", "=", "@options", ".", "fetch", "(", ":verify_card", ",", "true", ")", "@options", ".", "delete", "(", ":verify_card", ")", "if", "@options", ".", "key?", "(", ":verification_merchant_account_id", ")", "h", "[", ":verification_merchant_account_id", "]", "=", "@options", ".", "delete", "(", ":verification_merchant_account_id", ")", "end", "end", "super", "end" ]
Request verification when the card is stored, using the merchant account id if one is provided
[ "Request", "verification", "when", "the", "card", "is", "stored", "using", "the", "merchant", "account", "id", "if", "one", "is", "provided" ]
67fd15ac223eb3118da5fe75177e9e6e42430504
https://github.com/conduit/conduit-braintree/blob/67fd15ac223eb3118da5fe75177e9e6e42430504/lib/conduit/braintree/actions/update_credit_card.rb#L27-L36
22,042
robmiller/ruby-wpdb
lib/ruby-wpdb/term.rb
WPDB.Termable.add_term
def add_term(term, taxonomy, description, count) if term.respond_to?(:term_id) term_id = term.term_id else term_id = term.to_i end term_taxonomy = WPDB::TermTaxonomy.where(term_id: term_id, taxonomy: taxonomy).first unless term_taxonomy term_taxonomy = WPDB::TermTaxonomy.create( term_id: term_id, taxonomy: taxonomy, description: description, count: count ) else term_taxonomy.count += count end add_termtaxonomy(term_taxonomy) end
ruby
def add_term(term, taxonomy, description, count) if term.respond_to?(:term_id) term_id = term.term_id else term_id = term.to_i end term_taxonomy = WPDB::TermTaxonomy.where(term_id: term_id, taxonomy: taxonomy).first unless term_taxonomy term_taxonomy = WPDB::TermTaxonomy.create( term_id: term_id, taxonomy: taxonomy, description: description, count: count ) else term_taxonomy.count += count end add_termtaxonomy(term_taxonomy) end
[ "def", "add_term", "(", "term", ",", "taxonomy", ",", "description", ",", "count", ")", "if", "term", ".", "respond_to?", "(", ":term_id", ")", "term_id", "=", "term", ".", "term_id", "else", "term_id", "=", "term", ".", "to_i", "end", "term_taxonomy", "=", "WPDB", "::", "TermTaxonomy", ".", "where", "(", "term_id", ":", "term_id", ",", "taxonomy", ":", "taxonomy", ")", ".", "first", "unless", "term_taxonomy", "term_taxonomy", "=", "WPDB", "::", "TermTaxonomy", ".", "create", "(", "term_id", ":", "term_id", ",", "taxonomy", ":", "taxonomy", ",", "description", ":", "description", ",", "count", ":", "count", ")", "else", "term_taxonomy", ".", "count", "+=", "count", "end", "add_termtaxonomy", "(", "term_taxonomy", ")", "end" ]
For objects that have a relationship with termtaxonomies, this module can be mixed in and gives the ability to add a term directly to the model, rather than creating the relationship yourself. Used by Post and Link.
[ "For", "objects", "that", "have", "a", "relationship", "with", "termtaxonomies", "this", "module", "can", "be", "mixed", "in", "and", "gives", "the", "ability", "to", "add", "a", "term", "directly", "to", "the", "model", "rather", "than", "creating", "the", "relationship", "yourself", ".", "Used", "by", "Post", "and", "Link", "." ]
2252be12baa3b9607c26fc8cc5e167ae3b82a94d
https://github.com/robmiller/ruby-wpdb/blob/2252be12baa3b9607c26fc8cc5e167ae3b82a94d/lib/ruby-wpdb/term.rb#L19-L39
22,043
TailorBrands/noun-project-api
lib/noun-project-api/retriever.rb
NounProjectApi.Retriever.find
def find(id) raise ArgumentError.new("Missing id/slug") unless id result = access_token.get("#{API_BASE}#{self.class::API_PATH}#{id}") raise ServiceError.new(result.code, result.body) unless result.code == "200" self.class::ITEM_CLASS.new(result.body) end
ruby
def find(id) raise ArgumentError.new("Missing id/slug") unless id result = access_token.get("#{API_BASE}#{self.class::API_PATH}#{id}") raise ServiceError.new(result.code, result.body) unless result.code == "200" self.class::ITEM_CLASS.new(result.body) end
[ "def", "find", "(", "id", ")", "raise", "ArgumentError", ".", "new", "(", "\"Missing id/slug\"", ")", "unless", "id", "result", "=", "access_token", ".", "get", "(", "\"#{API_BASE}#{self.class::API_PATH}#{id}\"", ")", "raise", "ServiceError", ".", "new", "(", "result", ".", "code", ",", "result", ".", "body", ")", "unless", "result", ".", "code", "==", "\"200\"", "self", ".", "class", "::", "ITEM_CLASS", ".", "new", "(", "result", ".", "body", ")", "end" ]
Find an item based on it's id.
[ "Find", "an", "item", "based", "on", "it", "s", "id", "." ]
b4fbd0836fd80aee843af03569bdfa2a6ffe79f9
https://github.com/TailorBrands/noun-project-api/blob/b4fbd0836fd80aee843af03569bdfa2a6ffe79f9/lib/noun-project-api/retriever.rb#L7-L14
22,044
vaharoni/trusted-sandbox
lib/trusted_sandbox/uid_pool.rb
TrustedSandbox.UidPool.lock
def lock retries.times do atomically(timeout) do uid = available_uid if uid lock_uid uid return uid.to_i end end sleep(delay) end raise PoolTimeoutError.new('No available UIDs in the pool. Please try again later.') end
ruby
def lock retries.times do atomically(timeout) do uid = available_uid if uid lock_uid uid return uid.to_i end end sleep(delay) end raise PoolTimeoutError.new('No available UIDs in the pool. Please try again later.') end
[ "def", "lock", "retries", ".", "times", "do", "atomically", "(", "timeout", ")", "do", "uid", "=", "available_uid", "if", "uid", "lock_uid", "uid", "return", "uid", ".", "to_i", "end", "end", "sleep", "(", "delay", ")", "end", "raise", "PoolTimeoutError", ".", "new", "(", "'No available UIDs in the pool. Please try again later.'", ")", "end" ]
Locks one UID from the pool, in a cross-process atomic manner @return [Integer] @raise [PoolTimeoutError] if no ID is available after retries
[ "Locks", "one", "UID", "from", "the", "pool", "in", "a", "cross", "-", "process", "atomic", "manner" ]
e5d5e99bebfeab9e88c2512e30742b392bc09677
https://github.com/vaharoni/trusted-sandbox/blob/e5d5e99bebfeab9e88c2512e30742b392bc09677/lib/trusted_sandbox/uid_pool.rb#L56-L68
22,045
vaharoni/trusted-sandbox
lib/trusted_sandbox/response.rb
TrustedSandbox.Response.parse!
def parse! unless File.exists? output_file_path @status = 'error' @error = ContainerError.new('User code did not finish properly') @error_to_raise = @error return end begin data = File.binread output_file_path @raw_response = Marshal.load(data) rescue => e @status = 'error' @error = e @error_to_raise = ContainerError.new(e) return end unless ['success', 'error'].include? @raw_response[:status] @status = 'error' @error = InternalError.new('Output file has invalid format') @error_to_raise = @error return end @status = @raw_response[:status] @output = @raw_response[:output] @error = @raw_response[:error] @error_to_raise = UserCodeError.new(@error) if @error nil end
ruby
def parse! unless File.exists? output_file_path @status = 'error' @error = ContainerError.new('User code did not finish properly') @error_to_raise = @error return end begin data = File.binread output_file_path @raw_response = Marshal.load(data) rescue => e @status = 'error' @error = e @error_to_raise = ContainerError.new(e) return end unless ['success', 'error'].include? @raw_response[:status] @status = 'error' @error = InternalError.new('Output file has invalid format') @error_to_raise = @error return end @status = @raw_response[:status] @output = @raw_response[:output] @error = @raw_response[:error] @error_to_raise = UserCodeError.new(@error) if @error nil end
[ "def", "parse!", "unless", "File", ".", "exists?", "output_file_path", "@status", "=", "'error'", "@error", "=", "ContainerError", ".", "new", "(", "'User code did not finish properly'", ")", "@error_to_raise", "=", "@error", "return", "end", "begin", "data", "=", "File", ".", "binread", "output_file_path", "@raw_response", "=", "Marshal", ".", "load", "(", "data", ")", "rescue", "=>", "e", "@status", "=", "'error'", "@error", "=", "e", "@error_to_raise", "=", "ContainerError", ".", "new", "(", "e", ")", "return", "end", "unless", "[", "'success'", ",", "'error'", "]", ".", "include?", "@raw_response", "[", ":status", "]", "@status", "=", "'error'", "@error", "=", "InternalError", ".", "new", "(", "'Output file has invalid format'", ")", "@error_to_raise", "=", "@error", "return", "end", "@status", "=", "@raw_response", "[", ":status", "]", "@output", "=", "@raw_response", "[", ":output", "]", "@error", "=", "@raw_response", "[", ":error", "]", "@error_to_raise", "=", "UserCodeError", ".", "new", "(", "@error", ")", "if", "@error", "nil", "end" ]
Parses the output file and stores the values in the appropriate ivars @return [nil]
[ "Parses", "the", "output", "file", "and", "stores", "the", "values", "in", "the", "appropriate", "ivars" ]
e5d5e99bebfeab9e88c2512e30742b392bc09677
https://github.com/vaharoni/trusted-sandbox/blob/e5d5e99bebfeab9e88c2512e30742b392bc09677/lib/trusted_sandbox/response.rb#L64-L94
22,046
trishume/pro
lib/pro/commands.rb
Pro.Commands.find_repo
def find_repo(name) return @index.base_dirs.first unless name match = FuzzyMatch.new(@index.to_a, :read => :name).find(name) match[1] unless match.nil? end
ruby
def find_repo(name) return @index.base_dirs.first unless name match = FuzzyMatch.new(@index.to_a, :read => :name).find(name) match[1] unless match.nil? end
[ "def", "find_repo", "(", "name", ")", "return", "@index", ".", "base_dirs", ".", "first", "unless", "name", "match", "=", "FuzzyMatch", ".", "new", "(", "@index", ".", "to_a", ",", ":read", "=>", ":name", ")", ".", "find", "(", "name", ")", "match", "[", "1", "]", "unless", "match", ".", "nil?", "end" ]
Fuzzy search for a git repository by name Returns the full path to the repository. If name is nil return the pro base.
[ "Fuzzy", "search", "for", "a", "git", "repository", "by", "name", "Returns", "the", "full", "path", "to", "the", "repository", "." ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L46-L50
22,047
trishume/pro
lib/pro/commands.rb
Pro.Commands.status
def status() max_name = @index.map {|repo| repo.name.length}.max + 1 @index.each do |r| next unless Dir.exists?(r.path) status = repo_status(r.path) next if status.empty? name = format("%-#{max_name}s",r.name).bold puts "#{name} > #{status}" end end
ruby
def status() max_name = @index.map {|repo| repo.name.length}.max + 1 @index.each do |r| next unless Dir.exists?(r.path) status = repo_status(r.path) next if status.empty? name = format("%-#{max_name}s",r.name).bold puts "#{name} > #{status}" end end
[ "def", "status", "(", ")", "max_name", "=", "@index", ".", "map", "{", "|", "repo", "|", "repo", ".", "name", ".", "length", "}", ".", "max", "+", "1", "@index", ".", "each", "do", "|", "r", "|", "next", "unless", "Dir", ".", "exists?", "(", "r", ".", "path", ")", "status", "=", "repo_status", "(", "r", ".", "path", ")", "next", "if", "status", ".", "empty?", "name", "=", "format", "(", "\"%-#{max_name}s\"", ",", "r", ".", "name", ")", ".", "bold", "puts", "\"#{name} > #{status}\"", "end", "end" ]
prints a status list showing repos with unpushed commits or uncommitted changes
[ "prints", "a", "status", "list", "showing", "repos", "with", "unpushed", "commits", "or", "uncommitted", "changes" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L88-L97
22,048
trishume/pro
lib/pro/commands.rb
Pro.Commands.repo_status
def repo_status(path) messages = [] messages << EMPTY_MESSAGE if repo_empty?(path) messages << UNCOMMITTED_MESSAGE if commit_pending?(path) messages << UNTRACKED_MESSAGE if untracked_files?(path) messages << UNPUSHED_MESSAGE if repo_unpushed?(path) messages.join(JOIN_STRING) end
ruby
def repo_status(path) messages = [] messages << EMPTY_MESSAGE if repo_empty?(path) messages << UNCOMMITTED_MESSAGE if commit_pending?(path) messages << UNTRACKED_MESSAGE if untracked_files?(path) messages << UNPUSHED_MESSAGE if repo_unpushed?(path) messages.join(JOIN_STRING) end
[ "def", "repo_status", "(", "path", ")", "messages", "=", "[", "]", "messages", "<<", "EMPTY_MESSAGE", "if", "repo_empty?", "(", "path", ")", "messages", "<<", "UNCOMMITTED_MESSAGE", "if", "commit_pending?", "(", "path", ")", "messages", "<<", "UNTRACKED_MESSAGE", "if", "untracked_files?", "(", "path", ")", "messages", "<<", "UNPUSHED_MESSAGE", "if", "repo_unpushed?", "(", "path", ")", "messages", ".", "join", "(", "JOIN_STRING", ")", "end" ]
returns a short status message for the repo
[ "returns", "a", "short", "status", "message", "for", "the", "repo" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L100-L107
22,049
trishume/pro
lib/pro/commands.rb
Pro.Commands.install_cd
def install_cd puts CD_INFO print "Continue with installation (yN)? " return unless gets.chomp.downcase == "y" # get name print "Name of pro cd command (default 'pd'): " name = gets.strip name = 'pd' if name.empty? # sub into function func = SHELL_FUNCTION.sub("{{name}}",name) did_any = false ['~/.profile', '~/.bashrc','~/.zshrc','~/.bash_profile'].each do |rel_path| # check if file exists path = File.expand_path(rel_path) next unless File.exists?(path) # ask the user if they want to add it print "Install #{name} function to #{rel_path} [yN]: " next unless gets.chomp.downcase == "y" # add it on to the end of the file File.open(path,'a') do |file| file.puts func end did_any = true end if did_any puts "Done! #{name} will be available in new shells." else STDERR.puts "WARNING: Did not install in any shell dotfiles.".red STDERR.puts "Maybe you should create the shell config file you want.".red end end
ruby
def install_cd puts CD_INFO print "Continue with installation (yN)? " return unless gets.chomp.downcase == "y" # get name print "Name of pro cd command (default 'pd'): " name = gets.strip name = 'pd' if name.empty? # sub into function func = SHELL_FUNCTION.sub("{{name}}",name) did_any = false ['~/.profile', '~/.bashrc','~/.zshrc','~/.bash_profile'].each do |rel_path| # check if file exists path = File.expand_path(rel_path) next unless File.exists?(path) # ask the user if they want to add it print "Install #{name} function to #{rel_path} [yN]: " next unless gets.chomp.downcase == "y" # add it on to the end of the file File.open(path,'a') do |file| file.puts func end did_any = true end if did_any puts "Done! #{name} will be available in new shells." else STDERR.puts "WARNING: Did not install in any shell dotfiles.".red STDERR.puts "Maybe you should create the shell config file you want.".red end end
[ "def", "install_cd", "puts", "CD_INFO", "print", "\"Continue with installation (yN)? \"", "return", "unless", "gets", ".", "chomp", ".", "downcase", "==", "\"y\"", "# get name", "print", "\"Name of pro cd command (default 'pd'): \"", "name", "=", "gets", ".", "strip", "name", "=", "'pd'", "if", "name", ".", "empty?", "# sub into function", "func", "=", "SHELL_FUNCTION", ".", "sub", "(", "\"{{name}}\"", ",", "name", ")", "did_any", "=", "false", "[", "'~/.profile'", ",", "'~/.bashrc'", ",", "'~/.zshrc'", ",", "'~/.bash_profile'", "]", ".", "each", "do", "|", "rel_path", "|", "# check if file exists", "path", "=", "File", ".", "expand_path", "(", "rel_path", ")", "next", "unless", "File", ".", "exists?", "(", "path", ")", "# ask the user if they want to add it", "print", "\"Install #{name} function to #{rel_path} [yN]: \"", "next", "unless", "gets", ".", "chomp", ".", "downcase", "==", "\"y\"", "# add it on to the end of the file", "File", ".", "open", "(", "path", ",", "'a'", ")", "do", "|", "file", "|", "file", ".", "puts", "func", "end", "did_any", "=", "true", "end", "if", "did_any", "puts", "\"Done! #{name} will be available in new shells.\"", "else", "STDERR", ".", "puts", "\"WARNING: Did not install in any shell dotfiles.\"", ".", "red", "STDERR", ".", "puts", "\"Maybe you should create the shell config file you want.\"", ".", "red", "end", "end" ]
Adds a shell function to the shell config files that allows easy directory changing.
[ "Adds", "a", "shell", "function", "to", "the", "shell", "config", "files", "that", "allows", "easy", "directory", "changing", "." ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L149-L179
22,050
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.read_cache
def read_cache return nil unless File.readable_real?(CACHE_PATH) index = YAML::load_file(CACHE_PATH) return nil unless index.created_version == Pro::VERSION return nil unless index.base_dirs == @base_dirs index end
ruby
def read_cache return nil unless File.readable_real?(CACHE_PATH) index = YAML::load_file(CACHE_PATH) return nil unless index.created_version == Pro::VERSION return nil unless index.base_dirs == @base_dirs index end
[ "def", "read_cache", "return", "nil", "unless", "File", ".", "readable_real?", "(", "CACHE_PATH", ")", "index", "=", "YAML", "::", "load_file", "(", "CACHE_PATH", ")", "return", "nil", "unless", "index", ".", "created_version", "==", "Pro", "::", "VERSION", "return", "nil", "unless", "index", ".", "base_dirs", "==", "@base_dirs", "index", "end" ]
unserializes the cache file and returns the index object
[ "unserializes", "the", "cache", "file", "and", "returns", "the", "index", "object" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L28-L34
22,051
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.run_index_process
def run_index_process readme, writeme = IO.pipe p1 = fork { # Stop cd function from blocking on fork STDOUT.reopen(writeme) readme.close index_process unless File.exists?(INDEXER_LOCK_PATH) } Process.detach(p1) end
ruby
def run_index_process readme, writeme = IO.pipe p1 = fork { # Stop cd function from blocking on fork STDOUT.reopen(writeme) readme.close index_process unless File.exists?(INDEXER_LOCK_PATH) } Process.detach(p1) end
[ "def", "run_index_process", "readme", ",", "writeme", "=", "IO", ".", "pipe", "p1", "=", "fork", "{", "# Stop cd function from blocking on fork", "STDOUT", ".", "reopen", "(", "writeme", ")", "readme", ".", "close", "index_process", "unless", "File", ".", "exists?", "(", "INDEXER_LOCK_PATH", ")", "}", "Process", ".", "detach", "(", "p1", ")", "end" ]
spins off a background process to update the cache file
[ "spins", "off", "a", "background", "process", "to", "update", "the", "cache", "file" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L37-L47
22,052
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.cache_index
def cache_index(index) # TODO: atomic rename. Right now we just hope. File.open(CACHE_PATH, 'w' ) do |out| YAML::dump( index, out ) end end
ruby
def cache_index(index) # TODO: atomic rename. Right now we just hope. File.open(CACHE_PATH, 'w' ) do |out| YAML::dump( index, out ) end end
[ "def", "cache_index", "(", "index", ")", "# TODO: atomic rename. Right now we just hope.", "File", ".", "open", "(", "CACHE_PATH", ",", "'w'", ")", "do", "|", "out", "|", "YAML", "::", "dump", "(", "index", ",", "out", ")", "end", "end" ]
serialize the index to a cache file
[ "serialize", "the", "index", "to", "a", "cache", "file" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L70-L75
22,053
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.index_repos_slow
def index_repos_slow(base) STDERR.puts "WARNING: pro is indexing slowly, please install the 'find' command." repos = [] Find.find(base) do |path| target = path # additionally, index repos symlinked directly from a base root if FileTest.symlink?(path) next if File.dirname(path) != base target = File.readlink(path) end # dir must exist and be a git repo if FileTest.directory?(target) && File.exists?(path+"/.git") base_name = File.basename(path) repos << Repo.new(base_name,path) Find.prune end end repos end
ruby
def index_repos_slow(base) STDERR.puts "WARNING: pro is indexing slowly, please install the 'find' command." repos = [] Find.find(base) do |path| target = path # additionally, index repos symlinked directly from a base root if FileTest.symlink?(path) next if File.dirname(path) != base target = File.readlink(path) end # dir must exist and be a git repo if FileTest.directory?(target) && File.exists?(path+"/.git") base_name = File.basename(path) repos << Repo.new(base_name,path) Find.prune end end repos end
[ "def", "index_repos_slow", "(", "base", ")", "STDERR", ".", "puts", "\"WARNING: pro is indexing slowly, please install the 'find' command.\"", "repos", "=", "[", "]", "Find", ".", "find", "(", "base", ")", "do", "|", "path", "|", "target", "=", "path", "# additionally, index repos symlinked directly from a base root", "if", "FileTest", ".", "symlink?", "(", "path", ")", "next", "if", "File", ".", "dirname", "(", "path", ")", "!=", "base", "target", "=", "File", ".", "readlink", "(", "path", ")", "end", "# dir must exist and be a git repo", "if", "FileTest", ".", "directory?", "(", "target", ")", "&&", "File", ".", "exists?", "(", "path", "+", "\"/.git\"", ")", "base_name", "=", "File", ".", "basename", "(", "path", ")", "repos", "<<", "Repo", ".", "new", "(", "base_name", ",", "path", ")", "Find", ".", "prune", "end", "end", "repos", "end" ]
recursive walk in ruby
[ "recursive", "walk", "in", "ruby" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L129-L147
22,054
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.find_base_dirs
def find_base_dirs() bases = [] # check environment first base = ENV['PRO_BASE'] bases << base if base # next check proBase file path = ENV['HOME'] + "/.proBase" if File.exists?(path) # read lines of the pro base file bases += IO.read(path).split("\n").map {|p| File.expand_path(p.strip)} end # strip bases that do not exist # I know about select! but it doesn't exist in 1.8 bases = bases.select {|b| File.exists?(b)} # if no bases then return home bases << ENV['HOME'] if bases.empty? bases end
ruby
def find_base_dirs() bases = [] # check environment first base = ENV['PRO_BASE'] bases << base if base # next check proBase file path = ENV['HOME'] + "/.proBase" if File.exists?(path) # read lines of the pro base file bases += IO.read(path).split("\n").map {|p| File.expand_path(p.strip)} end # strip bases that do not exist # I know about select! but it doesn't exist in 1.8 bases = bases.select {|b| File.exists?(b)} # if no bases then return home bases << ENV['HOME'] if bases.empty? bases end
[ "def", "find_base_dirs", "(", ")", "bases", "=", "[", "]", "# check environment first", "base", "=", "ENV", "[", "'PRO_BASE'", "]", "bases", "<<", "base", "if", "base", "# next check proBase file", "path", "=", "ENV", "[", "'HOME'", "]", "+", "\"/.proBase\"", "if", "File", ".", "exists?", "(", "path", ")", "# read lines of the pro base file", "bases", "+=", "IO", ".", "read", "(", "path", ")", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "p", "|", "File", ".", "expand_path", "(", "p", ".", "strip", ")", "}", "end", "# strip bases that do not exist", "# I know about select! but it doesn't exist in 1.8", "bases", "=", "bases", ".", "select", "{", "|", "b", "|", "File", ".", "exists?", "(", "b", ")", "}", "# if no bases then return home", "bases", "<<", "ENV", "[", "'HOME'", "]", "if", "bases", ".", "empty?", "bases", "end" ]
Finds the base directory where repos are kept Checks the environment variable PRO_BASE and the file .proBase
[ "Finds", "the", "base", "directory", "where", "repos", "are", "kept", "Checks", "the", "environment", "variable", "PRO_BASE", "and", "the", "file", ".", "proBase" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L152-L169
22,055
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.artifact_sign
def artifact_sign @signature = 'unsigned' # Clean up the existing signature file signature_cleanup Dir.chdir("#{$config['general']['app_cache']}/artifacts/") do # Generate the signature file and pick up the signature data unless system "gpg --use-agent --detach-sign artifact.#{@checksum}.tar.gz" $logger.error 'Unable to sign the artifact, an unexpected failure occured. No file uploaded.' return false end if File.exist?("artifact.#{@checksum}.tar.gz.sig") $logger.info 'A signature file was successfully generated.' else $logger.error 'A signature file was NOT generated.' return false end # Convert the signature into base64. It's easier to bundle all the # metadata into a single file and extracting it out when needed, than # having to keep track of yet-another-file. Because we encode into # ASCII here, no need to call GPG with --armor either. @signature = Base64.encode64(File.read("artifact.#{@checksum}.tar.gz.sig")) unless @signature $logger.error 'An unexpected issue occured and no signature was generated' return false end end # Make sure the public key has been uploaded if it hasn't already pubkey_upload @signature end
ruby
def artifact_sign @signature = 'unsigned' # Clean up the existing signature file signature_cleanup Dir.chdir("#{$config['general']['app_cache']}/artifacts/") do # Generate the signature file and pick up the signature data unless system "gpg --use-agent --detach-sign artifact.#{@checksum}.tar.gz" $logger.error 'Unable to sign the artifact, an unexpected failure occured. No file uploaded.' return false end if File.exist?("artifact.#{@checksum}.tar.gz.sig") $logger.info 'A signature file was successfully generated.' else $logger.error 'A signature file was NOT generated.' return false end # Convert the signature into base64. It's easier to bundle all the # metadata into a single file and extracting it out when needed, than # having to keep track of yet-another-file. Because we encode into # ASCII here, no need to call GPG with --armor either. @signature = Base64.encode64(File.read("artifact.#{@checksum}.tar.gz.sig")) unless @signature $logger.error 'An unexpected issue occured and no signature was generated' return false end end # Make sure the public key has been uploaded if it hasn't already pubkey_upload @signature end
[ "def", "artifact_sign", "@signature", "=", "'unsigned'", "# Clean up the existing signature file", "signature_cleanup", "Dir", ".", "chdir", "(", "\"#{$config['general']['app_cache']}/artifacts/\"", ")", "do", "# Generate the signature file and pick up the signature data", "unless", "system", "\"gpg --use-agent --detach-sign artifact.#{@checksum}.tar.gz\"", "$logger", ".", "error", "'Unable to sign the artifact, an unexpected failure occured. No file uploaded.'", "return", "false", "end", "if", "File", ".", "exist?", "(", "\"artifact.#{@checksum}.tar.gz.sig\"", ")", "$logger", ".", "info", "'A signature file was successfully generated.'", "else", "$logger", ".", "error", "'A signature file was NOT generated.'", "return", "false", "end", "# Convert the signature into base64. It's easier to bundle all the", "# metadata into a single file and extracting it out when needed, than", "# having to keep track of yet-another-file. Because we encode into", "# ASCII here, no need to call GPG with --armor either.", "@signature", "=", "Base64", ".", "encode64", "(", "File", ".", "read", "(", "\"artifact.#{@checksum}.tar.gz.sig\"", ")", ")", "unless", "@signature", "$logger", ".", "error", "'An unexpected issue occured and no signature was generated'", "return", "false", "end", "end", "# Make sure the public key has been uploaded if it hasn't already", "pubkey_upload", "@signature", "end" ]
Sign the artifact and return the signature. Does not validation of the signature. false Failure base64 Encoded signature
[ "Sign", "the", "artifact", "and", "return", "the", "signature", ".", "Does", "not", "validation", "of", "the", "signature", "." ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L37-L74
22,056
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.signature_extract
def signature_extract manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) if manifest['gpgsig'] # We have the base64 version @signature = manifest['gpgsig'] # Decode the base64 and write the signature file File.write("#{$config['general']['app_cache']}/artifacts/artifact.#{@checksum}.tar.gz.sig", Base64.decode64(@signature)) return @signature else return false end rescue StandardError => e $logger.error 'Something unexpected occured when reading the manifest file' raise e end
ruby
def signature_extract manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) if manifest['gpgsig'] # We have the base64 version @signature = manifest['gpgsig'] # Decode the base64 and write the signature file File.write("#{$config['general']['app_cache']}/artifacts/artifact.#{@checksum}.tar.gz.sig", Base64.decode64(@signature)) return @signature else return false end rescue StandardError => e $logger.error 'Something unexpected occured when reading the manifest file' raise e end
[ "def", "signature_extract", "manifest", "=", "YAML", ".", "load", "(", "File", ".", "open", "(", "$config", "[", "'general'", "]", "[", "'app_cache'", "]", "+", "\"/artifacts/manifest.#{@checksum}.yaml\"", ")", ",", "safe", ":", "true", ",", "raise_on_unknown_tag", ":", "true", ")", "if", "manifest", "[", "'gpgsig'", "]", "# We have the base64 version", "@signature", "=", "manifest", "[", "'gpgsig'", "]", "# Decode the base64 and write the signature file", "File", ".", "write", "(", "\"#{$config['general']['app_cache']}/artifacts/artifact.#{@checksum}.tar.gz.sig\"", ",", "Base64", ".", "decode64", "(", "@signature", ")", ")", "return", "@signature", "else", "return", "false", "end", "rescue", "StandardError", "=>", "e", "$logger", ".", "error", "'Something unexpected occured when reading the manifest file'", "raise", "e", "end" ]
Extract the signature from the manifest file and write it to file in native binary format. false Unable to extract unsigned Manifest shows that the artifact is not signed base64 Encoded signature
[ "Extract", "the", "signature", "from", "the", "manifest", "file", "and", "write", "it", "to", "file", "in", "native", "binary", "format", "." ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L136-L154
22,057
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.signature_save
def signature_save manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) manifest['gpgsig'] = @signature File.open("#{$config['general']['app_cache']}/artifacts/manifest.#{@checksum}.yaml", 'w') do |fh| fh.write YAML.dump(manifest) end return true rescue StandardError $logger.error 'Something unexpected occured when updating the manifest file with GPG signature' return false end
ruby
def signature_save manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) manifest['gpgsig'] = @signature File.open("#{$config['general']['app_cache']}/artifacts/manifest.#{@checksum}.yaml", 'w') do |fh| fh.write YAML.dump(manifest) end return true rescue StandardError $logger.error 'Something unexpected occured when updating the manifest file with GPG signature' return false end
[ "def", "signature_save", "manifest", "=", "YAML", ".", "load", "(", "File", ".", "open", "(", "$config", "[", "'general'", "]", "[", "'app_cache'", "]", "+", "\"/artifacts/manifest.#{@checksum}.yaml\"", ")", ",", "safe", ":", "true", ",", "raise_on_unknown_tag", ":", "true", ")", "manifest", "[", "'gpgsig'", "]", "=", "@signature", "File", ".", "open", "(", "\"#{$config['general']['app_cache']}/artifacts/manifest.#{@checksum}.yaml\"", ",", "'w'", ")", "do", "|", "fh", "|", "fh", ".", "write", "YAML", ".", "dump", "(", "manifest", ")", "end", "return", "true", "rescue", "StandardError", "$logger", ".", "error", "'Something unexpected occured when updating the manifest file with GPG signature'", "return", "false", "end" ]
Save the signature into the manifest file
[ "Save", "the", "signature", "into", "the", "manifest", "file" ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L158-L171
22,058
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.pubkey_upload
def pubkey_upload unless File.exist?("#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey") # GPG key does not exist locally, we therefore assume it's not in the S3 # bucket either, so we should export out and upload. Technically this may # result in a few extra uploads (once for any new machine using Pupistry) # but it doesn't cause any issue and saves me writing more code ;-) $logger.info "Exporting GPG key #{$config['general']['gpg_signing_key']} and uploading to S3 bucket..." # If it doesn't exist on this machine, then we're a bit stuck! unless pubkey_exist? $logger.error "The public key #{$config['general']['gpg_signing_key']} does not exist on this system, so unable to export it out" return false end # Export out key unless system "gpg --export --armour 0x#{$config['general']['gpg_signing_key']} > #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'A fault occured when trying to export the GPG key' return false end # Upload s3 = Pupistry::StorageAWS.new 'build' unless s3.upload "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to upload GPG key to S3 bucket' return false end end end
ruby
def pubkey_upload unless File.exist?("#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey") # GPG key does not exist locally, we therefore assume it's not in the S3 # bucket either, so we should export out and upload. Technically this may # result in a few extra uploads (once for any new machine using Pupistry) # but it doesn't cause any issue and saves me writing more code ;-) $logger.info "Exporting GPG key #{$config['general']['gpg_signing_key']} and uploading to S3 bucket..." # If it doesn't exist on this machine, then we're a bit stuck! unless pubkey_exist? $logger.error "The public key #{$config['general']['gpg_signing_key']} does not exist on this system, so unable to export it out" return false end # Export out key unless system "gpg --export --armour 0x#{$config['general']['gpg_signing_key']} > #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'A fault occured when trying to export the GPG key' return false end # Upload s3 = Pupistry::StorageAWS.new 'build' unless s3.upload "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to upload GPG key to S3 bucket' return false end end end
[ "def", "pubkey_upload", "unless", "File", ".", "exist?", "(", "\"#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", ")", "# GPG key does not exist locally, we therefore assume it's not in the S3", "# bucket either, so we should export out and upload. Technically this may", "# result in a few extra uploads (once for any new machine using Pupistry)", "# but it doesn't cause any issue and saves me writing more code ;-)", "$logger", ".", "info", "\"Exporting GPG key #{$config['general']['gpg_signing_key']} and uploading to S3 bucket...\"", "# If it doesn't exist on this machine, then we're a bit stuck!", "unless", "pubkey_exist?", "$logger", ".", "error", "\"The public key #{$config['general']['gpg_signing_key']} does not exist on this system, so unable to export it out\"", "return", "false", "end", "# Export out key", "unless", "system", "\"gpg --export --armour 0x#{$config['general']['gpg_signing_key']} > #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", "$logger", ".", "error", "'A fault occured when trying to export the GPG key'", "return", "false", "end", "# Upload", "s3", "=", "Pupistry", "::", "StorageAWS", ".", "new", "'build'", "unless", "s3", ".", "upload", "\"#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", ",", "\"#{$config['general']['gpg_signing_key']}.publickey\"", "$logger", ".", "error", "'Unable to upload GPG key to S3 bucket'", "return", "false", "end", "end", "end" ]
Extract & upload the public key to the s3 bucket for other users
[ "Extract", "&", "upload", "the", "public", "key", "to", "the", "s3", "bucket", "for", "other", "users" ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L188-L219
22,059
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.pubkey_install
def pubkey_install $logger.warn "Installing GPG key #{$config['general']['gpg_signing_key']}..." s3 = Pupistry::StorageAWS.new 'agent' unless s3.download "#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to download GPG key from S3 bucket, this will prevent validation of signature' return false end unless system "gpg --import < #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey > /dev/null 2>&1" $logger.error 'A fault occured when trying to import the GPG key' return false end rescue StandardError $logger.error 'Something unexpected occured when installing the GPG public key' return false end
ruby
def pubkey_install $logger.warn "Installing GPG key #{$config['general']['gpg_signing_key']}..." s3 = Pupistry::StorageAWS.new 'agent' unless s3.download "#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to download GPG key from S3 bucket, this will prevent validation of signature' return false end unless system "gpg --import < #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey > /dev/null 2>&1" $logger.error 'A fault occured when trying to import the GPG key' return false end rescue StandardError $logger.error 'Something unexpected occured when installing the GPG public key' return false end
[ "def", "pubkey_install", "$logger", ".", "warn", "\"Installing GPG key #{$config['general']['gpg_signing_key']}...\"", "s3", "=", "Pupistry", "::", "StorageAWS", ".", "new", "'agent'", "unless", "s3", ".", "download", "\"#{$config['general']['gpg_signing_key']}.publickey\"", ",", "\"#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", "$logger", ".", "error", "'Unable to download GPG key from S3 bucket, this will prevent validation of signature'", "return", "false", "end", "unless", "system", "\"gpg --import < #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey > /dev/null 2>&1\"", "$logger", ".", "error", "'A fault occured when trying to import the GPG key'", "return", "false", "end", "rescue", "StandardError", "$logger", ".", "error", "'Something unexpected occured when installing the GPG public key'", "return", "false", "end" ]
Install the public key. This is a potential avenue for exploit, if a machine is being built for the first time, it has no existing trust of the GPG key, other than transit encryption to the S3 bucket. To protect against attacks at the bootstrap time, you should pre-load your machine images with the public GPG key. For those users who trade off some security for convienence, we install the GPG public key for them direct from the S3 repo.
[ "Install", "the", "public", "key", ".", "This", "is", "a", "potential", "avenue", "for", "exploit", "if", "a", "machine", "is", "being", "built", "for", "the", "first", "time", "it", "has", "no", "existing", "trust", "of", "the", "GPG", "key", "other", "than", "transit", "encryption", "to", "the", "S3", "bucket", ".", "To", "protect", "against", "attacks", "at", "the", "bootstrap", "time", "you", "should", "pre", "-", "load", "your", "machine", "images", "with", "the", "public", "GPG", "key", "." ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L230-L248
22,060
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.wip=
def wip=(pr) label_names = [] labels.each do |label| label_names << label.name end puts("exist labels:" + label_names.join(", ")) unless wip? begin add_label("WIP") rescue Octokit::UnprocessableEntity => e puts "WIP label is already exists." puts e end end github.api.add_labels_to_an_issue(repo, pr, [wip_label]) end
ruby
def wip=(pr) label_names = [] labels.each do |label| label_names << label.name end puts("exist labels:" + label_names.join(", ")) unless wip? begin add_label("WIP") rescue Octokit::UnprocessableEntity => e puts "WIP label is already exists." puts e end end github.api.add_labels_to_an_issue(repo, pr, [wip_label]) end
[ "def", "wip", "=", "(", "pr", ")", "label_names", "=", "[", "]", "labels", ".", "each", "do", "|", "label", "|", "label_names", "<<", "label", ".", "name", "end", "puts", "(", "\"exist labels:\"", "+", "label_names", ".", "join", "(", "\", \"", ")", ")", "unless", "wip?", "begin", "add_label", "(", "\"WIP\"", ")", "rescue", "Octokit", "::", "UnprocessableEntity", "=>", "e", "puts", "\"WIP label is already exists.\"", "puts", "e", "end", "end", "github", ".", "api", ".", "add_labels_to_an_issue", "(", "repo", ",", "pr", ",", "[", "wip_label", "]", ")", "end" ]
Set WIP label to PR. @param [Number] pr A number of issue or pull request for set label. @return [void]
[ "Set", "WIP", "label", "to", "PR", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L21-L36
22,061
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.set
def set(pr, name, color) message = "" if label?(name) message = "Set #{name} label. (Color: #{color})" else message = "Add #{name} new label. (Color: #{color})" add_label(name, color) end github.api.add_labels_to_an_issue(repo, pr, [name]) puts message end
ruby
def set(pr, name, color) message = "" if label?(name) message = "Set #{name} label. (Color: #{color})" else message = "Add #{name} new label. (Color: #{color})" add_label(name, color) end github.api.add_labels_to_an_issue(repo, pr, [name]) puts message end
[ "def", "set", "(", "pr", ",", "name", ",", "color", ")", "message", "=", "\"\"", "if", "label?", "(", "name", ")", "message", "=", "\"Set #{name} label. (Color: #{color})\"", "else", "message", "=", "\"Add #{name} new label. (Color: #{color})\"", "add_label", "(", "name", ",", "color", ")", "end", "github", ".", "api", ".", "add_labels_to_an_issue", "(", "repo", ",", "pr", ",", "[", "name", "]", ")", "puts", "message", "end" ]
Set any labels to PR by this. @param [Number] pr A number of issue or pull request for set label. @param [String] name A new label name. @param [String] color A color, in hex, without the leading #. Default is "fef2c0" @return [void]
[ "Set", "any", "labels", "to", "PR", "by", "this", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L46-L56
22,062
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.delete
def delete(name) begin github.api.delete_label!(repo, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
ruby
def delete(name) begin github.api.delete_label!(repo, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
[ "def", "delete", "(", "name", ")", "begin", "github", ".", "api", ".", "delete_label!", "(", "repo", ",", "name", ")", "rescue", "Octokit", "::", "Error", "=>", "e", "puts", "\"Error message: \\\"#{name}\\\" label is not existing.\"", "puts", "e", "end", "end" ]
Delete label from repository. @param [String] name Delete label name. @return [void]
[ "Delete", "label", "from", "repository", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L62-L69
22,063
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.remove
def remove(name) begin github.api.remove_label(repo, number, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
ruby
def remove(name) begin github.api.remove_label(repo, number, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
[ "def", "remove", "(", "name", ")", "begin", "github", ".", "api", ".", "remove_label", "(", "repo", ",", "number", ",", "name", ")", "rescue", "Octokit", "::", "Error", "=>", "e", "puts", "\"Error message: \\\"#{name}\\\" label is not existing.\"", "puts", "e", "end", "end" ]
Remove label from PR. @param [String] name Remove label name. @return [void]
[ "Remove", "label", "from", "PR", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L75-L82
22,064
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.diff
def diff(cov1, cov2) ncov = {} old_format = true cov1.each do |path1, runs1| if cov2[path1] runs2 = cov2[path1] if runs1.is_a?(Array) && runs2.is_a?(Array) && old_format # diff two old-format (ruby 2.4 or before) coverage results ncov[path1] = diff_lines(runs1, runs2) next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if runs2.is_a?(Array) runs2 = { :lines => runs2 } end if old_format old_format = false old2new!(ncov) end # diff two new-format (ruby 2.5 or later) coverage results ncov[path1] = {} [ [:lines, :diff_lines], [:branches, :diff_branches], [:methods, :diff_methods], ].each do |type, diff_func| if runs1[type] if runs2[type] ncov[path1][type] = send(diff_func, runs1[type], runs2[type]) else ncov[path1][type] = runs1[type] end end end else if runs1.is_a?(Array) && old_format ncov[path1] = runs1 next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if old_format old_format = false old2new!(ncov) end ncov[path1] = runs1 end end ncov end
ruby
def diff(cov1, cov2) ncov = {} old_format = true cov1.each do |path1, runs1| if cov2[path1] runs2 = cov2[path1] if runs1.is_a?(Array) && runs2.is_a?(Array) && old_format # diff two old-format (ruby 2.4 or before) coverage results ncov[path1] = diff_lines(runs1, runs2) next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if runs2.is_a?(Array) runs2 = { :lines => runs2 } end if old_format old_format = false old2new!(ncov) end # diff two new-format (ruby 2.5 or later) coverage results ncov[path1] = {} [ [:lines, :diff_lines], [:branches, :diff_branches], [:methods, :diff_methods], ].each do |type, diff_func| if runs1[type] if runs2[type] ncov[path1][type] = send(diff_func, runs1[type], runs2[type]) else ncov[path1][type] = runs1[type] end end end else if runs1.is_a?(Array) && old_format ncov[path1] = runs1 next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if old_format old_format = false old2new!(ncov) end ncov[path1] = runs1 end end ncov end
[ "def", "diff", "(", "cov1", ",", "cov2", ")", "ncov", "=", "{", "}", "old_format", "=", "true", "cov1", ".", "each", "do", "|", "path1", ",", "runs1", "|", "if", "cov2", "[", "path1", "]", "runs2", "=", "cov2", "[", "path1", "]", "if", "runs1", ".", "is_a?", "(", "Array", ")", "&&", "runs2", ".", "is_a?", "(", "Array", ")", "&&", "old_format", "# diff two old-format (ruby 2.4 or before) coverage results", "ncov", "[", "path1", "]", "=", "diff_lines", "(", "runs1", ",", "runs2", ")", "next", "end", "# promotes from old format to new one", "if", "runs1", ".", "is_a?", "(", "Array", ")", "runs1", "=", "{", ":lines", "=>", "runs1", "}", "end", "if", "runs2", ".", "is_a?", "(", "Array", ")", "runs2", "=", "{", ":lines", "=>", "runs2", "}", "end", "if", "old_format", "old_format", "=", "false", "old2new!", "(", "ncov", ")", "end", "# diff two new-format (ruby 2.5 or later) coverage results", "ncov", "[", "path1", "]", "=", "{", "}", "[", "[", ":lines", ",", ":diff_lines", "]", ",", "[", ":branches", ",", ":diff_branches", "]", ",", "[", ":methods", ",", ":diff_methods", "]", ",", "]", ".", "each", "do", "|", "type", ",", "diff_func", "|", "if", "runs1", "[", "type", "]", "if", "runs2", "[", "type", "]", "ncov", "[", "path1", "]", "[", "type", "]", "=", "send", "(", "diff_func", ",", "runs1", "[", "type", "]", ",", "runs2", "[", "type", "]", ")", "else", "ncov", "[", "path1", "]", "[", "type", "]", "=", "runs1", "[", "type", "]", "end", "end", "end", "else", "if", "runs1", ".", "is_a?", "(", "Array", ")", "&&", "old_format", "ncov", "[", "path1", "]", "=", "runs1", "next", "end", "# promotes from old format to new one", "if", "runs1", ".", "is_a?", "(", "Array", ")", "runs1", "=", "{", ":lines", "=>", "runs1", "}", "end", "if", "old_format", "old_format", "=", "false", "old2new!", "(", "ncov", ")", "end", "ncov", "[", "path1", "]", "=", "runs1", "end", "end", "ncov", "end" ]
Extract the coverage results that is covered by `cov1` but not covered by `cov2`.
[ "Extract", "the", "coverage", "results", "that", "is", "covered", "by", "cov1", "but", "not", "covered", "by", "cov2", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L114-L174
22,065
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.sanitize
def sanitize(cov) ncov = {} cov.each do |path, runs| if runs.is_a?(Array) ncov[path] = runs next end ncov[path] = {} ncov[path][:lines] = runs[:lines] if runs[:lines] ncov[path][:branches] = runs[:branches] if runs[:branches] if runs[:methods] ncov[path][:methods] = methods = {} runs[:methods].each do |mthd, run| klass = begin Marshal.dump(mthd[0]) mthd[0] rescue mthd[0].to_s end methods[[klass] + mthd.drop(1)] = run end end end ncov end
ruby
def sanitize(cov) ncov = {} cov.each do |path, runs| if runs.is_a?(Array) ncov[path] = runs next end ncov[path] = {} ncov[path][:lines] = runs[:lines] if runs[:lines] ncov[path][:branches] = runs[:branches] if runs[:branches] if runs[:methods] ncov[path][:methods] = methods = {} runs[:methods].each do |mthd, run| klass = begin Marshal.dump(mthd[0]) mthd[0] rescue mthd[0].to_s end methods[[klass] + mthd.drop(1)] = run end end end ncov end
[ "def", "sanitize", "(", "cov", ")", "ncov", "=", "{", "}", "cov", ".", "each", "do", "|", "path", ",", "runs", "|", "if", "runs", ".", "is_a?", "(", "Array", ")", "ncov", "[", "path", "]", "=", "runs", "next", "end", "ncov", "[", "path", "]", "=", "{", "}", "ncov", "[", "path", "]", "[", ":lines", "]", "=", "runs", "[", ":lines", "]", "if", "runs", "[", ":lines", "]", "ncov", "[", "path", "]", "[", ":branches", "]", "=", "runs", "[", ":branches", "]", "if", "runs", "[", ":branches", "]", "if", "runs", "[", ":methods", "]", "ncov", "[", "path", "]", "[", ":methods", "]", "=", "methods", "=", "{", "}", "runs", "[", ":methods", "]", ".", "each", "do", "|", "mthd", ",", "run", "|", "klass", "=", "begin", "Marshal", ".", "dump", "(", "mthd", "[", "0", "]", ")", "mthd", "[", "0", "]", "rescue", "mthd", "[", "0", "]", ".", "to_s", "end", "methods", "[", "[", "klass", "]", "+", "mthd", ".", "drop", "(", "1", ")", "]", "=", "run", "end", "end", "end", "ncov", "end" ]
Make the covearge result able to marshal.
[ "Make", "the", "covearge", "result", "able", "to", "marshal", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L177-L204
22,066
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.save
def save(path, cov) File.binwrite(path, Marshal.dump(sanitize(cov))) end
ruby
def save(path, cov) File.binwrite(path, Marshal.dump(sanitize(cov))) end
[ "def", "save", "(", "path", ",", "cov", ")", "File", ".", "binwrite", "(", "path", ",", "Marshal", ".", "dump", "(", "sanitize", "(", "cov", ")", ")", ")", "end" ]
Save the coverage result to a file.
[ "Save", "the", "coverage", "result", "to", "a", "file", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L207-L209
22,067
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.to_lcov_info
def to_lcov_info(cov, out: "", test_name: nil) out << "TN:#{ test_name }\n" cov.each do |path, runs| out << "SF:#{ path }\n" # function coverage if runs.is_a?(Hash) && runs[:methods] total = covered = 0 runs[:methods].each do |(klass, name, lineno), run| out << "FN:#{ lineno },#{ klass }##{ name }\n" total += 1 covered += 1 if run > 0 end out << "FNF:#{ total }\n" out << "FNF:#{ covered }\n" runs[:methods].each do |(klass, name, _), run| out << "FNDA:#{ run },#{ klass }##{ name }\n" end end # line coverage if runs.is_a?(Array) || (runs.is_a?(Hash) && runs[:lines]) total = covered = 0 lines = runs.is_a?(Array) ? runs : runs[:lines] lines.each_with_index do |run, lineno| next unless run out << "DA:#{ lineno + 1 },#{ run }\n" total += 1 covered += 1 if run > 0 end out << "LF:#{ total }\n" out << "LH:#{ covered }\n" end # branch coverage if runs.is_a?(Hash) && runs[:branches] total = covered = 0 id = 0 runs[:branches].each do |(_base_type, _, base_lineno), targets| i = 0 targets.each do |(_target_type, _target_lineno), run| out << "BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\n" total += 1 covered += 1 if run > 0 i += 1 end id += 1 end out << "BRF:#{ total }\n" out << "BRH:#{ covered }\n" end out << "end_of_record\n" end out end
ruby
def to_lcov_info(cov, out: "", test_name: nil) out << "TN:#{ test_name }\n" cov.each do |path, runs| out << "SF:#{ path }\n" # function coverage if runs.is_a?(Hash) && runs[:methods] total = covered = 0 runs[:methods].each do |(klass, name, lineno), run| out << "FN:#{ lineno },#{ klass }##{ name }\n" total += 1 covered += 1 if run > 0 end out << "FNF:#{ total }\n" out << "FNF:#{ covered }\n" runs[:methods].each do |(klass, name, _), run| out << "FNDA:#{ run },#{ klass }##{ name }\n" end end # line coverage if runs.is_a?(Array) || (runs.is_a?(Hash) && runs[:lines]) total = covered = 0 lines = runs.is_a?(Array) ? runs : runs[:lines] lines.each_with_index do |run, lineno| next unless run out << "DA:#{ lineno + 1 },#{ run }\n" total += 1 covered += 1 if run > 0 end out << "LF:#{ total }\n" out << "LH:#{ covered }\n" end # branch coverage if runs.is_a?(Hash) && runs[:branches] total = covered = 0 id = 0 runs[:branches].each do |(_base_type, _, base_lineno), targets| i = 0 targets.each do |(_target_type, _target_lineno), run| out << "BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\n" total += 1 covered += 1 if run > 0 i += 1 end id += 1 end out << "BRF:#{ total }\n" out << "BRH:#{ covered }\n" end out << "end_of_record\n" end out end
[ "def", "to_lcov_info", "(", "cov", ",", "out", ":", "\"\"", ",", "test_name", ":", "nil", ")", "out", "<<", "\"TN:#{ test_name }\\n\"", "cov", ".", "each", "do", "|", "path", ",", "runs", "|", "out", "<<", "\"SF:#{ path }\\n\"", "# function coverage", "if", "runs", ".", "is_a?", "(", "Hash", ")", "&&", "runs", "[", ":methods", "]", "total", "=", "covered", "=", "0", "runs", "[", ":methods", "]", ".", "each", "do", "|", "(", "klass", ",", "name", ",", "lineno", ")", ",", "run", "|", "out", "<<", "\"FN:#{ lineno },#{ klass }##{ name }\\n\"", "total", "+=", "1", "covered", "+=", "1", "if", "run", ">", "0", "end", "out", "<<", "\"FNF:#{ total }\\n\"", "out", "<<", "\"FNF:#{ covered }\\n\"", "runs", "[", ":methods", "]", ".", "each", "do", "|", "(", "klass", ",", "name", ",", "_", ")", ",", "run", "|", "out", "<<", "\"FNDA:#{ run },#{ klass }##{ name }\\n\"", "end", "end", "# line coverage", "if", "runs", ".", "is_a?", "(", "Array", ")", "||", "(", "runs", ".", "is_a?", "(", "Hash", ")", "&&", "runs", "[", ":lines", "]", ")", "total", "=", "covered", "=", "0", "lines", "=", "runs", ".", "is_a?", "(", "Array", ")", "?", "runs", ":", "runs", "[", ":lines", "]", "lines", ".", "each_with_index", "do", "|", "run", ",", "lineno", "|", "next", "unless", "run", "out", "<<", "\"DA:#{ lineno + 1 },#{ run }\\n\"", "total", "+=", "1", "covered", "+=", "1", "if", "run", ">", "0", "end", "out", "<<", "\"LF:#{ total }\\n\"", "out", "<<", "\"LH:#{ covered }\\n\"", "end", "# branch coverage", "if", "runs", ".", "is_a?", "(", "Hash", ")", "&&", "runs", "[", ":branches", "]", "total", "=", "covered", "=", "0", "id", "=", "0", "runs", "[", ":branches", "]", ".", "each", "do", "|", "(", "_base_type", ",", "_", ",", "base_lineno", ")", ",", "targets", "|", "i", "=", "0", "targets", ".", "each", "do", "|", "(", "_target_type", ",", "_target_lineno", ")", ",", "run", "|", "out", "<<", "\"BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\\n\"", "total", "+=", "1", "covered", "+=", "1", "if", "run", ">", "0", "i", "+=", "1", "end", "id", "+=", "1", "end", "out", "<<", "\"BRF:#{ total }\\n\"", "out", "<<", "\"BRH:#{ covered }\\n\"", "end", "out", "<<", "\"end_of_record\\n\"", "end", "out", "end" ]
Translate the result into LCOV info format.
[ "Translate", "the", "result", "into", "LCOV", "info", "format", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L217-L273
22,068
kymmt90/hatenablog
lib/hatenablog/entry.rb
Hatenablog.AfterHook.after_hook
def after_hook(hook, *methods) methods.each do |method| origin_method = "#{method}_origin".to_sym if instance_methods.include? origin_method raise NameError, "#{origin_method} isn't a unique name" end alias_method origin_method, method define_method(method) do |*args, &block| result = send(origin_method, *args, &block) send(hook) end end end
ruby
def after_hook(hook, *methods) methods.each do |method| origin_method = "#{method}_origin".to_sym if instance_methods.include? origin_method raise NameError, "#{origin_method} isn't a unique name" end alias_method origin_method, method define_method(method) do |*args, &block| result = send(origin_method, *args, &block) send(hook) end end end
[ "def", "after_hook", "(", "hook", ",", "*", "methods", ")", "methods", ".", "each", "do", "|", "method", "|", "origin_method", "=", "\"#{method}_origin\"", ".", "to_sym", "if", "instance_methods", ".", "include?", "origin_method", "raise", "NameError", ",", "\"#{origin_method} isn't a unique name\"", "end", "alias_method", "origin_method", ",", "method", "define_method", "(", "method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "result", "=", "send", "(", "origin_method", ",", "args", ",", "block", ")", "send", "(", "hook", ")", "end", "end", "end" ]
Register a hooking method for given methods. The hook method is executed after calling given methods. @param [Symbol] hooking method name @param [Array] hooked methods name array
[ "Register", "a", "hooking", "method", "for", "given", "methods", ".", "The", "hook", "method", "is", "executed", "after", "calling", "given", "methods", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/entry.rb#L10-L24
22,069
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.next_feed
def next_feed(feed = nil) return Feed.load_xml(get_collection(collection_uri).body) if feed.nil? return nil unless feed.has_next? Feed.load_xml(get_collection(feed.next_uri).body) end
ruby
def next_feed(feed = nil) return Feed.load_xml(get_collection(collection_uri).body) if feed.nil? return nil unless feed.has_next? Feed.load_xml(get_collection(feed.next_uri).body) end
[ "def", "next_feed", "(", "feed", "=", "nil", ")", "return", "Feed", ".", "load_xml", "(", "get_collection", "(", "collection_uri", ")", ".", "body", ")", "if", "feed", ".", "nil?", "return", "nil", "unless", "feed", ".", "has_next?", "Feed", ".", "load_xml", "(", "get_collection", "(", "feed", ".", "next_uri", ")", ".", "body", ")", "end" ]
Get the next feed of the given feed. Return the first feed if no argument is passed. @param [Hatenablog::Feed] feed blog feed @return [Hatenablog::Feed] next blog feed
[ "Get", "the", "next", "feed", "of", "the", "given", "feed", ".", "Return", "the", "first", "feed", "if", "no", "argument", "is", "passed", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L69-L73
22,070
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.get_entry
def get_entry(entry_id) response = get(member_uri(entry_id)) Entry.load_xml(response.body) end
ruby
def get_entry(entry_id) response = get(member_uri(entry_id)) Entry.load_xml(response.body) end
[ "def", "get_entry", "(", "entry_id", ")", "response", "=", "get", "(", "member_uri", "(", "entry_id", ")", ")", "Entry", ".", "load_xml", "(", "response", ".", "body", ")", "end" ]
Get a blog entry specified by its ID. @param [String] entry_id entry ID @return [Hatenablog::BlogEntry] entry
[ "Get", "a", "blog", "entry", "specified", "by", "its", "ID", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L85-L88
22,071
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.post_entry
def post_entry(title = '', content = '', categories = [], draft = 'no') entry_xml = entry_xml(title, content, categories, draft) response = post(entry_xml) Entry.load_xml(response.body) end
ruby
def post_entry(title = '', content = '', categories = [], draft = 'no') entry_xml = entry_xml(title, content, categories, draft) response = post(entry_xml) Entry.load_xml(response.body) end
[ "def", "post_entry", "(", "title", "=", "''", ",", "content", "=", "''", ",", "categories", "=", "[", "]", ",", "draft", "=", "'no'", ")", "entry_xml", "=", "entry_xml", "(", "title", ",", "content", ",", "categories", ",", "draft", ")", "response", "=", "post", "(", "entry_xml", ")", "Entry", ".", "load_xml", "(", "response", ".", "body", ")", "end" ]
Post a blog entry. @param [String] title entry title @param [String] content entry content @param [Array] categories entry categories @param [String] draft this entry is draft if 'yes', otherwise it is not draft @return [Hatenablog::BlogEntry] posted entry
[ "Post", "a", "blog", "entry", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L96-L100
22,072
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.update_entry
def update_entry(entry_id, title = '', content = '', categories = [], draft = 'no', updated = '') entry_xml = entry_xml(title, content, categories, draft, updated) response = put(entry_xml, member_uri(entry_id)) Entry.load_xml(response.body) end
ruby
def update_entry(entry_id, title = '', content = '', categories = [], draft = 'no', updated = '') entry_xml = entry_xml(title, content, categories, draft, updated) response = put(entry_xml, member_uri(entry_id)) Entry.load_xml(response.body) end
[ "def", "update_entry", "(", "entry_id", ",", "title", "=", "''", ",", "content", "=", "''", ",", "categories", "=", "[", "]", ",", "draft", "=", "'no'", ",", "updated", "=", "''", ")", "entry_xml", "=", "entry_xml", "(", "title", ",", "content", ",", "categories", ",", "draft", ",", "updated", ")", "response", "=", "put", "(", "entry_xml", ",", "member_uri", "(", "entry_id", ")", ")", "Entry", ".", "load_xml", "(", "response", ".", "body", ")", "end" ]
Update a blog entry specified by its ID. @param [String] entry_id updated entry ID @param [String] title entry title @param [String] content entry content @param [Array] categories entry categories @param [String] draft this entry is draft if 'yes', otherwise it is not draft @param [String] updated entry updated datetime (ISO 8601) @return [Hatenablog::BlogEntry] updated entry
[ "Update", "a", "blog", "entry", "specified", "by", "its", "ID", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L110-L114
22,073
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.entry_xml
def entry_xml(title = '', content = '', categories = [], draft = 'no', updated = '', author_name = @user_id) builder = Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml| xml.entry('xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:app' => 'http://www.w3.org/2007/app') do xml.title title xml.author do xml.name author_name end xml.content(content, type: 'text/x-markdown') xml.updated updated unless updated.empty? || updated.nil? categories.each do |category| xml.category(term: category) end xml['app'].control do xml['app'].draft draft end end end builder.to_xml end
ruby
def entry_xml(title = '', content = '', categories = [], draft = 'no', updated = '', author_name = @user_id) builder = Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml| xml.entry('xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:app' => 'http://www.w3.org/2007/app') do xml.title title xml.author do xml.name author_name end xml.content(content, type: 'text/x-markdown') xml.updated updated unless updated.empty? || updated.nil? categories.each do |category| xml.category(term: category) end xml['app'].control do xml['app'].draft draft end end end builder.to_xml end
[ "def", "entry_xml", "(", "title", "=", "''", ",", "content", "=", "''", ",", "categories", "=", "[", "]", ",", "draft", "=", "'no'", ",", "updated", "=", "''", ",", "author_name", "=", "@user_id", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "(", "encoding", ":", "'utf-8'", ")", "do", "|", "xml", "|", "xml", ".", "entry", "(", "'xmlns'", "=>", "'http://www.w3.org/2005/Atom'", ",", "'xmlns:app'", "=>", "'http://www.w3.org/2007/app'", ")", "do", "xml", ".", "title", "title", "xml", ".", "author", "do", "xml", ".", "name", "author_name", "end", "xml", ".", "content", "(", "content", ",", "type", ":", "'text/x-markdown'", ")", "xml", ".", "updated", "updated", "unless", "updated", ".", "empty?", "||", "updated", ".", "nil?", "categories", ".", "each", "do", "|", "category", "|", "xml", ".", "category", "(", "term", ":", "category", ")", "end", "xml", "[", "'app'", "]", ".", "control", "do", "xml", "[", "'app'", "]", ".", "draft", "draft", "end", "end", "end", "builder", ".", "to_xml", "end" ]
Build a entry XML from arguments. @param [String] title entry title @param [String] content entry content @param [Array] categories entry categories @param [String] draft this entry is draft if 'yes', otherwise it is not draft @param [String] updated entry updated datetime (ISO 8601) @param [String] author_name entry author name @return [String] XML string
[ "Build", "a", "entry", "XML", "from", "arguments", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L155-L175
22,074
Everlane/async_cache
lib/async_cache/store.rb
AsyncCache.Store.check_arguments
def check_arguments arguments arguments.each_with_index do |argument, index| next if argument.is_a? Numeric next if argument.is_a? String next if argument.is_a? Symbol next if argument.is_a? Hash next if argument.is_a? NilClass next if argument.is_a? TrueClass next if argument.is_a? FalseClass raise ArgumentError, "Cannot send complex data for block argument #{index + 1}: #{argument.class.name}" end arguments end
ruby
def check_arguments arguments arguments.each_with_index do |argument, index| next if argument.is_a? Numeric next if argument.is_a? String next if argument.is_a? Symbol next if argument.is_a? Hash next if argument.is_a? NilClass next if argument.is_a? TrueClass next if argument.is_a? FalseClass raise ArgumentError, "Cannot send complex data for block argument #{index + 1}: #{argument.class.name}" end arguments end
[ "def", "check_arguments", "arguments", "arguments", ".", "each_with_index", "do", "|", "argument", ",", "index", "|", "next", "if", "argument", ".", "is_a?", "Numeric", "next", "if", "argument", ".", "is_a?", "String", "next", "if", "argument", ".", "is_a?", "Symbol", "next", "if", "argument", ".", "is_a?", "Hash", "next", "if", "argument", ".", "is_a?", "NilClass", "next", "if", "argument", ".", "is_a?", "TrueClass", "next", "if", "argument", ".", "is_a?", "FalseClass", "raise", "ArgumentError", ",", "\"Cannot send complex data for block argument #{index + 1}: #{argument.class.name}\"", "end", "arguments", "end" ]
Ensures the arguments are primitives.
[ "Ensures", "the", "arguments", "are", "primitives", "." ]
68709579b1d3e3bd03ff0afdf01dae32bec767be
https://github.com/Everlane/async_cache/blob/68709579b1d3e3bd03ff0afdf01dae32bec767be/lib/async_cache/store.rb#L153-L167
22,075
mfdavid/rackstep
lib/router.rb
RackStep.Router.find_route_for
def find_route_for(path, verb) # Ignoring the first char if path starts with '/'. This way the path of # 'http//localhost/' will be the same of 'http://localhost' (both will # be empty strings). path = path[1..-1] if path[0] == '/' route_id = verb + path route = routes[route_id] # If no route was found, set it to 'notfound' route (maintaining the # original verb). route = routes["#{verb}notfound"] if route == nil return route end
ruby
def find_route_for(path, verb) # Ignoring the first char if path starts with '/'. This way the path of # 'http//localhost/' will be the same of 'http://localhost' (both will # be empty strings). path = path[1..-1] if path[0] == '/' route_id = verb + path route = routes[route_id] # If no route was found, set it to 'notfound' route (maintaining the # original verb). route = routes["#{verb}notfound"] if route == nil return route end
[ "def", "find_route_for", "(", "path", ",", "verb", ")", "# Ignoring the first char if path starts with '/'. This way the path of", "# 'http//localhost/' will be the same of 'http://localhost' (both will", "# be empty strings).", "path", "=", "path", "[", "1", "..", "-", "1", "]", "if", "path", "[", "0", "]", "==", "'/'", "route_id", "=", "verb", "+", "path", "route", "=", "routes", "[", "route_id", "]", "# If no route was found, set it to 'notfound' route (maintaining the", "# original verb).", "route", "=", "routes", "[", "\"#{verb}notfound\"", "]", "if", "route", "==", "nil", "return", "route", "end" ]
Given a request, will parse it's path to find what it the apropriate controller to respond it.
[ "Given", "a", "request", "will", "parse", "it", "s", "path", "to", "find", "what", "it", "the", "apropriate", "controller", "to", "respond", "it", "." ]
dd0ef8d568dbf46e66e9e3a35eaed59027fe84d3
https://github.com/mfdavid/rackstep/blob/dd0ef8d568dbf46e66e9e3a35eaed59027fe84d3/lib/router.rb#L30-L42
22,076
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.hide
def hide(name) base_fields[name] = base_fields[name].dup base_fields[name].widget = Widgets::HiddenInput.new end
ruby
def hide(name) base_fields[name] = base_fields[name].dup base_fields[name].widget = Widgets::HiddenInput.new end
[ "def", "hide", "(", "name", ")", "base_fields", "[", "name", "]", "=", "base_fields", "[", "name", "]", ".", "dup", "base_fields", "[", "name", "]", ".", "widget", "=", "Widgets", "::", "HiddenInput", ".", "new", "end" ]
Hide field named +name+
[ "Hide", "field", "named", "+", "name", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L7-L10
22,077
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.text
def text(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::Textarea.new)) end
ruby
def text(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::Textarea.new)) end
[ "def", "text", "(", "name", ",", "options", "=", "{", "}", ")", "field", "name", ",", "CharField", ".", "new", "(", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "Textarea", ".", "new", ")", ")", "end" ]
Declare a +CharField+ with text area widget
[ "Declare", "a", "+", "CharField", "+", "with", "text", "area", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L23-L25
22,078
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.password
def password(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::PasswordInput.new)) end
ruby
def password(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::PasswordInput.new)) end
[ "def", "password", "(", "name", ",", "options", "=", "{", "}", ")", "field", "name", ",", "CharField", ".", "new", "(", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "PasswordInput", ".", "new", ")", ")", "end" ]
Declare a +CharField+ with password widget
[ "Declare", "a", "+", "CharField", "+", "with", "password", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L28-L30
22,079
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.regex
def regex(name, regexp, options = {}) field name, RegexField.new(regexp, options) end
ruby
def regex(name, regexp, options = {}) field name, RegexField.new(regexp, options) end
[ "def", "regex", "(", "name", ",", "regexp", ",", "options", "=", "{", "}", ")", "field", "name", ",", "RegexField", ".", "new", "(", "regexp", ",", "options", ")", "end" ]
Declare a +RegexField+
[ "Declare", "a", "+", "RegexField", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L43-L45
22,080
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.choice
def choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options) end
ruby
def choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options) end
[ "def", "choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "ChoiceField", ".", "new", "(", "choices", ",", "options", ")", "end" ]
Declare a +ChoiceField+ with +choices+
[ "Declare", "a", "+", "ChoiceField", "+", "with", "+", "choices", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L68-L70
22,081
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.typed_choice
def typed_choice(name, choices = [], options = {}) field name, TypedChoiceField.new(choices, options) end
ruby
def typed_choice(name, choices = [], options = {}) field name, TypedChoiceField.new(choices, options) end
[ "def", "typed_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "TypedChoiceField", ".", "new", "(", "choices", ",", "options", ")", "end" ]
Declare a +TypedChoiceField+ with +choices+
[ "Declare", "a", "+", "TypedChoiceField", "+", "with", "+", "choices", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L73-L75
22,082
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.multiple_choice
def multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options) end
ruby
def multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options) end
[ "def", "multiple_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "MultipleChoiceField", ".", "new", "(", "choices", ",", "options", ")", "end" ]
Declare a +MultipleChoiceField+ with +choices+
[ "Declare", "a", "+", "MultipleChoiceField", "+", "with", "+", "choices", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L78-L80
22,083
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.radio_choice
def radio_choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options.merge(widget: Widgets::RadioSelect.new)) end
ruby
def radio_choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options.merge(widget: Widgets::RadioSelect.new)) end
[ "def", "radio_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "ChoiceField", ".", "new", "(", "choices", ",", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "RadioSelect", ".", "new", ")", ")", "end" ]
Declare a +ChoiceField+ using the +RadioSelect+ widget
[ "Declare", "a", "+", "ChoiceField", "+", "using", "the", "+", "RadioSelect", "+", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L83-L85
22,084
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.checkbox_multiple_choice
def checkbox_multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options.merge(widget: Widgets::CheckboxSelectMultiple.new)) end
ruby
def checkbox_multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options.merge(widget: Widgets::CheckboxSelectMultiple.new)) end
[ "def", "checkbox_multiple_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "MultipleChoiceField", ".", "new", "(", "choices", ",", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "CheckboxSelectMultiple", ".", "new", ")", ")", "end" ]
Declare a +MultipleChoiceField+ with the +CheckboxSelectMultiple+ widget
[ "Declare", "a", "+", "MultipleChoiceField", "+", "with", "the", "+", "CheckboxSelectMultiple", "+", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L88-L90
22,085
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.save
def save(filename, path, params={}) payload = get! path, nil, params File.write filename, payload.response.body end
ruby
def save(filename, path, params={}) payload = get! path, nil, params File.write filename, payload.response.body end
[ "def", "save", "(", "filename", ",", "path", ",", "params", "=", "{", "}", ")", "payload", "=", "get!", "path", ",", "nil", ",", "params", "File", ".", "write", "filename", ",", "payload", ".", "response", ".", "body", "end" ]
Save the response body to a file === Example client = Client.new client.save 'out.json', 'some/to/resource', param: value
[ "Save", "the", "response", "body", "to", "a", "file" ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L170-L173
22,086
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.csv_node
def csv_node(data) arrays = data.keys.select { |key| data[key].is_a? Array } arrays.empty? ? [data] : data[arrays.first] end
ruby
def csv_node(data) arrays = data.keys.select { |key| data[key].is_a? Array } arrays.empty? ? [data] : data[arrays.first] end
[ "def", "csv_node", "(", "data", ")", "arrays", "=", "data", ".", "keys", ".", "select", "{", "|", "key", "|", "data", "[", "key", "]", ".", "is_a?", "Array", "}", "arrays", ".", "empty?", "?", "[", "data", "]", ":", "data", "[", "arrays", ".", "first", "]", "end" ]
Determins which part of the data is best suited to be displayed as CSV. - If the response contains one or more arrays, the first array will be the CSV output - Otherwise, if the response was parsed to a ruby object, the response itself will be used as a single-row CSV output. Override this if you want to have a different decision process.
[ "Determins", "which", "part", "of", "the", "data", "is", "best", "suited", "to", "be", "displayed", "as", "CSV", "." ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L222-L225
22,087
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.http_get
def http_get(path, extra=nil, params={}) payload = self.class.get path, params APICake::Payload.new payload end
ruby
def http_get(path, extra=nil, params={}) payload = self.class.get path, params APICake::Payload.new payload end
[ "def", "http_get", "(", "path", ",", "extra", "=", "nil", ",", "params", "=", "{", "}", ")", "payload", "=", "self", ".", "class", ".", "get", "path", ",", "params", "APICake", "::", "Payload", ".", "new", "payload", "end" ]
Make a call with HTTParty and return a payload object.
[ "Make", "a", "call", "with", "HTTParty", "and", "return", "a", "payload", "object", "." ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L230-L233
22,088
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.normalize
def normalize(path, extra=nil, params={}) if extra.is_a?(Hash) and params.empty? params = extra extra = nil end path = "#{path}/#{extra}" if extra path = "/#{path}" unless path[0] == '/' query = default_query.merge params params[:query] = query unless query.empty? params = default_params.merge params [path, extra, params] end
ruby
def normalize(path, extra=nil, params={}) if extra.is_a?(Hash) and params.empty? params = extra extra = nil end path = "#{path}/#{extra}" if extra path = "/#{path}" unless path[0] == '/' query = default_query.merge params params[:query] = query unless query.empty? params = default_params.merge params [path, extra, params] end
[ "def", "normalize", "(", "path", ",", "extra", "=", "nil", ",", "params", "=", "{", "}", ")", "if", "extra", ".", "is_a?", "(", "Hash", ")", "and", "params", ".", "empty?", "params", "=", "extra", "extra", "=", "nil", "end", "path", "=", "\"#{path}/#{extra}\"", "if", "extra", "path", "=", "\"/#{path}\"", "unless", "path", "[", "0", "]", "==", "'/'", "query", "=", "default_query", ".", "merge", "params", "params", "[", ":query", "]", "=", "query", "unless", "query", ".", "empty?", "params", "=", "default_params", ".", "merge", "params", "[", "path", ",", "extra", ",", "params", "]", "end" ]
Normalize the three input parameters
[ "Normalize", "the", "three", "input", "parameters" ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L236-L251
22,089
rsim/ruby-plsql
lib/plsql/connection.rb
PLSQL.Connection.describe_synonym
def describe_synonym(schema_name, synonym_name) #:nodoc: select_first( "SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name", schema_name.to_s.upcase, synonym_name.to_s.upcase) end
ruby
def describe_synonym(schema_name, synonym_name) #:nodoc: select_first( "SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name", schema_name.to_s.upcase, synonym_name.to_s.upcase) end
[ "def", "describe_synonym", "(", "schema_name", ",", "synonym_name", ")", "#:nodoc:", "select_first", "(", "\"SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name\"", ",", "schema_name", ".", "to_s", ".", "upcase", ",", "synonym_name", ".", "to_s", ".", "upcase", ")", "end" ]
all_synonyms view is quite slow therefore this implementation is overriden in OCI connection with faster native OCI method
[ "all_synonyms", "view", "is", "quite", "slow", "therefore", "this", "implementation", "is", "overriden", "in", "OCI", "connection", "with", "faster", "native", "OCI", "method" ]
dc5e74200b186ba9e444f75821351aa454f84795
https://github.com/rsim/ruby-plsql/blob/dc5e74200b186ba9e444f75821351aa454f84795/lib/plsql/connection.rb#L184-L188
22,090
mongoid/moped
lib/moped/connection.rb
Moped.Connection.read
def read with_connection do |socket| reply = Protocol::Reply.allocate data = read_data(socket, 36) response = data.unpack(REPLY_DECODE_STR) reply.length, reply.request_id, reply.response_to, reply.op_code, reply.flags, reply.cursor_id, reply.offset, reply.count = response if reply.count == 0 reply.documents = [] else sock_read = read_data(socket, reply.length - 36) buffer = StringIO.new(sock_read) reply.documents = reply.count.times.map do ::BSON::Document.from_bson(buffer) end end reply end end
ruby
def read with_connection do |socket| reply = Protocol::Reply.allocate data = read_data(socket, 36) response = data.unpack(REPLY_DECODE_STR) reply.length, reply.request_id, reply.response_to, reply.op_code, reply.flags, reply.cursor_id, reply.offset, reply.count = response if reply.count == 0 reply.documents = [] else sock_read = read_data(socket, reply.length - 36) buffer = StringIO.new(sock_read) reply.documents = reply.count.times.map do ::BSON::Document.from_bson(buffer) end end reply end end
[ "def", "read", "with_connection", "do", "|", "socket", "|", "reply", "=", "Protocol", "::", "Reply", ".", "allocate", "data", "=", "read_data", "(", "socket", ",", "36", ")", "response", "=", "data", ".", "unpack", "(", "REPLY_DECODE_STR", ")", "reply", ".", "length", ",", "reply", ".", "request_id", ",", "reply", ".", "response_to", ",", "reply", ".", "op_code", ",", "reply", ".", "flags", ",", "reply", ".", "cursor_id", ",", "reply", ".", "offset", ",", "reply", ".", "count", "=", "response", "if", "reply", ".", "count", "==", "0", "reply", ".", "documents", "=", "[", "]", "else", "sock_read", "=", "read_data", "(", "socket", ",", "reply", ".", "length", "-", "36", ")", "buffer", "=", "StringIO", ".", "new", "(", "sock_read", ")", "reply", ".", "documents", "=", "reply", ".", "count", ".", "times", ".", "map", "do", "::", "BSON", "::", "Document", ".", "from_bson", "(", "buffer", ")", "end", "end", "reply", "end", "end" ]
Initialize the connection. @example Initialize the connection. Connection.new("localhost", 27017, 5) @param [ String ] host The host to connect to. @param [ Integer ] post The server port. @param [ Integer ] timeout The connection timeout. @param [ Hash ] options Options for the connection. @option options [ Boolean ] :ssl Connect using SSL @since 1.0.0 Read from the connection. @example Read from the connection. connection.read @return [ Hash ] The returned document. @since 1.0.0
[ "Initialize", "the", "connection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/connection.rb#L114-L139
22,091
mongoid/moped
lib/moped/connection.rb
Moped.Connection.write
def write(operations) buf = "" operations.each do |operation| operation.request_id = (@request_id += 1) operation.serialize(buf) end with_connection do |socket| socket.write(buf) end end
ruby
def write(operations) buf = "" operations.each do |operation| operation.request_id = (@request_id += 1) operation.serialize(buf) end with_connection do |socket| socket.write(buf) end end
[ "def", "write", "(", "operations", ")", "buf", "=", "\"\"", "operations", ".", "each", "do", "|", "operation", "|", "operation", ".", "request_id", "=", "(", "@request_id", "+=", "1", ")", "operation", ".", "serialize", "(", "buf", ")", "end", "with_connection", "do", "|", "socket", "|", "socket", ".", "write", "(", "buf", ")", "end", "end" ]
Write to the connection. @example Write to the connection. connection.write(data) @param [ Array<Message> ] operations The database operations. @return [ Integer ] The number of bytes written. @since 1.0.0
[ "Write", "to", "the", "connection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/connection.rb#L167-L176
22,092
mongoid/moped
lib/moped/connection.rb
Moped.Connection.read_data
def read_data(socket, length) data = socket.read(length) unless data raise Errors::ConnectionFailure.new( "Attempted to read #{length} bytes from the socket but nothing was returned." ) end if data.length < length data << read_data(socket, length - data.length) end data end
ruby
def read_data(socket, length) data = socket.read(length) unless data raise Errors::ConnectionFailure.new( "Attempted to read #{length} bytes from the socket but nothing was returned." ) end if data.length < length data << read_data(socket, length - data.length) end data end
[ "def", "read_data", "(", "socket", ",", "length", ")", "data", "=", "socket", ".", "read", "(", "length", ")", "unless", "data", "raise", "Errors", "::", "ConnectionFailure", ".", "new", "(", "\"Attempted to read #{length} bytes from the socket but nothing was returned.\"", ")", "end", "if", "data", ".", "length", "<", "length", "data", "<<", "read_data", "(", "socket", ",", "length", "-", "data", ".", "length", ")", "end", "data", "end" ]
Read data from the socket until we get back the number of bytes that we are expecting. @api private @example Read the number of bytes. connection.read_data(socket, 36) @param [ TCPSocket ] socket The socket to read from. @param [ Integer ] length The number of bytes to read. @return [ String ] The read data. @since 1.2.9
[ "Read", "data", "from", "the", "socket", "until", "we", "get", "back", "the", "number", "of", "bytes", "that", "we", "are", "expecting", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/connection.rb#L194-L205
22,093
mongoid/moped
lib/moped/node.rb
Moped.Node.command
def command(database, cmd, options = {}) read(Protocol::Command.new(database, cmd, options)) end
ruby
def command(database, cmd, options = {}) read(Protocol::Command.new(database, cmd, options)) end
[ "def", "command", "(", "database", ",", "cmd", ",", "options", "=", "{", "}", ")", "read", "(", "Protocol", "::", "Command", ".", "new", "(", "database", ",", "cmd", ",", "options", ")", ")", "end" ]
Execute a command against a database. @example Execute a command. node.command(database, { ping: 1 }) @param [ Database ] database The database to run the command on. @param [ Hash ] cmd The command to execute. @options [ Hash ] options The command options. @raise [ OperationFailure ] If the command failed. @return [ Hash ] The result of the command. @since 1.0.0
[ "Execute", "a", "command", "against", "a", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L89-L91
22,094
mongoid/moped
lib/moped/node.rb
Moped.Node.connection
def connection connection_acquired = false begin pool.with do |conn| connection_acquired = true yield(conn) end rescue Timeout::Error, ConnectionPool::PoolShuttingDownError => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) raise Errors::PoolTimeout.new(e) end raise connection_acquired ? e : Errors::PoolTimeout.new(e) end end
ruby
def connection connection_acquired = false begin pool.with do |conn| connection_acquired = true yield(conn) end rescue Timeout::Error, ConnectionPool::PoolShuttingDownError => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) raise Errors::PoolTimeout.new(e) end raise connection_acquired ? e : Errors::PoolTimeout.new(e) end end
[ "def", "connection", "connection_acquired", "=", "false", "begin", "pool", ".", "with", "do", "|", "conn", "|", "connection_acquired", "=", "true", "yield", "(", "conn", ")", "end", "rescue", "Timeout", "::", "Error", ",", "ConnectionPool", "::", "PoolShuttingDownError", "=>", "e", "if", "e", ".", "kind_of?", "(", "ConnectionPool", "::", "PoolShuttingDownError", ")", "@pool", "=", "nil", "Connection", "::", "Manager", ".", "delete_pool", "(", "self", ")", "raise", "Errors", "::", "PoolTimeout", ".", "new", "(", "e", ")", "end", "raise", "connection_acquired", "?", "e", ":", "Errors", "::", "PoolTimeout", ".", "new", "(", "e", ")", "end", "end" ]
Get the underlying connection for the node. @example Get the node's connection. node.connection @return [ Connection ] The connection. @since 2.0.0
[ "Get", "the", "underlying", "connection", "for", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L113-L128
22,095
mongoid/moped
lib/moped/node.rb
Moped.Node.ensure_connected
def ensure_connected(&block) unless (conn = stack(:connection)).empty? return yield(conn.first) end begin connection do |conn| connect(conn) unless conn.alive? conn.apply_credentials(@credentials) stack(:connection) << conn yield(conn) end rescue Exception => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) end Failover.get(e).execute(e, self, &block) ensure end_execution(:connection) end end
ruby
def ensure_connected(&block) unless (conn = stack(:connection)).empty? return yield(conn.first) end begin connection do |conn| connect(conn) unless conn.alive? conn.apply_credentials(@credentials) stack(:connection) << conn yield(conn) end rescue Exception => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) end Failover.get(e).execute(e, self, &block) ensure end_execution(:connection) end end
[ "def", "ensure_connected", "(", "&", "block", ")", "unless", "(", "conn", "=", "stack", "(", ":connection", ")", ")", ".", "empty?", "return", "yield", "(", "conn", ".", "first", ")", "end", "begin", "connection", "do", "|", "conn", "|", "connect", "(", "conn", ")", "unless", "conn", ".", "alive?", "conn", ".", "apply_credentials", "(", "@credentials", ")", "stack", "(", ":connection", ")", "<<", "conn", "yield", "(", "conn", ")", "end", "rescue", "Exception", "=>", "e", "if", "e", ".", "kind_of?", "(", "ConnectionPool", "::", "PoolShuttingDownError", ")", "@pool", "=", "nil", "Connection", "::", "Manager", ".", "delete_pool", "(", "self", ")", "end", "Failover", ".", "get", "(", "e", ")", ".", "execute", "(", "e", ",", "self", ",", "block", ")", "ensure", "end_execution", "(", ":connection", ")", "end", "end" ]
Yields the block if a connection can be established, retrying when a connection error is raised. @example Ensure we are connection. node.ensure_connected do #... end @raises [ ConnectionFailure ] When a connection cannot be established. @return [ nil ] nil. @since 1.0.0
[ "Yields", "the", "block", "if", "a", "connection", "can", "be", "established", "retrying", "when", "a", "connection", "error", "is", "raised", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L183-L204
22,096
mongoid/moped
lib/moped/node.rb
Moped.Node.get_more
def get_more(database, collection, cursor_id, limit) read(Protocol::GetMore.new(database, collection, cursor_id, limit)) end
ruby
def get_more(database, collection, cursor_id, limit) read(Protocol::GetMore.new(database, collection, cursor_id, limit)) end
[ "def", "get_more", "(", "database", ",", "collection", ",", "cursor_id", ",", "limit", ")", "read", "(", "Protocol", "::", "GetMore", ".", "new", "(", "database", ",", "collection", ",", "cursor_id", ",", "limit", ")", ")", "end" ]
Execute a get more operation on the node. @example Execute a get more. node.get_more(database, collection, 12345, -1) @param [ Database ] database The database to get more from. @param [ Collection ] collection The collection to get more from. @param [ Integer ] cursor_id The id of the cursor on the server. @param [ Integer ] limit The number of documents to limit. @raise [ CursorNotFound ] if the cursor has been killed @return [ Message ] The result of the operation. @since 1.0.0
[ "Execute", "a", "get", "more", "operation", "on", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L237-L239
22,097
mongoid/moped
lib/moped/node.rb
Moped.Node.insert
def insert(database, collection, documents, concern, options = {}) write(Protocol::Insert.new(database, collection, documents, options), concern) end
ruby
def insert(database, collection, documents, concern, options = {}) write(Protocol::Insert.new(database, collection, documents, options), concern) end
[ "def", "insert", "(", "database", ",", "collection", ",", "documents", ",", "concern", ",", "options", "=", "{", "}", ")", "write", "(", "Protocol", "::", "Insert", ".", "new", "(", "database", ",", "collection", ",", "documents", ",", "options", ")", ",", "concern", ")", "end" ]
Get the hash identifier for the node. @example Get the hash identifier. node.hash @return [ Integer ] The hash identifier. @since 1.0.0 Creat the new node. @example Create the new node. Node.new("127.0.0.1:27017") @param [ String ] address The location of the server node. @param [ Hash ] options Additional options for the node (ssl) @since 1.0.0 Insert documents into the database. @example Insert documents. node.insert(database, collection, [{ name: "Tool" }]) @param [ Database ] database The database to insert to. @param [ Collection ] collection The collection to insert to. @param [ Array<Hash> ] documents The documents to insert. @return [ Message ] The result of the operation. @since 1.0.0
[ "Get", "the", "hash", "identifier", "for", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L287-L289
22,098
mongoid/moped
lib/moped/node.rb
Moped.Node.process
def process(operation, &callback) if executing?(:pipeline) queue.push([ operation, callback ]) else flush([[ operation, callback ]]) end end
ruby
def process(operation, &callback) if executing?(:pipeline) queue.push([ operation, callback ]) else flush([[ operation, callback ]]) end end
[ "def", "process", "(", "operation", ",", "&", "callback", ")", "if", "executing?", "(", ":pipeline", ")", "queue", ".", "push", "(", "[", "operation", ",", "callback", "]", ")", "else", "flush", "(", "[", "[", "operation", ",", "callback", "]", "]", ")", "end", "end" ]
Processes the provided operation on this node, and will execute the callback when the operation is sent to the database. @example Process a read operation. node.process(query) do |reply| return reply.documents end @param [ Message ] operation The database operation. @param [ Proc ] callback The callback to run on operation completion. @return [ Object ] The result of the callback. @since 1.0.0
[ "Processes", "the", "provided", "operation", "on", "this", "node", "and", "will", "execute", "the", "callback", "when", "the", "operation", "is", "sent", "to", "the", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L402-L408
22,099
mongoid/moped
lib/moped/node.rb
Moped.Node.query
def query(database, collection, selector, options = {}) read(Protocol::Query.new(database, collection, selector, options)) end
ruby
def query(database, collection, selector, options = {}) read(Protocol::Query.new(database, collection, selector, options)) end
[ "def", "query", "(", "database", ",", "collection", ",", "selector", ",", "options", "=", "{", "}", ")", "read", "(", "Protocol", "::", "Query", ".", "new", "(", "database", ",", "collection", ",", "selector", ",", "options", ")", ")", "end" ]
Execute a query on the node. @example Execute a query. node.query(database, collection, { name: "Tool" }) @param [ Database ] database The database to query from. @param [ Collection ] collection The collection to query from. @param [ Hash ] selector The query selector. @param [ Hash ] options The query options. @raise [ QueryFailure ] If the query had an error. @return [ Message ] The result of the operation. @since 1.0.0
[ "Execute", "a", "query", "on", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L425-L427