repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.colorize_null
def colorize_null(params = {}, &block) component[:null_colorizer] = (params[:using] or block) component[:null_colorizer] ||= proc do |value| params[:with] end end
ruby
def colorize_null(params = {}, &block) component[:null_colorizer] = (params[:using] or block) component[:null_colorizer] ||= proc do |value| params[:with] end end
[ "def", "colorize_null", "(", "params", "=", "{", "}", ",", "&", "block", ")", "component", "[", ":null_colorizer", "]", "=", "(", "params", "[", ":using", "]", "or", "block", ")", "component", "[", ":null_colorizer", "]", "||=", "proc", "do", "|", "value", "|", "params", "[", ":with", "]", "end", "end" ]
Defines a colorizer to null values. === Args +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the format to use
[ "Defines", "a", "colorizer", "to", "null", "values", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L305-L310
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.format
def format(indexes, params = {}, &block) [*indexes].each do |index| index = parse_index(index) if index component[:formatters][index] = (params[:using] or block) component[:formatters][index] ||= proc do |ctx| params[:with] % ctx.value end else format_null params, &block end end end
ruby
def format(indexes, params = {}, &block) [*indexes].each do |index| index = parse_index(index) if index component[:formatters][index] = (params[:using] or block) component[:formatters][index] ||= proc do |ctx| params[:with] % ctx.value end else format_null params, &block end end end
[ "def", "format", "(", "indexes", ",", "params", "=", "{", "}", ",", "&", "block", ")", "[", "*", "indexes", "]", ".", "each", "do", "|", "index", "|", "index", "=", "parse_index", "(", "index", ")", "if", "index", "component", "[", ":formatters", "]", "[", "index", "]", "=", "(", "params", "[", ":using", "]", "or", "block", ")", "component", "[", ":formatters", "]", "[", "index", "]", "||=", "proc", "do", "|", "ctx", "|", "params", "[", ":with", "]", "%", "ctx", ".", "value", "end", "else", "format_null", "params", ",", "&", "block", "end", "end", "end" ]
Sets a component to format a column. The component must respond to +call+ with the column value as the arguments and return a color or +nil+ if default color should be used. A block can also be used. === Args +indexes+:: The column indexes or its aliases +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the format to use (to use the same format for all columns) === Example table.format :value, :with => '%.2f' table.format [:value, :total], :with => '%.2f'
[ "Sets", "a", "component", "to", "format", "a", "column", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L333-L345
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.format_null
def format_null(params = {}, &block) component[:null_formatter] = (params[:using] or block) component[:null_formatter] ||= proc do |value| params[:with] % value end end
ruby
def format_null(params = {}, &block) component[:null_formatter] = (params[:using] or block) component[:null_formatter] ||= proc do |value| params[:with] % value end end
[ "def", "format_null", "(", "params", "=", "{", "}", ",", "&", "block", ")", "component", "[", ":null_formatter", "]", "=", "(", "params", "[", ":using", "]", "or", "block", ")", "component", "[", ":null_formatter", "]", "||=", "proc", "do", "|", "value", "|", "params", "[", ":with", "]", "%", "value", "end", "end" ]
Defines a formatter to null values. === Args +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the format to use
[ "Defines", "a", "formatter", "to", "null", "values", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L357-L362
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.to_s
def to_s header_output = build_header_output data_output = build_data_output string = '' string << Yummi.colorize(@title, @style[:title]) << $/ if @title string << Yummi.colorize(@description, @style[:description]) << $/ if @description table_data = header_output + data_output if @layout == :vertical # don't use array transpose because the data may differ in each line size table_data = rotate table_data end string << content(table_data) end
ruby
def to_s header_output = build_header_output data_output = build_data_output string = '' string << Yummi.colorize(@title, @style[:title]) << $/ if @title string << Yummi.colorize(@description, @style[:description]) << $/ if @description table_data = header_output + data_output if @layout == :vertical # don't use array transpose because the data may differ in each line size table_data = rotate table_data end string << content(table_data) end
[ "def", "to_s", "header_output", "=", "build_header_output", "data_output", "=", "build_data_output", "string", "=", "''", "string", "<<", "Yummi", ".", "colorize", "(", "@title", ",", "@style", "[", ":title", "]", ")", "<<", "$/", "if", "@title", "string", "<<", "Yummi", ".", "colorize", "(", "@description", ",", "@style", "[", ":description", "]", ")", "<<", "$/", "if", "@description", "table_data", "=", "header_output", "+", "data_output", "if", "@layout", "==", ":vertical", "table_data", "=", "rotate", "table_data", "end", "string", "<<", "content", "(", "table_data", ")", "end" ]
Return a colorized and formatted table.
[ "Return", "a", "colorized", "and", "formatted", "table", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L374-L387
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.width
def width string = to_s max_width = 0 string.each_line do |line| max_width = [max_width, line.uncolored.chomp.size].max end max_width end
ruby
def width string = to_s max_width = 0 string.each_line do |line| max_width = [max_width, line.uncolored.chomp.size].max end max_width end
[ "def", "width", "string", "=", "to_s", "max_width", "=", "0", "string", ".", "each_line", "do", "|", "line", "|", "max_width", "=", "[", "max_width", ",", "line", ".", "uncolored", ".", "chomp", ".", "size", "]", ".", "max", "end", "max_width", "end" ]
Calculates the table width using the rendered lines
[ "Calculates", "the", "table", "width", "using", "the", "rendered", "lines" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L392-L399
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.content
def content (data) string = '' data.each_index do |i| row = data[i] row.each_index do |j| column = row[j] column ||= {:value => nil, :color => nil} width = max_width data, j alignment = (@align[j] or @default_align) value = Aligner.align alignment, column[:value].to_s, width value = Yummi.colorize value, column[:color] unless @no_colors string << value string << (' ' * @colspan) end string.strip! << $/ end string end
ruby
def content (data) string = '' data.each_index do |i| row = data[i] row.each_index do |j| column = row[j] column ||= {:value => nil, :color => nil} width = max_width data, j alignment = (@align[j] or @default_align) value = Aligner.align alignment, column[:value].to_s, width value = Yummi.colorize value, column[:color] unless @no_colors string << value string << (' ' * @colspan) end string.strip! << $/ end string end
[ "def", "content", "(", "data", ")", "string", "=", "''", "data", ".", "each_index", "do", "|", "i", "|", "row", "=", "data", "[", "i", "]", "row", ".", "each_index", "do", "|", "j", "|", "column", "=", "row", "[", "j", "]", "column", "||=", "{", ":value", "=>", "nil", ",", ":color", "=>", "nil", "}", "width", "=", "max_width", "data", ",", "j", "alignment", "=", "(", "@align", "[", "j", "]", "or", "@default_align", ")", "value", "=", "Aligner", ".", "align", "alignment", ",", "column", "[", ":value", "]", ".", "to_s", ",", "width", "value", "=", "Yummi", ".", "colorize", "value", ",", "column", "[", ":color", "]", "unless", "@no_colors", "string", "<<", "value", "string", "<<", "(", "' '", "*", "@colspan", ")", "end", "string", ".", "strip!", "<<", "$/", "end", "string", "end" ]
Gets the content string for the given color map and content
[ "Gets", "the", "content", "string", "for", "the", "given", "color", "map", "and", "content" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L436-L453
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.build_header_output
def build_header_output output = [] @header.each do |line| _data = [] line.each do |h| _data << {:value => h, :color => @style[:header]} end output << _data end output end
ruby
def build_header_output output = [] @header.each do |line| _data = [] line.each do |h| _data << {:value => h, :color => @style[:header]} end output << _data end output end
[ "def", "build_header_output", "output", "=", "[", "]", "@header", ".", "each", "do", "|", "line", "|", "_data", "=", "[", "]", "line", ".", "each", "do", "|", "h", "|", "_data", "<<", "{", ":value", "=>", "h", ",", ":color", "=>", "@style", "[", ":header", "]", "}", "end", "output", "<<", "_data", "end", "output", "end" ]
Builds the header output for this table. Returns the color map and the header.
[ "Builds", "the", "header", "output", "for", "this", "table", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L460-L471
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.build_row_contexts
def build_row_contexts rows = @data.size row_contexts = [:default] * rows offset = 0 @contexts.each do |ctx| if ctx == :default break end size = ctx[:rows] row_contexts[offset...(size + offset)] = [ctx[:id]] * size offset += size end @contexts.reverse_each do |ctx| if ctx == :default break end size = ctx[:rows] row_contexts[(rows - size)...rows] = [ctx[:id]] * size rows -= size end row_contexts end
ruby
def build_row_contexts rows = @data.size row_contexts = [:default] * rows offset = 0 @contexts.each do |ctx| if ctx == :default break end size = ctx[:rows] row_contexts[offset...(size + offset)] = [ctx[:id]] * size offset += size end @contexts.reverse_each do |ctx| if ctx == :default break end size = ctx[:rows] row_contexts[(rows - size)...rows] = [ctx[:id]] * size rows -= size end row_contexts end
[ "def", "build_row_contexts", "rows", "=", "@data", ".", "size", "row_contexts", "=", "[", ":default", "]", "*", "rows", "offset", "=", "0", "@contexts", ".", "each", "do", "|", "ctx", "|", "if", "ctx", "==", ":default", "break", "end", "size", "=", "ctx", "[", ":rows", "]", "row_contexts", "[", "offset", "...", "(", "size", "+", "offset", ")", "]", "=", "[", "ctx", "[", ":id", "]", "]", "*", "size", "offset", "+=", "size", "end", "@contexts", ".", "reverse_each", "do", "|", "ctx", "|", "if", "ctx", "==", ":default", "break", "end", "size", "=", "ctx", "[", ":rows", "]", "row_contexts", "[", "(", "rows", "-", "size", ")", "...", "rows", "]", "=", "[", "ctx", "[", ":id", "]", "]", "*", "size", "rows", "-=", "size", "end", "row_contexts", "end" ]
maps the context for each row
[ "maps", "the", "context", "for", "each", "row" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L474-L495
train
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.build_data_output
def build_data_output output = [] row_contexts = build_row_contexts @data.each_index do |row_index| # sets the current context @current_context = row_contexts[row_index] row = row_to_array(@data[row_index], row_index) _row_data = [] row.each_index do |col_index| next if not @header.empty? and @header[0].size < col_index + 1 column = row[col_index] colorizer = component[:colorizers][col_index] color = if component[:null_colorizer] and column.value.nil? component[:null_colorizer].call(column) elsif colorizer colorizer.call(column) else @style[:value] end formatter = if column.value.nil? @null_formatter else component[:formatters][col_index] end value = if formatter formatter.call(column) else column.value end _row_data << {:value => value, :color => color} end row_colorizer = component[:row_colorizer] if row_colorizer row_color = row_colorizer.call row.first _row_data.collect! { |data| data[:color] = row_color; data } if row_color end _row_data = normalize( _row_data, :extract => proc do |data| data[:value].to_s end, :new => proc do |value, data| {:value => value, :color => data[:color]} end ) _row_data.each do |_row| output << _row end end output end
ruby
def build_data_output output = [] row_contexts = build_row_contexts @data.each_index do |row_index| # sets the current context @current_context = row_contexts[row_index] row = row_to_array(@data[row_index], row_index) _row_data = [] row.each_index do |col_index| next if not @header.empty? and @header[0].size < col_index + 1 column = row[col_index] colorizer = component[:colorizers][col_index] color = if component[:null_colorizer] and column.value.nil? component[:null_colorizer].call(column) elsif colorizer colorizer.call(column) else @style[:value] end formatter = if column.value.nil? @null_formatter else component[:formatters][col_index] end value = if formatter formatter.call(column) else column.value end _row_data << {:value => value, :color => color} end row_colorizer = component[:row_colorizer] if row_colorizer row_color = row_colorizer.call row.first _row_data.collect! { |data| data[:color] = row_color; data } if row_color end _row_data = normalize( _row_data, :extract => proc do |data| data[:value].to_s end, :new => proc do |value, data| {:value => value, :color => data[:color]} end ) _row_data.each do |_row| output << _row end end output end
[ "def", "build_data_output", "output", "=", "[", "]", "row_contexts", "=", "build_row_contexts", "@data", ".", "each_index", "do", "|", "row_index", "|", "@current_context", "=", "row_contexts", "[", "row_index", "]", "row", "=", "row_to_array", "(", "@data", "[", "row_index", "]", ",", "row_index", ")", "_row_data", "=", "[", "]", "row", ".", "each_index", "do", "|", "col_index", "|", "next", "if", "not", "@header", ".", "empty?", "and", "@header", "[", "0", "]", ".", "size", "<", "col_index", "+", "1", "column", "=", "row", "[", "col_index", "]", "colorizer", "=", "component", "[", ":colorizers", "]", "[", "col_index", "]", "color", "=", "if", "component", "[", ":null_colorizer", "]", "and", "column", ".", "value", ".", "nil?", "component", "[", ":null_colorizer", "]", ".", "call", "(", "column", ")", "elsif", "colorizer", "colorizer", ".", "call", "(", "column", ")", "else", "@style", "[", ":value", "]", "end", "formatter", "=", "if", "column", ".", "value", ".", "nil?", "@null_formatter", "else", "component", "[", ":formatters", "]", "[", "col_index", "]", "end", "value", "=", "if", "formatter", "formatter", ".", "call", "(", "column", ")", "else", "column", ".", "value", "end", "_row_data", "<<", "{", ":value", "=>", "value", ",", ":color", "=>", "color", "}", "end", "row_colorizer", "=", "component", "[", ":row_colorizer", "]", "if", "row_colorizer", "row_color", "=", "row_colorizer", ".", "call", "row", ".", "first", "_row_data", ".", "collect!", "{", "|", "data", "|", "data", "[", ":color", "]", "=", "row_color", ";", "data", "}", "if", "row_color", "end", "_row_data", "=", "normalize", "(", "_row_data", ",", ":extract", "=>", "proc", "do", "|", "data", "|", "data", "[", ":value", "]", ".", "to_s", "end", ",", ":new", "=>", "proc", "do", "|", "value", ",", "data", "|", "{", ":value", "=>", "value", ",", ":color", "=>", "data", "[", ":color", "]", "}", "end", ")", "_row_data", ".", "each", "do", "|", "_row", "|", "output", "<<", "_row", "end", "end", "output", "end" ]
Builds the data output for this table. Returns the color map and the formatted data.
[ "Builds", "the", "data", "output", "for", "this", "table", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L502-L553
train
sleewoo/tokyo
lib/tokyo/assert.rb
Tokyo.Assert.raise
def raise type = nil, message = nil, &block failure = Tokyo.__send__( @assert ? :assert_raised_as_expected : :refute_raised_as_expected, @object, type, message, block ) Tokyo.fail(failure, caller[0]) if failure end
ruby
def raise type = nil, message = nil, &block failure = Tokyo.__send__( @assert ? :assert_raised_as_expected : :refute_raised_as_expected, @object, type, message, block ) Tokyo.fail(failure, caller[0]) if failure end
[ "def", "raise", "type", "=", "nil", ",", "message", "=", "nil", ",", "&", "block", "failure", "=", "Tokyo", ".", "__send__", "(", "@assert", "?", ":assert_raised_as_expected", ":", ":refute_raised_as_expected", ",", "@object", ",", "type", ",", "message", ",", "block", ")", "Tokyo", ".", "fail", "(", "failure", ",", "caller", "[", "0", "]", ")", "if", "failure", "end" ]
ensure the given block raises as expected @note if block given it will have precedence over arguments @example assertion pass if block raises whatever assert {some code}.raise @example assertion pass if block raises NameError assert {some code}.raise NameError @example assertion pass if block raises NameError and error message matches /blah/ assert {some code}.raise NameError, /blah/ @example assertion pass if block raises whatever error that matches /blah/ assert {some code}.raise nil, /blah/ @example assertion pass if validation block returns a positive value assert {some code}.raise {|e| e.is_a?(NameError) && e.message =~ /blah/} @example assertion pass if nothing raised refute {some code}.raise # same fail_if {some code}.raise @example assertion fails only if block raises a NameError. it may raise whatever but NameError. if nothing raised assertion will fail. fail_if {some code}.raise NameError @example assertion pass if raised error does not match /blah/ if nothing raised assertion will fail. fail_if {some code}.raise nil, /blah/ @example assertion will pass if raised error is not a NameError and error message does not match /blah/ if nothing raised assertion will fail as well. fail_if {some code}.raise NameError, /blah/
[ "ensure", "the", "given", "block", "raises", "as", "expected" ]
bcd0a031b535dadce13039acde81aef3d16454e0
https://github.com/sleewoo/tokyo/blob/bcd0a031b535dadce13039acde81aef3d16454e0/lib/tokyo/assert.rb#L76-L82
train
sleewoo/tokyo
lib/tokyo/assert.rb
Tokyo.Assert.throw
def throw expected_symbol = nil, &block failure = Tokyo.__send__( @assert ? :assert_thrown_as_expected : :refute_thrown_as_expected, @object, expected_symbol ? expected_symbol.to_sym : nil, block ) Tokyo.fail(failure, caller[0]) if failure end
ruby
def throw expected_symbol = nil, &block failure = Tokyo.__send__( @assert ? :assert_thrown_as_expected : :refute_thrown_as_expected, @object, expected_symbol ? expected_symbol.to_sym : nil, block ) Tokyo.fail(failure, caller[0]) if failure end
[ "def", "throw", "expected_symbol", "=", "nil", ",", "&", "block", "failure", "=", "Tokyo", ".", "__send__", "(", "@assert", "?", ":assert_thrown_as_expected", ":", ":refute_thrown_as_expected", ",", "@object", ",", "expected_symbol", "?", "expected_symbol", ".", "to_sym", ":", "nil", ",", "block", ")", "Tokyo", ".", "fail", "(", "failure", ",", "caller", "[", "0", "]", ")", "if", "failure", "end" ]
ensure given block thrown as expected @note if block given it will have precedence over arguments @example assertion pass if any symbol thrown assert {some code}.throw @example assertion pass only if :x symbol thrown assert {some code}.throw(:x) @example assertion pass only if given block validates thrown symbol assert {some code}.throw {|sym| sym == :x}
[ "ensure", "given", "block", "thrown", "as", "expected" ]
bcd0a031b535dadce13039acde81aef3d16454e0
https://github.com/sleewoo/tokyo/blob/bcd0a031b535dadce13039acde81aef3d16454e0/lib/tokyo/assert.rb#L98-L104
train
flipback/lipa
lib/lipa/node.rb
Lipa.Node.eval_attrs
def eval_attrs result = {} @attrs.each_pair do |k,v| result[k.to_sym] = instance_eval(k.to_s) end result end
ruby
def eval_attrs result = {} @attrs.each_pair do |k,v| result[k.to_sym] = instance_eval(k.to_s) end result end
[ "def", "eval_attrs", "result", "=", "{", "}", "@attrs", ".", "each_pair", "do", "|", "k", ",", "v", "|", "result", "[", "k", ".", "to_sym", "]", "=", "instance_eval", "(", "k", ".", "to_s", ")", "end", "result", "end" ]
Copy attributes with eval @retun [Hash] hash @example node :some_node d: param_1 1 param_2 run{ param_1 + 2} end node.attrs #=> {:param_1 => 1, :param_2 => Proc} node.eval_attrs #=> {:param_1 => 1, :param_2 => 3}
[ "Copy", "attributes", "with", "eval" ]
d735846c09473525df812fa829141a83aa2b385d
https://github.com/flipback/lipa/blob/d735846c09473525df812fa829141a83aa2b385d/lib/lipa/node.rb#L96-L102
train
CruGlobal/cru-auth-lib
lib/cru_auth_lib/access_token_protected_concern.rb
CruAuthLib.AccessTokenProtectedConcern.oauth_access_token_from_header
def oauth_access_token_from_header auth_header = request.env['HTTP_AUTHORIZATION'] || '' match = auth_header.match(/^Bearer\s(.*)/) return match[1] if match.present? false end
ruby
def oauth_access_token_from_header auth_header = request.env['HTTP_AUTHORIZATION'] || '' match = auth_header.match(/^Bearer\s(.*)/) return match[1] if match.present? false end
[ "def", "oauth_access_token_from_header", "auth_header", "=", "request", ".", "env", "[", "'HTTP_AUTHORIZATION'", "]", "||", "''", "match", "=", "auth_header", ".", "match", "(", "/", "\\s", "/", ")", "return", "match", "[", "1", "]", "if", "match", ".", "present?", "false", "end" ]
grabs access_token from header if one is present
[ "grabs", "access_token", "from", "header", "if", "one", "is", "present" ]
e25d4100236ee6fa062d9a8350ec4c207827c584
https://github.com/CruGlobal/cru-auth-lib/blob/e25d4100236ee6fa062d9a8350ec4c207827c584/lib/cru_auth_lib/access_token_protected_concern.rb#L20-L25
train
vladson/xml_dsl
lib/xml_dsl/block_method.rb
XmlDsl.BlockMethod.call
def call(a, b = nil, c = nil) if block self.send method, *[a, b, c].compact + args, &block else self.send method, *[a, b, c].compact + args end end
ruby
def call(a, b = nil, c = nil) if block self.send method, *[a, b, c].compact + args, &block else self.send method, *[a, b, c].compact + args end end
[ "def", "call", "(", "a", ",", "b", "=", "nil", ",", "c", "=", "nil", ")", "if", "block", "self", ".", "send", "method", ",", "*", "[", "a", ",", "b", ",", "c", "]", ".", "compact", "+", "args", ",", "&", "block", "else", "self", ".", "send", "method", ",", "*", "[", "a", ",", "b", ",", "c", "]", ".", "compact", "+", "args", "end", "end" ]
order of params to be called can differ, so naming is ambiguous
[ "order", "of", "params", "to", "be", "called", "can", "differ", "so", "naming", "is", "ambiguous" ]
dc96eb41df35617bf8740f225e7218df4c674bb0
https://github.com/vladson/xml_dsl/blob/dc96eb41df35617bf8740f225e7218df4c674bb0/lib/xml_dsl/block_method.rb#L11-L17
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.load
def load( typecode ) offset = 0 typecode.typecodes.collect do |t| value = GCCValue.new @function, "*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} )" offset += t.storage_size value end end
ruby
def load( typecode ) offset = 0 typecode.typecodes.collect do |t| value = GCCValue.new @function, "*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} )" offset += t.storage_size value end end
[ "def", "load", "(", "typecode", ")", "offset", "=", "0", "typecode", ".", "typecodes", ".", "collect", "do", "|", "t", "|", "value", "=", "GCCValue", ".", "new", "@function", ",", "\"*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} )\"", "offset", "+=", "t", ".", "storage_size", "value", "end", "end" ]
Add code to read all components of a typed value from memory @return [Array<GCCValue>] An array of objects referencing values in C. @private
[ "Add", "code", "to", "read", "all", "components", "of", "a", "typed", "value", "from", "memory" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L185-L193
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.save
def save( value ) offset = 0 value.class.typecodes.zip( value.values ).each do |t,v| @function << "#{@function.indent}*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} ) = #{v};\n" offset += t.storage_size end end
ruby
def save( value ) offset = 0 value.class.typecodes.zip( value.values ).each do |t,v| @function << "#{@function.indent}*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} ) = #{v};\n" offset += t.storage_size end end
[ "def", "save", "(", "value", ")", "offset", "=", "0", "value", ".", "class", ".", "typecodes", ".", "zip", "(", "value", ".", "values", ")", ".", "each", "do", "|", "t", ",", "v", "|", "@function", "<<", "\"#{@function.indent}*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} ) = #{v};\\n\"", "offset", "+=", "t", ".", "storage_size", "end", "end" ]
Add code to write all components of a typed value to memory @param [Node] value Value to write to memory. @return [Object] The return value should be ignored. @private
[ "Add", "code", "to", "write", "all", "components", "of", "a", "typed", "value", "to", "memory" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L202-L208
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.conditional
def conditional( a, b ) if a.is_a?( Proc ) and b.is_a?( Proc ) conditional a.call, b.call else GCCValue.new @function, "( #{self} ) ? ( #{a} ) : ( #{b} )" end end
ruby
def conditional( a, b ) if a.is_a?( Proc ) and b.is_a?( Proc ) conditional a.call, b.call else GCCValue.new @function, "( #{self} ) ? ( #{a} ) : ( #{b} )" end end
[ "def", "conditional", "(", "a", ",", "b", ")", "if", "a", ".", "is_a?", "(", "Proc", ")", "and", "b", ".", "is_a?", "(", "Proc", ")", "conditional", "a", ".", "call", ",", "b", ".", "call", "else", "GCCValue", ".", "new", "@function", ",", "\"( #{self} ) ? ( #{a} ) : ( #{b} )\"", "end", "end" ]
Create code for conditional selection of value @param [GCCValue,Object] a First value. @param [GCCValue,Object] b Second value. @return [GCCValue] C value referring to result. @private
[ "Create", "code", "for", "conditional", "selection", "of", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L299-L305
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.if_else
def if_else( action1, action2 ) @function << "#{@function.indent}if ( #{self} ) {\n" @function.indent_offset +1 action1.call @function.indent_offset -1 @function << "#{@function.indent}} else {\n" @function.indent_offset +1 action2.call @function.indent_offset -1 @function << "#{@function.indent}};\n" self end
ruby
def if_else( action1, action2 ) @function << "#{@function.indent}if ( #{self} ) {\n" @function.indent_offset +1 action1.call @function.indent_offset -1 @function << "#{@function.indent}} else {\n" @function.indent_offset +1 action2.call @function.indent_offset -1 @function << "#{@function.indent}};\n" self end
[ "def", "if_else", "(", "action1", ",", "action2", ")", "@function", "<<", "\"#{@function.indent}if ( #{self} ) {\\n\"", "@function", ".", "indent_offset", "+", "1", "action1", ".", "call", "@function", ".", "indent_offset", "-", "1", "@function", "<<", "\"#{@function.indent}} else {\\n\"", "@function", ".", "indent_offset", "+", "1", "action2", ".", "call", "@function", ".", "indent_offset", "-", "1", "@function", "<<", "\"#{@function.indent}};\\n\"", "self", "end" ]
Generate code for conditional statement @param [Proc] action1 Block to run when condition is fullfilled. @param [Proc] action2 Block to run otherwise. @return [Object] Returns +self+. @private
[ "Generate", "code", "for", "conditional", "statement" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L331-L342
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.**
def **( other ) if GCCValue.generic? other GCCValue.new @function, "pow( #{self}, #{other} )" else x, y = other.coerce self x ** y end end
ruby
def **( other ) if GCCValue.generic? other GCCValue.new @function, "pow( #{self}, #{other} )" else x, y = other.coerce self x ** y end end
[ "def", "**", "(", "other", ")", "if", "GCCValue", ".", "generic?", "other", "GCCValue", ".", "new", "@function", ",", "\"pow( #{self}, #{other} )\"", "else", "x", ",", "y", "=", "other", ".", "coerce", "self", "x", "**", "y", "end", "end" ]
Generate code for computing exponentiation @param [Object,GCCValue] other Second operand for binary operation. @return [GCCValue] C value refering to the result. @private
[ "Generate", "code", "for", "computing", "exponentiation" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L437-L444
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.conditional_with_rgb
def conditional_with_rgb( a, b ) if a.is_a?(RGB) or b.is_a?(RGB) Hornetseye::RGB conditional(a.r, b.r), conditional(a.g, b.g), conditional(a.b, b.b) else conditional_without_rgb a, b end end
ruby
def conditional_with_rgb( a, b ) if a.is_a?(RGB) or b.is_a?(RGB) Hornetseye::RGB conditional(a.r, b.r), conditional(a.g, b.g), conditional(a.b, b.b) else conditional_without_rgb a, b end end
[ "def", "conditional_with_rgb", "(", "a", ",", "b", ")", "if", "a", ".", "is_a?", "(", "RGB", ")", "or", "b", ".", "is_a?", "(", "RGB", ")", "Hornetseye", "::", "RGB", "conditional", "(", "a", ".", "r", ",", "b", ".", "r", ")", ",", "conditional", "(", "a", ".", "g", ",", "b", ".", "g", ")", ",", "conditional", "(", "a", ".", "b", ",", "b", ".", "b", ")", "else", "conditional_without_rgb", "a", ",", "b", "end", "end" ]
Create code for conditional selection of RGB value @param [GCCValue,Object] a First value. @param [GCCValue,Object] b Second value. @return [GCCValue] C value referring to result. @private
[ "Create", "code", "for", "conditional", "selection", "of", "RGB", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L496-L502
train
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.conditional_with_complex
def conditional_with_complex( a, b ) if a.is_a?( InternalComplex ) or b.is_a?( InternalComplex ) InternalComplex.new conditional( a.real, b.real ), conditional( a.imag, b.imag ) else conditional_without_complex a, b end end
ruby
def conditional_with_complex( a, b ) if a.is_a?( InternalComplex ) or b.is_a?( InternalComplex ) InternalComplex.new conditional( a.real, b.real ), conditional( a.imag, b.imag ) else conditional_without_complex a, b end end
[ "def", "conditional_with_complex", "(", "a", ",", "b", ")", "if", "a", ".", "is_a?", "(", "InternalComplex", ")", "or", "b", ".", "is_a?", "(", "InternalComplex", ")", "InternalComplex", ".", "new", "conditional", "(", "a", ".", "real", ",", "b", ".", "real", ")", ",", "conditional", "(", "a", ".", "imag", ",", "b", ".", "imag", ")", "else", "conditional_without_complex", "a", ",", "b", "end", "end" ]
Create code for conditional selection of complex value @param [GCCValue,Object] a First value. @param [GCCValue,Object] b Second value. @return [GCCValue] C value referring to result. @private
[ "Create", "code", "for", "conditional", "selection", "of", "complex", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L514-L521
train
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.build_env
def build_env(client, req) rack_env = DefaultRackEnv.dup req.fill_rack_env(rack_env) rack_env["SERVER_PORT"] ||= @port.to_s if (rack_env["rack.input"].respond_to? :set_encoding) rack_env["rack.input"].set_encoding "ASCII-8BIT" end rack_env["REMOTE_PORT"], rack_env["REMOTE_ADDR"] = Socket::unpack_sockaddr_in(client.getpeername) rack_env["REMOTE_PORT"] &&= rack_env["REMOTE_PORT"].to_s rack_env["SERVER_PROTOCOL"] = "HTTP/" << req.version.join('.') return rack_env end
ruby
def build_env(client, req) rack_env = DefaultRackEnv.dup req.fill_rack_env(rack_env) rack_env["SERVER_PORT"] ||= @port.to_s if (rack_env["rack.input"].respond_to? :set_encoding) rack_env["rack.input"].set_encoding "ASCII-8BIT" end rack_env["REMOTE_PORT"], rack_env["REMOTE_ADDR"] = Socket::unpack_sockaddr_in(client.getpeername) rack_env["REMOTE_PORT"] &&= rack_env["REMOTE_PORT"].to_s rack_env["SERVER_PROTOCOL"] = "HTTP/" << req.version.join('.') return rack_env end
[ "def", "build_env", "(", "client", ",", "req", ")", "rack_env", "=", "DefaultRackEnv", ".", "dup", "req", ".", "fill_rack_env", "(", "rack_env", ")", "rack_env", "[", "\"SERVER_PORT\"", "]", "||=", "@port", ".", "to_s", "if", "(", "rack_env", "[", "\"rack.input\"", "]", ".", "respond_to?", ":set_encoding", ")", "rack_env", "[", "\"rack.input\"", "]", ".", "set_encoding", "\"ASCII-8BIT\"", "end", "rack_env", "[", "\"REMOTE_PORT\"", "]", ",", "rack_env", "[", "\"REMOTE_ADDR\"", "]", "=", "Socket", "::", "unpack_sockaddr_in", "(", "client", ".", "getpeername", ")", "rack_env", "[", "\"REMOTE_PORT\"", "]", "&&=", "rack_env", "[", "\"REMOTE_PORT\"", "]", ".", "to_s", "rack_env", "[", "\"SERVER_PROTOCOL\"", "]", "=", "\"HTTP/\"", "<<", "req", ".", "version", ".", "join", "(", "'.'", ")", "return", "rack_env", "end" ]
Builds an env object from the information provided. Derived handlers can override this to provide additional information.
[ "Builds", "an", "env", "object", "from", "the", "information", "provided", ".", "Derived", "handlers", "can", "override", "this", "to", "provide", "additional", "information", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L97-L111
train
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.chunked_read
def chunked_read(io, timeout) begin loop do list = IO.select([io], [], [], @read_timeout) if (list.nil? || list.empty?) # IO.select tells us we timed out by giving us nil, # disconnect the non-talkative client. return end data = io.recv(4096) if (data == "") # If recv returns an empty string, that means the other # end closed the connection (either in response to our # end closing the write pipe or because they just felt # like it) so we close the connection from our end too. return end yield data end ensure io.close if (!io.closed?) end end
ruby
def chunked_read(io, timeout) begin loop do list = IO.select([io], [], [], @read_timeout) if (list.nil? || list.empty?) # IO.select tells us we timed out by giving us nil, # disconnect the non-talkative client. return end data = io.recv(4096) if (data == "") # If recv returns an empty string, that means the other # end closed the connection (either in response to our # end closing the write pipe or because they just felt # like it) so we close the connection from our end too. return end yield data end ensure io.close if (!io.closed?) end end
[ "def", "chunked_read", "(", "io", ",", "timeout", ")", "begin", "loop", "do", "list", "=", "IO", ".", "select", "(", "[", "io", "]", ",", "[", "]", ",", "[", "]", ",", "@read_timeout", ")", "if", "(", "list", ".", "nil?", "||", "list", ".", "empty?", ")", "return", "end", "data", "=", "io", ".", "recv", "(", "4096", ")", "if", "(", "data", "==", "\"\"", ")", "return", "end", "yield", "data", "end", "ensure", "io", ".", "close", "if", "(", "!", "io", ".", "closed?", ")", "end", "end" ]
Reads from a connection, yielding chunks of data as it goes, until the connection closes. Once the connection closes, it returns.
[ "Reads", "from", "a", "connection", "yielding", "chunks", "of", "data", "as", "it", "goes", "until", "the", "connection", "closes", ".", "Once", "the", "connection", "closes", "it", "returns", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L116-L138
train
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.process_client
def process_client(app) loop do client = nil begin make_interruptable do client = @listener.synchronize do begin @listener && @listener.accept() rescue => e return # this means we've been turned off, so exit the loop. end end if (!client) return # nil return means we're quitting, exit loop. end end req = Http::Parser.new() buf = "" chunked_read(client, @timeout) do |data| begin buf << data req.parse!(buf) if (req.done?) process_request(client, req, app) req = Http::Parser.new() if (@listener.closed?) return # ignore any more requests from this client if we're shutting down. end end rescue Http::ParserError => e err_str = "<h2>#{e.code} #{e.message}</h2>" client.write("HTTP/1.1 #{e.code} #{e.message}\r\n") client.write("Connection: close\r\n") client.write("Content-Length: #{err_str.length}\r\n") client.write("Content-Type: text/html\r\n") client.write("\r\n") client.write(err_str) client.close_write end end rescue Errno::EPIPE # do nothing, just let the connection close. rescue SystemExit, GracefulExit raise # pass it on. rescue Object => e $stderr.puts("Unhandled error #{e}:") e.backtrace.each do |line| $stderr.puts(line) end ensure client.close if (client && !client.closed?) end end end
ruby
def process_client(app) loop do client = nil begin make_interruptable do client = @listener.synchronize do begin @listener && @listener.accept() rescue => e return # this means we've been turned off, so exit the loop. end end if (!client) return # nil return means we're quitting, exit loop. end end req = Http::Parser.new() buf = "" chunked_read(client, @timeout) do |data| begin buf << data req.parse!(buf) if (req.done?) process_request(client, req, app) req = Http::Parser.new() if (@listener.closed?) return # ignore any more requests from this client if we're shutting down. end end rescue Http::ParserError => e err_str = "<h2>#{e.code} #{e.message}</h2>" client.write("HTTP/1.1 #{e.code} #{e.message}\r\n") client.write("Connection: close\r\n") client.write("Content-Length: #{err_str.length}\r\n") client.write("Content-Type: text/html\r\n") client.write("\r\n") client.write(err_str) client.close_write end end rescue Errno::EPIPE # do nothing, just let the connection close. rescue SystemExit, GracefulExit raise # pass it on. rescue Object => e $stderr.puts("Unhandled error #{e}:") e.backtrace.each do |line| $stderr.puts(line) end ensure client.close if (client && !client.closed?) end end end
[ "def", "process_client", "(", "app", ")", "loop", "do", "client", "=", "nil", "begin", "make_interruptable", "do", "client", "=", "@listener", ".", "synchronize", "do", "begin", "@listener", "&&", "@listener", ".", "accept", "(", ")", "rescue", "=>", "e", "return", "end", "end", "if", "(", "!", "client", ")", "return", "end", "end", "req", "=", "Http", "::", "Parser", ".", "new", "(", ")", "buf", "=", "\"\"", "chunked_read", "(", "client", ",", "@timeout", ")", "do", "|", "data", "|", "begin", "buf", "<<", "data", "req", ".", "parse!", "(", "buf", ")", "if", "(", "req", ".", "done?", ")", "process_request", "(", "client", ",", "req", ",", "app", ")", "req", "=", "Http", "::", "Parser", ".", "new", "(", ")", "if", "(", "@listener", ".", "closed?", ")", "return", "end", "end", "rescue", "Http", "::", "ParserError", "=>", "e", "err_str", "=", "\"<h2>#{e.code} #{e.message}</h2>\"", "client", ".", "write", "(", "\"HTTP/1.1 #{e.code} #{e.message}\\r\\n\"", ")", "client", ".", "write", "(", "\"Connection: close\\r\\n\"", ")", "client", ".", "write", "(", "\"Content-Length: #{err_str.length}\\r\\n\"", ")", "client", ".", "write", "(", "\"Content-Type: text/html\\r\\n\"", ")", "client", ".", "write", "(", "\"\\r\\n\"", ")", "client", ".", "write", "(", "err_str", ")", "client", ".", "close_write", "end", "end", "rescue", "Errno", "::", "EPIPE", "rescue", "SystemExit", ",", "GracefulExit", "raise", "rescue", "Object", "=>", "e", "$stderr", ".", "puts", "(", "\"Unhandled error #{e}:\"", ")", "e", ".", "backtrace", ".", "each", "do", "|", "line", "|", "$stderr", ".", "puts", "(", "line", ")", "end", "ensure", "client", ".", "close", "if", "(", "client", "&&", "!", "client", ".", "closed?", ")", "end", "end", "end" ]
Accepts a connection from a client and handles requests on it until the connection closes.
[ "Accepts", "a", "connection", "from", "a", "client", "and", "handles", "requests", "on", "it", "until", "the", "connection", "closes", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L252-L306
train
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.run
def run(app) synchronize do @interruptable = [] int_orig = trap "INT" do stop() end term_orig = trap "TERM" do stop() end begin @listener = create_listener(@options) @interruptable.extend Mutex_m if (@max_clients > 1) @master = Thread.current @workers = (0...@max_clients).collect do Thread.new do begin process_client(app) rescue GracefulExit, SystemExit => e # let it exit. rescue => e $stderr.puts("Handler thread unexpectedly died with #{e}:", e.backtrace) end end end @workers.each do |worker| worker.join end else begin @master = Thread.current @workers = [Thread.current] process_client(app) rescue GracefulExit, SystemExit => e # let it exit rescue => e $stderr.puts("Handler thread unexpectedly died with #{e}:", e.backtrace) end end ensure trap "INT", int_orig trap "TERM", term_orig @listener.close if (@listener && [email protected]?) @interruptable = @listener = @master = @workers = nil end end end
ruby
def run(app) synchronize do @interruptable = [] int_orig = trap "INT" do stop() end term_orig = trap "TERM" do stop() end begin @listener = create_listener(@options) @interruptable.extend Mutex_m if (@max_clients > 1) @master = Thread.current @workers = (0...@max_clients).collect do Thread.new do begin process_client(app) rescue GracefulExit, SystemExit => e # let it exit. rescue => e $stderr.puts("Handler thread unexpectedly died with #{e}:", e.backtrace) end end end @workers.each do |worker| worker.join end else begin @master = Thread.current @workers = [Thread.current] process_client(app) rescue GracefulExit, SystemExit => e # let it exit rescue => e $stderr.puts("Handler thread unexpectedly died with #{e}:", e.backtrace) end end ensure trap "INT", int_orig trap "TERM", term_orig @listener.close if (@listener && [email protected]?) @interruptable = @listener = @master = @workers = nil end end end
[ "def", "run", "(", "app", ")", "synchronize", "do", "@interruptable", "=", "[", "]", "int_orig", "=", "trap", "\"INT\"", "do", "stop", "(", ")", "end", "term_orig", "=", "trap", "\"TERM\"", "do", "stop", "(", ")", "end", "begin", "@listener", "=", "create_listener", "(", "@options", ")", "@interruptable", ".", "extend", "Mutex_m", "if", "(", "@max_clients", ">", "1", ")", "@master", "=", "Thread", ".", "current", "@workers", "=", "(", "0", "...", "@max_clients", ")", ".", "collect", "do", "Thread", ".", "new", "do", "begin", "process_client", "(", "app", ")", "rescue", "GracefulExit", ",", "SystemExit", "=>", "e", "rescue", "=>", "e", "$stderr", ".", "puts", "(", "\"Handler thread unexpectedly died with #{e}:\"", ",", "e", ".", "backtrace", ")", "end", "end", "end", "@workers", ".", "each", "do", "|", "worker", "|", "worker", ".", "join", "end", "else", "begin", "@master", "=", "Thread", ".", "current", "@workers", "=", "[", "Thread", ".", "current", "]", "process_client", "(", "app", ")", "rescue", "GracefulExit", ",", "SystemExit", "=>", "e", "rescue", "=>", "e", "$stderr", ".", "puts", "(", "\"Handler thread unexpectedly died with #{e}:\"", ",", "e", ".", "backtrace", ")", "end", "end", "ensure", "trap", "\"INT\"", ",", "int_orig", "trap", "\"TERM\"", ",", "term_orig", "@listener", ".", "close", "if", "(", "@listener", "&&", "!", "@listener", ".", "closed?", ")", "@interruptable", "=", "@listener", "=", "@master", "=", "@workers", "=", "nil", "end", "end", "end" ]
Runs the application through the configured handler. Can only be run once at a time. If you try to run it more than once, the second run will block until the first finishes.
[ "Runs", "the", "application", "through", "the", "configured", "handler", ".", "Can", "only", "be", "run", "once", "at", "a", "time", ".", "If", "you", "try", "to", "run", "it", "more", "than", "once", "the", "second", "run", "will", "block", "until", "the", "first", "finishes", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L328-L374
train
albertosaurus/us_bank_holidays
lib/us_bank_holidays/month.rb
UsBankHolidays.Month.to_s
def to_s @to_s ||= begin wks = @weeks.map { |w| w.map { |d| if d.nil? ' ' elsif d.day < 10 " #{d.day}" else "#{d.day}" end }.join(' ') }.join("\n") "Su Mo Tu We Th Fr Sa\n#{wks}\n" end end
ruby
def to_s @to_s ||= begin wks = @weeks.map { |w| w.map { |d| if d.nil? ' ' elsif d.day < 10 " #{d.day}" else "#{d.day}" end }.join(' ') }.join("\n") "Su Mo Tu We Th Fr Sa\n#{wks}\n" end end
[ "def", "to_s", "@to_s", "||=", "begin", "wks", "=", "@weeks", ".", "map", "{", "|", "w", "|", "w", ".", "map", "{", "|", "d", "|", "if", "d", ".", "nil?", "' '", "elsif", "d", ".", "day", "<", "10", "\" #{d.day}\"", "else", "\"#{d.day}\"", "end", "}", ".", "join", "(", "' '", ")", "}", ".", "join", "(", "\"\\n\"", ")", "\"Su Mo Tu We Th Fr Sa\\n#{wks}\\n\"", "end", "end" ]
Initializes an instance from a year and a month. Raises an error if the month is not in the allowed range, i.e. it must be between 1 and 12 inclusive.
[ "Initializes", "an", "instance", "from", "a", "year", "and", "a", "month", ".", "Raises", "an", "error", "if", "the", "month", "is", "not", "in", "the", "allowed", "range", "i", ".", "e", ".", "it", "must", "be", "between", "1", "and", "12", "inclusive", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/month.rb#L21-L36
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Create
def Create(*args) # TODO: implement and accept CreateOptions api_objects = args response = execute_request 'Create' do |xml| xml.CreateRequest do xml.Options # TODO: support CreateOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end CreateResponse.new(response) end
ruby
def Create(*args) # TODO: implement and accept CreateOptions api_objects = args response = execute_request 'Create' do |xml| xml.CreateRequest do xml.Options # TODO: support CreateOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end CreateResponse.new(response) end
[ "def", "Create", "(", "*", "args", ")", "api_objects", "=", "args", "response", "=", "execute_request", "'Create'", "do", "|", "xml", "|", "xml", ".", "CreateRequest", "do", "xml", ".", "Options", "api_objects", ".", "each", "do", "|", "api_object", "|", "xml", ".", "Objects", "\"xsi:type\"", "=>", "api_object", ".", "type_name", "do", "api_object", ".", "render!", "(", "xml", ")", "end", "end", "end", "end", "CreateResponse", ".", "new", "(", "response", ")", "end" ]
Constructs a client. Any of the options documented in ExactTargetSDK#config may be overridden using the options parameter. Since ExactTarget's API is stateless, constructing a client object will not make any remote calls. Invokes the Create method. The provided arguments should each be sub-classes of APIObject, and each provided object will be created in order. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a CreateResponse object.
[ "Constructs", "a", "client", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L42-L60
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Retrieve
def Retrieve(object_type_name, filter, *properties) object_type_name = object_type_name.type_name if object_type_name.respond_to?(:type_name) response = execute_request 'Retrieve' do |xml| xml.RetrieveRequestMsg do xml.RetrieveRequest do xml.Options xml.ObjectType object_type_name properties.each do |property| xml.Properties(property) end xml.Filter "xsi:type" => filter.type_name do filter.render!(xml) end end end end RetrieveResponse.new(response) end
ruby
def Retrieve(object_type_name, filter, *properties) object_type_name = object_type_name.type_name if object_type_name.respond_to?(:type_name) response = execute_request 'Retrieve' do |xml| xml.RetrieveRequestMsg do xml.RetrieveRequest do xml.Options xml.ObjectType object_type_name properties.each do |property| xml.Properties(property) end xml.Filter "xsi:type" => filter.type_name do filter.render!(xml) end end end end RetrieveResponse.new(response) end
[ "def", "Retrieve", "(", "object_type_name", ",", "filter", ",", "*", "properties", ")", "object_type_name", "=", "object_type_name", ".", "type_name", "if", "object_type_name", ".", "respond_to?", "(", ":type_name", ")", "response", "=", "execute_request", "'Retrieve'", "do", "|", "xml", "|", "xml", ".", "RetrieveRequestMsg", "do", "xml", ".", "RetrieveRequest", "do", "xml", ".", "Options", "xml", ".", "ObjectType", "object_type_name", "properties", ".", "each", "do", "|", "property", "|", "xml", ".", "Properties", "(", "property", ")", "end", "xml", ".", "Filter", "\"xsi:type\"", "=>", "filter", ".", "type_name", "do", "filter", ".", "render!", "(", "xml", ")", "end", "end", "end", "end", "RetrieveResponse", ".", "new", "(", "response", ")", "end" ]
Invokes the Retrieve method. Note that this implementation abstracts away the useless RetrieveRequest sub-wrapper, and introduces a RequestResponse wrapper to contain the output parameters. Does not currently support requests that have too many results for one batch. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a RetrieveResponse object.
[ "Invokes", "the", "Retrieve", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L78-L99
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Update
def Update(*args) # TODO: implement and accept UpdateOptions api_objects = args response = execute_request 'Update' do |xml| xml.UpdateRequest do xml.Options # TODO: support UpdateOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end UpdateResponse.new(response) end
ruby
def Update(*args) # TODO: implement and accept UpdateOptions api_objects = args response = execute_request 'Update' do |xml| xml.UpdateRequest do xml.Options # TODO: support UpdateOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end UpdateResponse.new(response) end
[ "def", "Update", "(", "*", "args", ")", "api_objects", "=", "args", "response", "=", "execute_request", "'Update'", "do", "|", "xml", "|", "xml", ".", "UpdateRequest", "do", "xml", ".", "Options", "api_objects", ".", "each", "do", "|", "api_object", "|", "xml", ".", "Objects", "\"xsi:type\"", "=>", "api_object", ".", "type_name", "do", "api_object", ".", "render!", "(", "xml", ")", "end", "end", "end", "end", "UpdateResponse", ".", "new", "(", "response", ")", "end" ]
Invokes the Update method. The provided arguments should each be sub-classes of APIObject, and each provided object will be updated in order. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns an UpdateResponse object.
[ "Invokes", "the", "Update", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L113-L131
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Delete
def Delete(*args) # TODO: implement and accept DeleteOptions api_objects = args response = execute_request 'Delete' do |xml| xml.DeleteRequest do xml.Options # TODO: support DeleteOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end DeleteResponse.new(response) end
ruby
def Delete(*args) # TODO: implement and accept DeleteOptions api_objects = args response = execute_request 'Delete' do |xml| xml.DeleteRequest do xml.Options # TODO: support DeleteOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end DeleteResponse.new(response) end
[ "def", "Delete", "(", "*", "args", ")", "api_objects", "=", "args", "response", "=", "execute_request", "'Delete'", "do", "|", "xml", "|", "xml", ".", "DeleteRequest", "do", "xml", ".", "Options", "api_objects", ".", "each", "do", "|", "api_object", "|", "xml", ".", "Objects", "\"xsi:type\"", "=>", "api_object", ".", "type_name", "do", "api_object", ".", "render!", "(", "xml", ")", "end", "end", "end", "end", "DeleteResponse", ".", "new", "(", "response", ")", "end" ]
Invokes the Delete method. The provided arguments should each be sub-classes of APIObject, and each provided object will be updated in order. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a DeleteResponse object.
[ "Invokes", "the", "Delete", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L145-L163
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Perform
def Perform(action, *args) # TODO: implement and accept PerformOptions definitions = args response = execute_request 'Perform' do |xml| xml.PerformRequestMsg do xml.Action action xml.Definitions do definitions.each do |definition| xml.Definition "xsi:type" => definition.type_name do definition.render!(xml) end end end xml.Options # TODO: support PerformOptions end end PerformResponse.new(response) end
ruby
def Perform(action, *args) # TODO: implement and accept PerformOptions definitions = args response = execute_request 'Perform' do |xml| xml.PerformRequestMsg do xml.Action action xml.Definitions do definitions.each do |definition| xml.Definition "xsi:type" => definition.type_name do definition.render!(xml) end end end xml.Options # TODO: support PerformOptions end end PerformResponse.new(response) end
[ "def", "Perform", "(", "action", ",", "*", "args", ")", "definitions", "=", "args", "response", "=", "execute_request", "'Perform'", "do", "|", "xml", "|", "xml", ".", "PerformRequestMsg", "do", "xml", ".", "Action", "action", "xml", ".", "Definitions", "do", "definitions", ".", "each", "do", "|", "definition", "|", "xml", ".", "Definition", "\"xsi:type\"", "=>", "definition", ".", "type_name", "do", "definition", ".", "render!", "(", "xml", ")", "end", "end", "end", "xml", ".", "Options", "end", "end", "PerformResponse", ".", "new", "(", "response", ")", "end" ]
Invokes the Perform method. The provided arguments should each be definitions that are sub-classes of APIObject. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a PerformResponse object.
[ "Invokes", "the", "Perform", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L177-L199
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.initialize_client!
def initialize_client! self.client = ::Savon.client( :endpoint => config[:endpoint], :namespace => config[:namespace], :open_timeout => config[:open_timeout], :read_timeout => config[:read_timeout], :raise_errors => false, :logger => config[:logger], :log => config[:logger] && config[:logger].level == Logger::DEBUG ) end
ruby
def initialize_client! self.client = ::Savon.client( :endpoint => config[:endpoint], :namespace => config[:namespace], :open_timeout => config[:open_timeout], :read_timeout => config[:read_timeout], :raise_errors => false, :logger => config[:logger], :log => config[:logger] && config[:logger].level == Logger::DEBUG ) end
[ "def", "initialize_client!", "self", ".", "client", "=", "::", "Savon", ".", "client", "(", ":endpoint", "=>", "config", "[", ":endpoint", "]", ",", ":namespace", "=>", "config", "[", ":namespace", "]", ",", ":open_timeout", "=>", "config", "[", ":open_timeout", "]", ",", ":read_timeout", "=>", "config", "[", ":read_timeout", "]", ",", ":raise_errors", "=>", "false", ",", ":logger", "=>", "config", "[", ":logger", "]", ",", ":log", "=>", "config", "[", ":logger", "]", "&&", "config", "[", ":logger", "]", ".", "level", "==", "Logger", "::", "DEBUG", ")", "end" ]
Constructs and saves the savon client using provided config.
[ "Constructs", "and", "saves", "the", "savon", "client", "using", "provided", "config", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L210-L220
train
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.execute_request
def execute_request(method) begin response = client.call(method) do |locals| xml = Builder::XmlMarkup.new xml.instruct!(:xml, :encoding => 'UTF-8') result = begin xml.s :Envelope, "xmlns" => config[:namespace], "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:s" => "http://www.w3.org/2003/05/soap-envelope", "xmlns:a" => "http://schemas.xmlsoap.org/ws/2004/08/addressing", "xmlns:o" => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" do xml.s :Header do xml.a :Action, method, "s:mustUnderstand" => "1" xml.a :MessageID, "uuid:#{Guid.new.to_s}" xml.a :ReplyTo do xml.a :Address, "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous" end xml.a :To, config[:endpoint], "s:mustUnderstand" => "1" xml.o :Security, "s:mustUnderstand" => "1" do xml.o :UsernameToken, "o:Id" => "test" do xml.o :Username, config[:username] xml.o :Password, config[:password] end end end xml.s :Body do yield(xml) end end end locals.xml result end if response.http_error? raise HTTPError, response.http_error.to_s end if response.soap_fault? raise SOAPFault, response.soap_fault.to_s end response rescue ::Timeout::Error => e timeout = ::ExactTargetSDK::TimeoutError.new("#{e.message}; open_timeout: #{config[:open_timeout]}; read_timeout: #{config[:read_timeout]}") timeout.set_backtrace(e.backtrace) raise timeout rescue Exception => e raise ::ExactTargetSDK::UnknownError, e end end
ruby
def execute_request(method) begin response = client.call(method) do |locals| xml = Builder::XmlMarkup.new xml.instruct!(:xml, :encoding => 'UTF-8') result = begin xml.s :Envelope, "xmlns" => config[:namespace], "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:s" => "http://www.w3.org/2003/05/soap-envelope", "xmlns:a" => "http://schemas.xmlsoap.org/ws/2004/08/addressing", "xmlns:o" => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" do xml.s :Header do xml.a :Action, method, "s:mustUnderstand" => "1" xml.a :MessageID, "uuid:#{Guid.new.to_s}" xml.a :ReplyTo do xml.a :Address, "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous" end xml.a :To, config[:endpoint], "s:mustUnderstand" => "1" xml.o :Security, "s:mustUnderstand" => "1" do xml.o :UsernameToken, "o:Id" => "test" do xml.o :Username, config[:username] xml.o :Password, config[:password] end end end xml.s :Body do yield(xml) end end end locals.xml result end if response.http_error? raise HTTPError, response.http_error.to_s end if response.soap_fault? raise SOAPFault, response.soap_fault.to_s end response rescue ::Timeout::Error => e timeout = ::ExactTargetSDK::TimeoutError.new("#{e.message}; open_timeout: #{config[:open_timeout]}; read_timeout: #{config[:read_timeout]}") timeout.set_backtrace(e.backtrace) raise timeout rescue Exception => e raise ::ExactTargetSDK::UnknownError, e end end
[ "def", "execute_request", "(", "method", ")", "begin", "response", "=", "client", ".", "call", "(", "method", ")", "do", "|", "locals", "|", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "(", ":xml", ",", ":encoding", "=>", "'UTF-8'", ")", "result", "=", "begin", "xml", ".", "s", ":Envelope", ",", "\"xmlns\"", "=>", "config", "[", ":namespace", "]", ",", "\"xmlns:xsd\"", "=>", "\"http://www.w3.org/2001/XMLSchema\"", ",", "\"xmlns:xsi\"", "=>", "\"http://www.w3.org/2001/XMLSchema-instance\"", ",", "\"xmlns:s\"", "=>", "\"http://www.w3.org/2003/05/soap-envelope\"", ",", "\"xmlns:a\"", "=>", "\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"", ",", "\"xmlns:o\"", "=>", "\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"", "do", "xml", ".", "s", ":Header", "do", "xml", ".", "a", ":Action", ",", "method", ",", "\"s:mustUnderstand\"", "=>", "\"1\"", "xml", ".", "a", ":MessageID", ",", "\"uuid:#{Guid.new.to_s}\"", "xml", ".", "a", ":ReplyTo", "do", "xml", ".", "a", ":Address", ",", "\"http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous\"", "end", "xml", ".", "a", ":To", ",", "config", "[", ":endpoint", "]", ",", "\"s:mustUnderstand\"", "=>", "\"1\"", "xml", ".", "o", ":Security", ",", "\"s:mustUnderstand\"", "=>", "\"1\"", "do", "xml", ".", "o", ":UsernameToken", ",", "\"o:Id\"", "=>", "\"test\"", "do", "xml", ".", "o", ":Username", ",", "config", "[", ":username", "]", "xml", ".", "o", ":Password", ",", "config", "[", ":password", "]", "end", "end", "end", "xml", ".", "s", ":Body", "do", "yield", "(", "xml", ")", "end", "end", "end", "locals", ".", "xml", "result", "end", "if", "response", ".", "http_error?", "raise", "HTTPError", ",", "response", ".", "http_error", ".", "to_s", "end", "if", "response", ".", "soap_fault?", "raise", "SOAPFault", ",", "response", ".", "soap_fault", ".", "to_s", "end", "response", "rescue", "::", "Timeout", "::", "Error", "=>", "e", "timeout", "=", "::", "ExactTargetSDK", "::", "TimeoutError", ".", "new", "(", "\"#{e.message}; open_timeout: #{config[:open_timeout]}; read_timeout: #{config[:read_timeout]}\"", ")", "timeout", ".", "set_backtrace", "(", "e", ".", "backtrace", ")", "raise", "timeout", "rescue", "Exception", "=>", "e", "raise", "::", "ExactTargetSDK", "::", "UnknownError", ",", "e", "end", "end" ]
Builds the SOAP request for the given method, delegating body rendering to the provided block. Handles errors and re-raises with appropriate sub-class of ExactTargetSDK::Error. Returns the raw savon response.
[ "Builds", "the", "SOAP", "request", "for", "the", "given", "method", "delegating", "body", "rendering", "to", "the", "provided", "block", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L229-L284
train
Lupeipei/i18n-processes
lib/i18n/processes/google_translation.rb
I18n::Processes.GoogleTranslation.dump_value
def dump_value(value) case value when Array # dump recursively value.map { |v| dump_value v } when String replace_interpolations value end end
ruby
def dump_value(value) case value when Array # dump recursively value.map { |v| dump_value v } when String replace_interpolations value end end
[ "def", "dump_value", "(", "value", ")", "case", "value", "when", "Array", "value", ".", "map", "{", "|", "v", "|", "dump_value", "v", "}", "when", "String", "replace_interpolations", "value", "end", "end" ]
Prepare value for translation. @return [String, Array<String, nil>, nil] value for Google Translate or nil for non-string values
[ "Prepare", "value", "for", "translation", "." ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/google_translation.rb#L68-L76
train
Lupeipei/i18n-processes
lib/i18n/processes/google_translation.rb
I18n::Processes.GoogleTranslation.parse_value
def parse_value(untranslated, each_translated) case untranslated when Array # implode array untranslated.map { |from| parse_value(from, each_translated) } when String restore_interpolations untranslated, each_translated.next else untranslated end end
ruby
def parse_value(untranslated, each_translated) case untranslated when Array # implode array untranslated.map { |from| parse_value(from, each_translated) } when String restore_interpolations untranslated, each_translated.next else untranslated end end
[ "def", "parse_value", "(", "untranslated", ",", "each_translated", ")", "case", "untranslated", "when", "Array", "untranslated", ".", "map", "{", "|", "from", "|", "parse_value", "(", "from", ",", "each_translated", ")", "}", "when", "String", "restore_interpolations", "untranslated", ",", "each_translated", ".", "next", "else", "untranslated", "end", "end" ]
Parse translated value from the each_translated enumerator @param [Object] untranslated @param [Enumerator] each_translated @return [Object] final translated value
[ "Parse", "translated", "value", "from", "the", "each_translated", "enumerator" ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/google_translation.rb#L82-L92
train
barkerest/barkest_core
lib/barkest_core/extensions/active_record_extensions.rb
BarkestCore.ConnectionAdapterExtensions.object_exists?
def object_exists?(object_name) safe_name = "'#{object_name.gsub('\'','\'\'')}'" klass = self.class.name sql = if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter' # use sysobjects table. "SELECT COUNT(*) AS \"one\" FROM \"sysobjects\" WHERE \"name\"=#{safe_name}" elsif klass == 'ActiveRecord::ConnectionAdapters::SQLite3Adapter' # use sqlite_master table. "SELECT COUNT(*) AS \"one\" FROM \"sqlite_master\" WHERE (\"type\"='table' OR \"type\"='view') AND (\"name\"=#{safe_name})" else # query the information_schema TABLES and ROUTINES views. "SELECT SUM(Z.\"one\") AS \"one\" FROM (SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=#{safe_name} UNION SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME=#{safe_name}) AS Z" end result = exec_query(sql).first result && result['one'] >= 1 end
ruby
def object_exists?(object_name) safe_name = "'#{object_name.gsub('\'','\'\'')}'" klass = self.class.name sql = if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter' # use sysobjects table. "SELECT COUNT(*) AS \"one\" FROM \"sysobjects\" WHERE \"name\"=#{safe_name}" elsif klass == 'ActiveRecord::ConnectionAdapters::SQLite3Adapter' # use sqlite_master table. "SELECT COUNT(*) AS \"one\" FROM \"sqlite_master\" WHERE (\"type\"='table' OR \"type\"='view') AND (\"name\"=#{safe_name})" else # query the information_schema TABLES and ROUTINES views. "SELECT SUM(Z.\"one\") AS \"one\" FROM (SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=#{safe_name} UNION SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME=#{safe_name}) AS Z" end result = exec_query(sql).first result && result['one'] >= 1 end
[ "def", "object_exists?", "(", "object_name", ")", "safe_name", "=", "\"'#{object_name.gsub('\\'','\\'\\'')}'\"", "klass", "=", "self", ".", "class", ".", "name", "sql", "=", "if", "klass", "==", "'ActiveRecord::ConnectionAdapters::SQLServerAdapter'", "\"SELECT COUNT(*) AS \\\"one\\\" FROM \\\"sysobjects\\\" WHERE \\\"name\\\"=#{safe_name}\"", "elsif", "klass", "==", "'ActiveRecord::ConnectionAdapters::SQLite3Adapter'", "\"SELECT COUNT(*) AS \\\"one\\\" FROM \\\"sqlite_master\\\" WHERE (\\\"type\\\"='table' OR \\\"type\\\"='view') AND (\\\"name\\\"=#{safe_name})\"", "else", "\"SELECT SUM(Z.\\\"one\\\") AS \\\"one\\\" FROM (SELECT COUNT(*) AS \\\"one\\\" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=#{safe_name} UNION SELECT COUNT(*) AS \\\"one\\\" FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME=#{safe_name}) AS Z\"", "end", "result", "=", "exec_query", "(", "sql", ")", ".", "first", "result", "&&", "result", "[", "'one'", "]", ">=", "1", "end" ]
Searches the database to determine if an object with the specified name exists.
[ "Searches", "the", "database", "to", "determine", "if", "an", "object", "with", "the", "specified", "name", "exists", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/active_record_extensions.rb#L11-L30
train
barkerest/barkest_core
lib/barkest_core/extensions/active_record_extensions.rb
BarkestCore.ConnectionAdapterExtensions.exec_sp
def exec_sp(stmt) klass = self.class.name if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter' rex = /^exec(?:ute)?\s+[\["]?(?<PROC>[a-z][a-z0-9_]*)[\]"]?(?<ARGS>\s.*)?$/i match = rex.match(stmt) if match exec_query("DECLARE @RET INTEGER; EXECUTE @RET=[#{match['PROC']}]#{match['ARGS']}; SELECT @RET AS [RET]").first['RET'] else execute stmt end else execute stmt end end
ruby
def exec_sp(stmt) klass = self.class.name if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter' rex = /^exec(?:ute)?\s+[\["]?(?<PROC>[a-z][a-z0-9_]*)[\]"]?(?<ARGS>\s.*)?$/i match = rex.match(stmt) if match exec_query("DECLARE @RET INTEGER; EXECUTE @RET=[#{match['PROC']}]#{match['ARGS']}; SELECT @RET AS [RET]").first['RET'] else execute stmt end else execute stmt end end
[ "def", "exec_sp", "(", "stmt", ")", "klass", "=", "self", ".", "class", ".", "name", "if", "klass", "==", "'ActiveRecord::ConnectionAdapters::SQLServerAdapter'", "rex", "=", "/", "\\s", "\\[", "\\]", "\\s", "/i", "match", "=", "rex", ".", "match", "(", "stmt", ")", "if", "match", "exec_query", "(", "\"DECLARE @RET INTEGER; EXECUTE @RET=[#{match['PROC']}]#{match['ARGS']}; SELECT @RET AS [RET]\"", ")", ".", "first", "[", "'RET'", "]", "else", "execute", "stmt", "end", "else", "execute", "stmt", "end", "end" ]
Executes a stored procedure. For MS SQL Server, this will return the return value from the procedure. For other providers, this is the same as +execute+.
[ "Executes", "a", "stored", "procedure", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/active_record_extensions.rb#L37-L50
train
LiveTyping/live-front-rails
lib/live-front/application_helper.rb
LiveFront.ApplicationHelper.current_controller?
def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end
ruby
def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end
[ "def", "current_controller?", "(", "*", "args", ")", "args", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", ".", "downcase", "==", "controller", ".", "controller_name", "}", "end" ]
Check if a particular controller is the current one args - One or more controller names to check Examples # On TreeController current_controller?(:tree) # => true current_controller?(:commits) # => false current_controller?(:commits, :tree) # => true
[ "Check", "if", "a", "particular", "controller", "is", "the", "current", "one" ]
605946ec748bab2a2a751fd7eebcbf9a0e99832c
https://github.com/LiveTyping/live-front-rails/blob/605946ec748bab2a2a751fd7eebcbf9a0e99832c/lib/live-front/application_helper.rb#L13-L15
train
youcune/yo_client
lib/yo_client.rb
YoClient.Client.yo
def yo(username, options = {}) options.merge!(username: username.upcase) response = connection_wrapper { @faraday.post '/yo/', token_hash.merge(options) } response.success? end
ruby
def yo(username, options = {}) options.merge!(username: username.upcase) response = connection_wrapper { @faraday.post '/yo/', token_hash.merge(options) } response.success? end
[ "def", "yo", "(", "username", ",", "options", "=", "{", "}", ")", "options", ".", "merge!", "(", "username", ":", "username", ".", "upcase", ")", "response", "=", "connection_wrapper", "{", "@faraday", ".", "post", "'/yo/'", ",", "token_hash", ".", "merge", "(", "options", ")", "}", "response", ".", "success?", "end" ]
Yo to specific user @param [String] username usename to send yo @param [Hash] options allowed only link for now @return [Boolean] if request has succeed
[ "Yo", "to", "specific", "user" ]
a966c9d2d454315cb77deda1b8487255e48d5673
https://github.com/youcune/yo_client/blob/a966c9d2d454315cb77deda1b8487255e48d5673/lib/yo_client.rb#L32-L38
train
youcune/yo_client
lib/yo_client.rb
YoClient.Client.connection_wrapper
def connection_wrapper(&block) begin response = block.call raise ClientError.new(response.body['error']) if response.body.has_key?('error') rescue Faraday::ParsingError => e # Has gotten a response, but it is not formatted with JSON raise ClientError.new(e.message) rescue Faraday::ClientError => e # Failed to build a connection raise ConnectionError.new(e.message) end response end
ruby
def connection_wrapper(&block) begin response = block.call raise ClientError.new(response.body['error']) if response.body.has_key?('error') rescue Faraday::ParsingError => e # Has gotten a response, but it is not formatted with JSON raise ClientError.new(e.message) rescue Faraday::ClientError => e # Failed to build a connection raise ConnectionError.new(e.message) end response end
[ "def", "connection_wrapper", "(", "&", "block", ")", "begin", "response", "=", "block", ".", "call", "raise", "ClientError", ".", "new", "(", "response", ".", "body", "[", "'error'", "]", ")", "if", "response", ".", "body", ".", "has_key?", "(", "'error'", ")", "rescue", "Faraday", "::", "ParsingError", "=>", "e", "raise", "ClientError", ".", "new", "(", "e", ".", "message", ")", "rescue", "Faraday", "::", "ClientError", "=>", "e", "raise", "ConnectionError", ".", "new", "(", "e", ".", "message", ")", "end", "response", "end" ]
Connect with error handling @param [Proc] block
[ "Connect", "with", "error", "handling" ]
a966c9d2d454315cb77deda1b8487255e48d5673
https://github.com/youcune/yo_client/blob/a966c9d2d454315cb77deda1b8487255e48d5673/lib/yo_client.rb#L52-L65
train
mdub/pith
lib/pith/plugins/publication/project.rb
Pith.Project.published_inputs
def published_inputs inputs.select { |i| i.published? }.sort_by { |i| i.published_at } end
ruby
def published_inputs inputs.select { |i| i.published? }.sort_by { |i| i.published_at } end
[ "def", "published_inputs", "inputs", ".", "select", "{", "|", "i", "|", "i", ".", "published?", "}", ".", "sort_by", "{", "|", "i", "|", "i", ".", "published_at", "}", "end" ]
Return all the published inputs, in order of publication.
[ "Return", "all", "the", "published", "inputs", "in", "order", "of", "publication", "." ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/plugins/publication/project.rb#L10-L12
train
Beetrack/fish_transactions
lib/fish_transactions/callbacks.rb
FishTransactions.Callbacks.after_transaction
def after_transaction(opts = {}, &block) # default options default_options = { only: nil, if_no_transaction: :run} opts = default_options.merge(opts) # normalize opts to string keys normalized = opts.dup opts.each{ |k,v| normalized[k.to_s] = v } opts = normalized if ActiveRecord::Base.connection.open_transactions > 0 callbacks = ActiveRecord::Base.callbacks case opts['only'] when :commit callbacks.store(:commit,&block) when :rollback callbacks.store(:rollback,&block) else # both cases callbacks.store(:commit,&block) callbacks.store(:rollback,&block) end else if opts['if_no_transaction'] == :run block.call end end end
ruby
def after_transaction(opts = {}, &block) # default options default_options = { only: nil, if_no_transaction: :run} opts = default_options.merge(opts) # normalize opts to string keys normalized = opts.dup opts.each{ |k,v| normalized[k.to_s] = v } opts = normalized if ActiveRecord::Base.connection.open_transactions > 0 callbacks = ActiveRecord::Base.callbacks case opts['only'] when :commit callbacks.store(:commit,&block) when :rollback callbacks.store(:rollback,&block) else # both cases callbacks.store(:commit,&block) callbacks.store(:rollback,&block) end else if opts['if_no_transaction'] == :run block.call end end end
[ "def", "after_transaction", "(", "opts", "=", "{", "}", ",", "&", "block", ")", "default_options", "=", "{", "only", ":", "nil", ",", "if_no_transaction", ":", ":run", "}", "opts", "=", "default_options", ".", "merge", "(", "opts", ")", "normalized", "=", "opts", ".", "dup", "opts", ".", "each", "{", "|", "k", ",", "v", "|", "normalized", "[", "k", ".", "to_s", "]", "=", "v", "}", "opts", "=", "normalized", "if", "ActiveRecord", "::", "Base", ".", "connection", ".", "open_transactions", ">", "0", "callbacks", "=", "ActiveRecord", "::", "Base", ".", "callbacks", "case", "opts", "[", "'only'", "]", "when", ":commit", "callbacks", ".", "store", "(", ":commit", ",", "&", "block", ")", "when", ":rollback", "callbacks", ".", "store", "(", ":rollback", ",", "&", "block", ")", "else", "callbacks", ".", "store", "(", ":commit", ",", "&", "block", ")", "callbacks", ".", "store", "(", ":rollback", ",", "&", "block", ")", "end", "else", "if", "opts", "[", "'if_no_transaction'", "]", "==", ":run", "block", ".", "call", "end", "end", "end" ]
Allows to execute any block of code after transaction completes. If no transaction is actually open, the code runs immediately. Accepts the following options that modifies this behavior: * <tt>:only</tt> - Execute this code only on commit or only on rollback. Accepts one of the following symbols: <tt>:commit</tt>, <tt>:rollback</tt>. * <tt>:if_no_transaction</tt> - Specifies what to do if there is no active transaction. Accepts one of the following symbols: <tt>:run</tt> (default), <tt>:skip</tt> (do not run). Example of use: ActiveRecord::Base.transaction do # executes some code puts "runs within transaction" after_transaction do # things to do after transaction puts "runs after transaction" end # executes more code puts "again runs within transaction" end will output runs within transaction again runs within transaction runs after transaction
[ "Allows", "to", "execute", "any", "block", "of", "code", "after", "transaction", "completes", ".", "If", "no", "transaction", "is", "actually", "open", "the", "code", "runs", "immediately", "." ]
ee2bd83d1bd8b81e6b3d437ad7cfb44c7f1b9fb2
https://github.com/Beetrack/fish_transactions/blob/ee2bd83d1bd8b81e6b3d437ad7cfb44c7f1b9fb2/lib/fish_transactions/callbacks.rb#L88-L118
train
riddopic/garcun
lib/garcon/chef/coerce/coercer.rb
Garcon.Coercer.register
def register(origin, target, &block) raise(ArgumentError, 'block is required') unless block_given? @mutex.synchronize do @coercions[origin][target] = Coercion.new(origin, target, &block) end end
ruby
def register(origin, target, &block) raise(ArgumentError, 'block is required') unless block_given? @mutex.synchronize do @coercions[origin][target] = Coercion.new(origin, target, &block) end end
[ "def", "register", "(", "origin", ",", "target", ",", "&", "block", ")", "raise", "(", "ArgumentError", ",", "'block is required'", ")", "unless", "block_given?", "@mutex", ".", "synchronize", "do", "@coercions", "[", "origin", "]", "[", "target", "]", "=", "Coercion", ".", "new", "(", "origin", ",", "target", ",", "&", "block", ")", "end", "end" ]
Registers a coercion with the Garcon library. @param [Class] origin The class to convert. @param [Class] target What the origin will be converted to.
[ "Registers", "a", "coercion", "with", "the", "Garcon", "library", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/coerce/coercer.rb#L50-L56
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.write_to_s3
def write_to_s3 status_path = "#{@s3_path}/status.json" s3.put_object(@bucket, status_path, "#{to_json}\n") unless @status_url expire_date = Time.now + (3600 * 24) # one day from now @status_url = s3.get_object_http_url(@bucket, status_path, expire_date) s3.put_object(@bucket, status_path, "#{to_json}\n") end end
ruby
def write_to_s3 status_path = "#{@s3_path}/status.json" s3.put_object(@bucket, status_path, "#{to_json}\n") unless @status_url expire_date = Time.now + (3600 * 24) # one day from now @status_url = s3.get_object_http_url(@bucket, status_path, expire_date) s3.put_object(@bucket, status_path, "#{to_json}\n") end end
[ "def", "write_to_s3", "status_path", "=", "\"#{@s3_path}/status.json\"", "s3", ".", "put_object", "(", "@bucket", ",", "status_path", ",", "\"#{to_json}\\n\"", ")", "unless", "@status_url", "expire_date", "=", "Time", ".", "now", "+", "(", "3600", "*", "24", ")", "@status_url", "=", "s3", ".", "get_object_http_url", "(", "@bucket", ",", "status_path", ",", "expire_date", ")", "s3", ".", "put_object", "(", "@bucket", ",", "status_path", ",", "\"#{to_json}\\n\"", ")", "end", "end" ]
Writes this job's JSON representation to S3
[ "Writes", "this", "job", "s", "JSON", "representation", "to", "S3" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L50-L58
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.perform_backup
def perform_backup begin prepare_backup update_status "Backing up #{rds_id} from account #{account_name}" create_disconnected_rds download_data_from_tmp_rds # populates @sql_file delete_disconnected_rds upload_output_to_s3 update_status "Backup of #{rds_id} complete" send_mail rescue Exception => e update_status "ERROR: #{e.message.split("\n").first}", 500 raise e end end
ruby
def perform_backup begin prepare_backup update_status "Backing up #{rds_id} from account #{account_name}" create_disconnected_rds download_data_from_tmp_rds # populates @sql_file delete_disconnected_rds upload_output_to_s3 update_status "Backup of #{rds_id} complete" send_mail rescue Exception => e update_status "ERROR: #{e.message.split("\n").first}", 500 raise e end end
[ "def", "perform_backup", "begin", "prepare_backup", "update_status", "\"Backing up #{rds_id} from account #{account_name}\"", "create_disconnected_rds", "download_data_from_tmp_rds", "delete_disconnected_rds", "upload_output_to_s3", "update_status", "\"Backup of #{rds_id} complete\"", "send_mail", "rescue", "Exception", "=>", "e", "update_status", "\"ERROR: #{e.message.split(\"\\n\").first}\"", ",", "500", "raise", "e", "end", "end" ]
Top-level, long-running method for performing the backup.
[ "Top", "-", "level", "long", "-", "running", "method", "for", "performing", "the", "backup", "." ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L74-L88
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.create_disconnected_rds
def create_disconnected_rds(new_rds_name = nil) @new_rds_id = new_rds_name if new_rds_name prepare_backup unless @original_server # in case run as a convenience method snapshot_original_rds create_tmp_rds_from_snapshot configure_tmp_rds wait_for_new_security_group wait_for_new_parameter_group # (reboots as needed) destroy_snapshot end
ruby
def create_disconnected_rds(new_rds_name = nil) @new_rds_id = new_rds_name if new_rds_name prepare_backup unless @original_server # in case run as a convenience method snapshot_original_rds create_tmp_rds_from_snapshot configure_tmp_rds wait_for_new_security_group wait_for_new_parameter_group # (reboots as needed) destroy_snapshot end
[ "def", "create_disconnected_rds", "(", "new_rds_name", "=", "nil", ")", "@new_rds_id", "=", "new_rds_name", "if", "new_rds_name", "prepare_backup", "unless", "@original_server", "snapshot_original_rds", "create_tmp_rds_from_snapshot", "configure_tmp_rds", "wait_for_new_security_group", "wait_for_new_parameter_group", "destroy_snapshot", "end" ]
Step 1 of the overall process - create a disconnected copy of the RDS
[ "Step", "1", "of", "the", "overall", "process", "-", "create", "a", "disconnected", "copy", "of", "the", "RDS" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L91-L100
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.prepare_backup
def prepare_backup unless @original_server = RDSBackup.get_rds(rds_id) names = RDSBackup.rds_accounts.map {|name, account| name } raise "Unable to find RDS #{rds_id} in accounts #{names.join ", "}" end @account_name = @original_server.tracker_account[:name] @rds = ::Fog::AWS::RDS.new( RDSBackup.rds_accounts[@account_name][:credentials]) @snapshot = @rds.snapshots.get @snapshot_id @new_instance = @rds.servers.get @new_rds_id end
ruby
def prepare_backup unless @original_server = RDSBackup.get_rds(rds_id) names = RDSBackup.rds_accounts.map {|name, account| name } raise "Unable to find RDS #{rds_id} in accounts #{names.join ", "}" end @account_name = @original_server.tracker_account[:name] @rds = ::Fog::AWS::RDS.new( RDSBackup.rds_accounts[@account_name][:credentials]) @snapshot = @rds.snapshots.get @snapshot_id @new_instance = @rds.servers.get @new_rds_id end
[ "def", "prepare_backup", "unless", "@original_server", "=", "RDSBackup", ".", "get_rds", "(", "rds_id", ")", "names", "=", "RDSBackup", ".", "rds_accounts", ".", "map", "{", "|", "name", ",", "account", "|", "name", "}", "raise", "\"Unable to find RDS #{rds_id} in accounts #{names.join \", \"}\"", "end", "@account_name", "=", "@original_server", ".", "tracker_account", "[", ":name", "]", "@rds", "=", "::", "Fog", "::", "AWS", "::", "RDS", ".", "new", "(", "RDSBackup", ".", "rds_accounts", "[", "@account_name", "]", "[", ":credentials", "]", ")", "@snapshot", "=", "@rds", ".", "snapshots", ".", "get", "@snapshot_id", "@new_instance", "=", "@rds", ".", "servers", ".", "get", "@new_rds_id", "end" ]
Queries RDS for any pre-existing entities associated with this job. Also waits for the original RDS to become ready.
[ "Queries", "RDS", "for", "any", "pre", "-", "existing", "entities", "associated", "with", "this", "job", ".", "Also", "waits", "for", "the", "original", "RDS", "to", "become", "ready", "." ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L104-L114
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.snapshot_original_rds
def snapshot_original_rds unless @new_instance || @snapshot update_status "Waiting for RDS instance #{@original_server.id}" @original_server.wait_for { ready? } update_status "Creating snapshot #{@snapshot_id} from RDS #{rds_id}" @snapshot = @rds.snapshots.create(id: @snapshot_id, instance_id: rds_id) end end
ruby
def snapshot_original_rds unless @new_instance || @snapshot update_status "Waiting for RDS instance #{@original_server.id}" @original_server.wait_for { ready? } update_status "Creating snapshot #{@snapshot_id} from RDS #{rds_id}" @snapshot = @rds.snapshots.create(id: @snapshot_id, instance_id: rds_id) end end
[ "def", "snapshot_original_rds", "unless", "@new_instance", "||", "@snapshot", "update_status", "\"Waiting for RDS instance #{@original_server.id}\"", "@original_server", ".", "wait_for", "{", "ready?", "}", "update_status", "\"Creating snapshot #{@snapshot_id} from RDS #{rds_id}\"", "@snapshot", "=", "@rds", ".", "snapshots", ".", "create", "(", "id", ":", "@snapshot_id", ",", "instance_id", ":", "rds_id", ")", "end", "end" ]
Snapshots the original RDS
[ "Snapshots", "the", "original", "RDS" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L117-L124
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.create_tmp_rds_from_snapshot
def create_tmp_rds_from_snapshot unless @new_instance update_status "Waiting for snapshot #{@snapshot_id}" @snapshot.wait_for { ready? } update_status "Booting new RDS #{@new_rds_id} from snapshot #{@snapshot.id}" @rds.restore_db_instance_from_db_snapshot(@snapshot.id, @new_rds_id, 'DBInstanceClass' => @original_server.flavor_id) @new_instance = @rds.servers.get @new_rds_id end end
ruby
def create_tmp_rds_from_snapshot unless @new_instance update_status "Waiting for snapshot #{@snapshot_id}" @snapshot.wait_for { ready? } update_status "Booting new RDS #{@new_rds_id} from snapshot #{@snapshot.id}" @rds.restore_db_instance_from_db_snapshot(@snapshot.id, @new_rds_id, 'DBInstanceClass' => @original_server.flavor_id) @new_instance = @rds.servers.get @new_rds_id end end
[ "def", "create_tmp_rds_from_snapshot", "unless", "@new_instance", "update_status", "\"Waiting for snapshot #{@snapshot_id}\"", "@snapshot", ".", "wait_for", "{", "ready?", "}", "update_status", "\"Booting new RDS #{@new_rds_id} from snapshot #{@snapshot.id}\"", "@rds", ".", "restore_db_instance_from_db_snapshot", "(", "@snapshot", ".", "id", ",", "@new_rds_id", ",", "'DBInstanceClass'", "=>", "@original_server", ".", "flavor_id", ")", "@new_instance", "=", "@rds", ".", "servers", ".", "get", "@new_rds_id", "end", "end" ]
Creates a new RDS from the snapshot
[ "Creates", "a", "new", "RDS", "from", "the", "snapshot" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L127-L136
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.configure_tmp_rds
def configure_tmp_rds update_status "Waiting for instance #{@new_instance.id}..." @new_instance.wait_for { ready? } update_status "Modifying RDS attributes for new RDS #{@new_instance.id}" @rds.modify_db_instance(@new_instance.id, true, { 'DBParameterGroupName' => @original_server.db_parameter_groups. first['DBParameterGroupName'], 'DBSecurityGroups' => [ @config['rds_security_group'] ], 'MasterUserPassword' => @new_password, }) end
ruby
def configure_tmp_rds update_status "Waiting for instance #{@new_instance.id}..." @new_instance.wait_for { ready? } update_status "Modifying RDS attributes for new RDS #{@new_instance.id}" @rds.modify_db_instance(@new_instance.id, true, { 'DBParameterGroupName' => @original_server.db_parameter_groups. first['DBParameterGroupName'], 'DBSecurityGroups' => [ @config['rds_security_group'] ], 'MasterUserPassword' => @new_password, }) end
[ "def", "configure_tmp_rds", "update_status", "\"Waiting for instance #{@new_instance.id}...\"", "@new_instance", ".", "wait_for", "{", "ready?", "}", "update_status", "\"Modifying RDS attributes for new RDS #{@new_instance.id}\"", "@rds", ".", "modify_db_instance", "(", "@new_instance", ".", "id", ",", "true", ",", "{", "'DBParameterGroupName'", "=>", "@original_server", ".", "db_parameter_groups", ".", "first", "[", "'DBParameterGroupName'", "]", ",", "'DBSecurityGroups'", "=>", "[", "@config", "[", "'rds_security_group'", "]", "]", ",", "'MasterUserPassword'", "=>", "@new_password", ",", "}", ")", "end" ]
Updates the Master Password and applies the configured RDS Security Group
[ "Updates", "the", "Master", "Password", "and", "applies", "the", "configured", "RDS", "Security", "Group" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L147-L157
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.wait_for_new_security_group
def wait_for_new_security_group old_group_name = @config['rds_security_group'] update_status "Applying security group #{old_group_name}"+ " to #{@new_instance.id}" @new_instance.wait_for { new_group = (db_security_groups.select do |group| group['DBSecurityGroupName'] == old_group_name end).first (new_group ? new_group['Status'] : 'Unknown') == 'active' } end
ruby
def wait_for_new_security_group old_group_name = @config['rds_security_group'] update_status "Applying security group #{old_group_name}"+ " to #{@new_instance.id}" @new_instance.wait_for { new_group = (db_security_groups.select do |group| group['DBSecurityGroupName'] == old_group_name end).first (new_group ? new_group['Status'] : 'Unknown') == 'active' } end
[ "def", "wait_for_new_security_group", "old_group_name", "=", "@config", "[", "'rds_security_group'", "]", "update_status", "\"Applying security group #{old_group_name}\"", "+", "\" to #{@new_instance.id}\"", "@new_instance", ".", "wait_for", "{", "new_group", "=", "(", "db_security_groups", ".", "select", "do", "|", "group", "|", "group", "[", "'DBSecurityGroupName'", "]", "==", "old_group_name", "end", ")", ".", "first", "(", "new_group", "?", "new_group", "[", "'Status'", "]", ":", "'Unknown'", ")", "==", "'active'", "}", "end" ]
Wait for the new RDS Security Group to become 'active'
[ "Wait", "for", "the", "new", "RDS", "Security", "Group", "to", "become", "active" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L160-L170
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.wait_for_new_parameter_group
def wait_for_new_parameter_group old_name = @original_server.db_parameter_groups.first['DBParameterGroupName'] update_status "Applying parameter group #{old_name} to #{@new_instance.id}" job = self # save local var for closure in wait_for, below @new_instance.wait_for { new_group = (db_parameter_groups.select do |group| group['DBParameterGroupName'] == old_name end).first status = (new_group ? new_group['ParameterApplyStatus'] : 'Unknown') if (status == "pending-reboot") job.update_status "Rebooting RDS #{id} to apply ParameterGroup #{old_name}" reboot and wait_for { ready? } end status == 'in-sync' && ready? } end
ruby
def wait_for_new_parameter_group old_name = @original_server.db_parameter_groups.first['DBParameterGroupName'] update_status "Applying parameter group #{old_name} to #{@new_instance.id}" job = self # save local var for closure in wait_for, below @new_instance.wait_for { new_group = (db_parameter_groups.select do |group| group['DBParameterGroupName'] == old_name end).first status = (new_group ? new_group['ParameterApplyStatus'] : 'Unknown') if (status == "pending-reboot") job.update_status "Rebooting RDS #{id} to apply ParameterGroup #{old_name}" reboot and wait_for { ready? } end status == 'in-sync' && ready? } end
[ "def", "wait_for_new_parameter_group", "old_name", "=", "@original_server", ".", "db_parameter_groups", ".", "first", "[", "'DBParameterGroupName'", "]", "update_status", "\"Applying parameter group #{old_name} to #{@new_instance.id}\"", "job", "=", "self", "@new_instance", ".", "wait_for", "{", "new_group", "=", "(", "db_parameter_groups", ".", "select", "do", "|", "group", "|", "group", "[", "'DBParameterGroupName'", "]", "==", "old_name", "end", ")", ".", "first", "status", "=", "(", "new_group", "?", "new_group", "[", "'ParameterApplyStatus'", "]", ":", "'Unknown'", ")", "if", "(", "status", "==", "\"pending-reboot\"", ")", "job", ".", "update_status", "\"Rebooting RDS #{id} to apply ParameterGroup #{old_name}\"", "reboot", "and", "wait_for", "{", "ready?", "}", "end", "status", "==", "'in-sync'", "&&", "ready?", "}", "end" ]
Wait for the new RDS Parameter Group to become 'in-sync'
[ "Wait", "for", "the", "new", "RDS", "Parameter", "Group", "to", "become", "in", "-", "sync" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L173-L188
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.update_status
def update_status(message, new_status = nil) @log = @options[:logger] || RDSBackup.default_logger(STDOUT) @message = message @status = new_status if new_status @status == 200 ? (@log.info message) : (@log.error message) write_to_s3 end
ruby
def update_status(message, new_status = nil) @log = @options[:logger] || RDSBackup.default_logger(STDOUT) @message = message @status = new_status if new_status @status == 200 ? (@log.info message) : (@log.error message) write_to_s3 end
[ "def", "update_status", "(", "message", ",", "new_status", "=", "nil", ")", "@log", "=", "@options", "[", ":logger", "]", "||", "RDSBackup", ".", "default_logger", "(", "STDOUT", ")", "@message", "=", "message", "@status", "=", "new_status", "if", "new_status", "@status", "==", "200", "?", "(", "@log", ".", "info", "message", ")", ":", "(", "@log", ".", "error", "message", ")", "write_to_s3", "end" ]
Writes a new status message to the log, and writes the job info to S3
[ "Writes", "a", "new", "status", "message", "to", "the", "log", "and", "writes", "the", "job", "info", "to", "S3" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L229-L235
train
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.send_mail
def send_mail return unless @options[:email] @log.info "Emailing #{@options[:email]}..." begin RDSBackup::Email.new(self).send! @log.info "Email sent to #{@options[:email]} for job #{backup_id}" rescue Exception => e @log.warn "Error sending email: #{e.message.split("\n").first}" end end
ruby
def send_mail return unless @options[:email] @log.info "Emailing #{@options[:email]}..." begin RDSBackup::Email.new(self).send! @log.info "Email sent to #{@options[:email]} for job #{backup_id}" rescue Exception => e @log.warn "Error sending email: #{e.message.split("\n").first}" end end
[ "def", "send_mail", "return", "unless", "@options", "[", ":email", "]", "@log", ".", "info", "\"Emailing #{@options[:email]}...\"", "begin", "RDSBackup", "::", "Email", ".", "new", "(", "self", ")", ".", "send!", "@log", ".", "info", "\"Email sent to #{@options[:email]} for job #{backup_id}\"", "rescue", "Exception", "=>", "e", "@log", ".", "warn", "\"Error sending email: #{e.message.split(\"\\n\").first}\"", "end", "end" ]
Sends a status email
[ "Sends", "a", "status", "email" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L238-L247
train
chef-workflow/chef-workflow-testlib
lib/chef-workflow/helpers/chef.rb
ChefWorkflow.ChefHelper.perform_search
def perform_search(type, query) Chef::Search::Query.new.search(type, query).first.map(&:name) end
ruby
def perform_search(type, query) Chef::Search::Query.new.search(type, query).first.map(&:name) end
[ "def", "perform_search", "(", "type", ",", "query", ")", "Chef", "::", "Search", "::", "Query", ".", "new", ".", "search", "(", "type", ",", "query", ")", ".", "first", ".", "map", "(", "&", ":name", ")", "end" ]
Perform a search and return the names of the nodes that match the search.
[ "Perform", "a", "search", "and", "return", "the", "names", "of", "the", "nodes", "that", "match", "the", "search", "." ]
39e9dee4e75d3165cad866babb643df0c519414a
https://github.com/chef-workflow/chef-workflow-testlib/blob/39e9dee4e75d3165cad866babb643df0c519414a/lib/chef-workflow/helpers/chef.rb#L13-L15
train
notCalle/ruby-keytree
lib/key_tree/tree.rb
KeyTree.Tree.keys
def keys @hash.deep.each_with_object([]) do |(key_path, value), result| result << key_path.to_key_path unless value.is_a?(Hash) end end
ruby
def keys @hash.deep.each_with_object([]) do |(key_path, value), result| result << key_path.to_key_path unless value.is_a?(Hash) end end
[ "def", "keys", "@hash", ".", "deep", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "(", "key_path", ",", "value", ")", ",", "result", "|", "result", "<<", "key_path", ".", "to_key_path", "unless", "value", ".", "is_a?", "(", "Hash", ")", "end", "end" ]
Return all maximal key paths in a tree :call-seq: keys => Array of KeyTree::Path
[ "Return", "all", "maximal", "key", "paths", "in", "a", "tree" ]
1a88c902c8b5d14f21fd350338776fc094eae8e3
https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/tree.rb#L97-L101
train
progressions/ymdt
lib/ymdt.rb
YMDT.Base.invoke
def invoke(command, params={}) command_string = compile_command(command, params) output_command(command_string) execute(command_string, params) end
ruby
def invoke(command, params={}) command_string = compile_command(command, params) output_command(command_string) execute(command_string, params) end
[ "def", "invoke", "(", "command", ",", "params", "=", "{", "}", ")", "command_string", "=", "compile_command", "(", "command", ",", "params", ")", "output_command", "(", "command_string", ")", "execute", "(", "command_string", ",", "params", ")", "end" ]
prepares the commands to correctly reference the application and path
[ "prepares", "the", "commands", "to", "correctly", "reference", "the", "application", "and", "path" ]
9345bc07380176ac94e300ce9c4f9f9f20ffbcd0
https://github.com/progressions/ymdt/blob/9345bc07380176ac94e300ce9c4f9f9f20ffbcd0/lib/ymdt.rb#L74-L78
train
progressions/ymdt
lib/ymdt.rb
YMDT.Base.output_command
def output_command(command_string) $stdout.puts $stdout.puts StringMasker.new(command_string, :username => username, :password => password).to_s end
ruby
def output_command(command_string) $stdout.puts $stdout.puts StringMasker.new(command_string, :username => username, :password => password).to_s end
[ "def", "output_command", "(", "command_string", ")", "$stdout", ".", "puts", "$stdout", ".", "puts", "StringMasker", ".", "new", "(", "command_string", ",", ":username", "=>", "username", ",", ":password", "=>", "password", ")", ".", "to_s", "end" ]
print the command on the screen
[ "print", "the", "command", "on", "the", "screen" ]
9345bc07380176ac94e300ce9c4f9f9f20ffbcd0
https://github.com/progressions/ymdt/blob/9345bc07380176ac94e300ce9c4f9f9f20ffbcd0/lib/ymdt.rb#L84-L87
train
progressions/ymdt
lib/ymdt.rb
YMDT.Base.execute
def execute(command, params={}) unless params[:dry_run] if params[:return] System.execute(command, :return => true) else $stdout.puts System.execute(command) end end end
ruby
def execute(command, params={}) unless params[:dry_run] if params[:return] System.execute(command, :return => true) else $stdout.puts System.execute(command) end end end
[ "def", "execute", "(", "command", ",", "params", "=", "{", "}", ")", "unless", "params", "[", ":dry_run", "]", "if", "params", "[", ":return", "]", "System", ".", "execute", "(", "command", ",", ":return", "=>", "true", ")", "else", "$stdout", ".", "puts", "System", ".", "execute", "(", "command", ")", "end", "end", "end" ]
execute the command, or not, and return the results, or not
[ "execute", "the", "command", "or", "not", "and", "return", "the", "results", "or", "not" ]
9345bc07380176ac94e300ce9c4f9f9f20ffbcd0
https://github.com/progressions/ymdt/blob/9345bc07380176ac94e300ce9c4f9f9f20ffbcd0/lib/ymdt.rb#L138-L147
train
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.doc
def doc @document = Nokogiri::HTML(@body) rescue Exception => e puts e.inspect puts e.backtrace end
ruby
def doc @document = Nokogiri::HTML(@body) rescue Exception => e puts e.inspect puts e.backtrace end
[ "def", "doc", "@document", "=", "Nokogiri", "::", "HTML", "(", "@body", ")", "rescue", "Exception", "=>", "e", "puts", "e", ".", "inspect", "puts", "e", ".", "backtrace", "end" ]
Return the Nokogiri html document
[ "Return", "the", "Nokogiri", "html", "document" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L51-L56
train
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.links
def links @links = doc.css('a').map { |link| link['href'].to_s }.uniq.delete_if { |href| href.empty? }.map { |url| absolutify(url.strip) } end
ruby
def links @links = doc.css('a').map { |link| link['href'].to_s }.uniq.delete_if { |href| href.empty? }.map { |url| absolutify(url.strip) } end
[ "def", "links", "@links", "=", "doc", ".", "css", "(", "'a'", ")", ".", "map", "{", "|", "link", "|", "link", "[", "'href'", "]", ".", "to_s", "}", ".", "uniq", ".", "delete_if", "{", "|", "href", "|", "href", ".", "empty?", "}", ".", "map", "{", "|", "url", "|", "absolutify", "(", "url", ".", "strip", ")", "}", "end" ]
Return the entire links found in the page; exclude empty links
[ "Return", "the", "entire", "links", "found", "in", "the", "page", ";", "exclude", "empty", "links" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L75-L77
train
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.images
def images @images = doc.css('img').map { |img| img['src'].to_s }.uniq.delete_if { |src| src.empty? }.map { |url| absolutify(url.strip) } end
ruby
def images @images = doc.css('img').map { |img| img['src'].to_s }.uniq.delete_if { |src| src.empty? }.map { |url| absolutify(url.strip) } end
[ "def", "images", "@images", "=", "doc", ".", "css", "(", "'img'", ")", ".", "map", "{", "|", "img", "|", "img", "[", "'src'", "]", ".", "to_s", "}", ".", "uniq", ".", "delete_if", "{", "|", "src", "|", "src", ".", "empty?", "}", ".", "map", "{", "|", "url", "|", "absolutify", "(", "url", ".", "strip", ")", "}", "end" ]
Return all images found in the page
[ "Return", "all", "images", "found", "in", "the", "page" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L103-L105
train
belsonheng/spidercrawl
lib/spidercrawl/page.rb
Spidercrawl.Page.text
def text temp_doc = doc temp_doc.css('script, noscript, style, link').each { |node| node.remove } @text = temp_doc.css('body').text.split("\n").collect { |line| line.strip }.join("\n") end
ruby
def text temp_doc = doc temp_doc.css('script, noscript, style, link').each { |node| node.remove } @text = temp_doc.css('body').text.split("\n").collect { |line| line.strip }.join("\n") end
[ "def", "text", "temp_doc", "=", "doc", "temp_doc", ".", "css", "(", "'script, noscript, style, link'", ")", ".", "each", "{", "|", "node", "|", "node", ".", "remove", "}", "@text", "=", "temp_doc", ".", "css", "(", "'body'", ")", ".", "text", ".", "split", "(", "\"\\n\"", ")", ".", "collect", "{", "|", "line", "|", "line", ".", "strip", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Return plain text of the page without html tags
[ "Return", "plain", "text", "of", "the", "page", "without", "html", "tags" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/page.rb#L144-L148
train
bluevialabs/connfu-client
lib/connfu/dispatcher.rb
Connfu.Dispatcher.set_channels!
def set_channels!(message) # :doc: channel_type = message.channel_type # select channels with the same channel_type as the incoming message channels = @app_channels.select { |channel| channel["channel_type"].eql?(channel_type) } # filter channels case message.channel_type when "twitter" # filter by from or to account channels = channels.select { |channel| channel["accounts"].select { |item| item["name"].eql?(message.from) or item["name"].eql?(message.to) }.length > 0 } when "voice" # filter by did channels = channels.select { |channel| channel["uid"].eql?(message.channel_name) #channel["phones"].select{|item| # item["phone_number"].eql?(message.to) #}.length > 0 } when "sms" channels = channels.select { |channel| channel["phones"].select{|item| item["phone_number"].eql?(message.to) }.length > 0 } when "rss" channels = channels.select { |channel| channel["uri"].eql?(message.channel_name) } else logger.warn("This code should not be executed because the first select should avoid this") logger.info("Unexpected message: #{message.channel_type}") channels = [] end # get only the channel unique identifier channels = channels.map { |channel| channel["uid"] } logger.debug "Setting channels in the incoming message to #{channels}" message.channel_name = channels end
ruby
def set_channels!(message) # :doc: channel_type = message.channel_type # select channels with the same channel_type as the incoming message channels = @app_channels.select { |channel| channel["channel_type"].eql?(channel_type) } # filter channels case message.channel_type when "twitter" # filter by from or to account channels = channels.select { |channel| channel["accounts"].select { |item| item["name"].eql?(message.from) or item["name"].eql?(message.to) }.length > 0 } when "voice" # filter by did channels = channels.select { |channel| channel["uid"].eql?(message.channel_name) #channel["phones"].select{|item| # item["phone_number"].eql?(message.to) #}.length > 0 } when "sms" channels = channels.select { |channel| channel["phones"].select{|item| item["phone_number"].eql?(message.to) }.length > 0 } when "rss" channels = channels.select { |channel| channel["uri"].eql?(message.channel_name) } else logger.warn("This code should not be executed because the first select should avoid this") logger.info("Unexpected message: #{message.channel_type}") channels = [] end # get only the channel unique identifier channels = channels.map { |channel| channel["uid"] } logger.debug "Setting channels in the incoming message to #{channels}" message.channel_name = channels end
[ "def", "set_channels!", "(", "message", ")", "channel_type", "=", "message", ".", "channel_type", "channels", "=", "@app_channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"channel_type\"", "]", ".", "eql?", "(", "channel_type", ")", "}", "case", "message", ".", "channel_type", "when", "\"twitter\"", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"accounts\"", "]", ".", "select", "{", "|", "item", "|", "item", "[", "\"name\"", "]", ".", "eql?", "(", "message", ".", "from", ")", "or", "item", "[", "\"name\"", "]", ".", "eql?", "(", "message", ".", "to", ")", "}", ".", "length", ">", "0", "}", "when", "\"voice\"", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"uid\"", "]", ".", "eql?", "(", "message", ".", "channel_name", ")", "}", "when", "\"sms\"", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"phones\"", "]", ".", "select", "{", "|", "item", "|", "item", "[", "\"phone_number\"", "]", ".", "eql?", "(", "message", ".", "to", ")", "}", ".", "length", ">", "0", "}", "when", "\"rss\"", "channels", "=", "channels", ".", "select", "{", "|", "channel", "|", "channel", "[", "\"uri\"", "]", ".", "eql?", "(", "message", ".", "channel_name", ")", "}", "else", "logger", ".", "warn", "(", "\"This code should not be executed because the first select should avoid this\"", ")", "logger", ".", "info", "(", "\"Unexpected message: #{message.channel_type}\"", ")", "channels", "=", "[", "]", "end", "channels", "=", "channels", ".", "map", "{", "|", "channel", "|", "channel", "[", "\"uid\"", "]", "}", "logger", ".", "debug", "\"Setting channels in the incoming message to #{channels}\"", "message", ".", "channel_name", "=", "channels", "end" ]
Sets the message channel_name attribute. The result is a list of application channels that should be advised about the inbound message * if message["type"].eql?("twitter"): message["channel_type"] is an array of all the application twitter channels that has associated the message twitter account. i.e. Application channels: @app_channels = [ {"uid"=>"twitter-channel-1", "type"=>"twitter", "accounts"=>[{"name"=>"juandebravo"}, {"name"=>"connfudev"}]}, {"uid"=>"twitter-channel-2", "type"=>"twitter", "accounts"=>[{"name"=>"telefonicaid"}]}] Incoming message: message.channel_type = "twitter" message.from = "juandebravo" set_channels!(message) => message.channel_name = ["twitter-channel-1"] ==== Parameters * +message+ Connfu::Message with no channel_name info ==== Return * Connfu::Message with the channel_name filled with the relevant app channels
[ "Sets", "the", "message", "channel_name", "attribute", ".", "The", "result", "is", "a", "list", "of", "application", "channels", "that", "should", "be", "advised", "about", "the", "inbound", "message" ]
b62a0f5176afa203ba1eecccc7994d6bc61af3a7
https://github.com/bluevialabs/connfu-client/blob/b62a0f5176afa203ba1eecccc7994d6bc61af3a7/lib/connfu/dispatcher.rb#L115-L157
train
bluevialabs/connfu-client
lib/connfu/dispatcher.rb
Connfu.Dispatcher.process_message
def process_message(message) logger.info("Calling event #{message.message_type} in the channel #{message.channel_type}") @listener_channels[message.channel_type.to_sym].message(message.message_type.to_sym, message) end
ruby
def process_message(message) logger.info("Calling event #{message.message_type} in the channel #{message.channel_type}") @listener_channels[message.channel_type.to_sym].message(message.message_type.to_sym, message) end
[ "def", "process_message", "(", "message", ")", "logger", ".", "info", "(", "\"Calling event #{message.message_type} in the channel #{message.channel_type}\"", ")", "@listener_channels", "[", "message", ".", "channel_type", ".", "to_sym", "]", ".", "message", "(", "message", ".", "message_type", ".", "to_sym", ",", "message", ")", "end" ]
Executes the blocks that are associated to that channel and event type @param *message* incoming message to be processed
[ "Executes", "the", "blocks", "that", "are", "associated", "to", "that", "channel", "and", "event", "type" ]
b62a0f5176afa203ba1eecccc7994d6bc61af3a7
https://github.com/bluevialabs/connfu-client/blob/b62a0f5176afa203ba1eecccc7994d6bc61af3a7/lib/connfu/dispatcher.rb#L161-L164
train
feduxorg/the_array_comparator
lib/the_array_comparator/comparator.rb
TheArrayComparator.Comparator.add_check
def add_check(data, type, keywords, options = {}) t = type.to_sym fail Exceptions::UnknownCheckType, "Unknown check type \":#{t}\" given. Did you register it in advance?" unless comparators.key?(t) opts = { exceptions: [], tag: '' }.merge options sample = Sample.new(data, keywords, opts[:exceptions], opts[:tag]) strategy_klass = comparators[t] check = Check.new(strategy_klass, sample) @cache[:checks].add check end
ruby
def add_check(data, type, keywords, options = {}) t = type.to_sym fail Exceptions::UnknownCheckType, "Unknown check type \":#{t}\" given. Did you register it in advance?" unless comparators.key?(t) opts = { exceptions: [], tag: '' }.merge options sample = Sample.new(data, keywords, opts[:exceptions], opts[:tag]) strategy_klass = comparators[t] check = Check.new(strategy_klass, sample) @cache[:checks].add check end
[ "def", "add_check", "(", "data", ",", "type", ",", "keywords", ",", "options", "=", "{", "}", ")", "t", "=", "type", ".", "to_sym", "fail", "Exceptions", "::", "UnknownCheckType", ",", "\"Unknown check type \\\":#{t}\\\" given. Did you register it in advance?\"", "unless", "comparators", ".", "key?", "(", "t", ")", "opts", "=", "{", "exceptions", ":", "[", "]", ",", "tag", ":", "''", "}", ".", "merge", "options", "sample", "=", "Sample", ".", "new", "(", "data", ",", "keywords", ",", "opts", "[", ":exceptions", "]", ",", "opts", "[", ":tag", "]", ")", "strategy_klass", "=", "comparators", "[", "t", "]", "check", "=", "Check", ".", "new", "(", "strategy_klass", ",", "sample", ")", "@cache", "[", ":checks", "]", ".", "add", "check", "end" ]
Add a check to test against @param [Array] data the data which should be used as check, will be passed to the concrete comparator strategy @param [Symbol] type the comparator strategy (needs to be registered first) @param [Array] keywords what to look for in the data, will be passed to the concrete comparator strategy @param [Hash] options exception, should not be considered as match @option options [Hash] exceptions the exceptions from keywords @option options [String] tag a tag to identify the check @raise [Exceptions::UnknownCheckType] if a unknown strategy is given (needs to be registered first)
[ "Add", "a", "check", "to", "test", "against" ]
66cdaf953909a34366cbee2b519dfcf306bc03c7
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/comparator.rb#L69-L83
train
feduxorg/the_array_comparator
lib/the_array_comparator/comparator.rb
TheArrayComparator.Comparator.result
def result if @cache[:checks].new_objects? @cache[:checks].stored_objects.each do |c| @result = Result.new(c.sample) unless c.success? end end @result end
ruby
def result if @cache[:checks].new_objects? @cache[:checks].stored_objects.each do |c| @result = Result.new(c.sample) unless c.success? end end @result end
[ "def", "result", "if", "@cache", "[", ":checks", "]", ".", "new_objects?", "@cache", "[", ":checks", "]", ".", "stored_objects", ".", "each", "do", "|", "c", "|", "@result", "=", "Result", ".", "new", "(", "c", ".", "sample", ")", "unless", "c", ".", "success?", "end", "end", "@result", "end" ]
The result of all checks defined @return [Result] the result class with all the data need for further analysis
[ "The", "result", "of", "all", "checks", "defined" ]
66cdaf953909a34366cbee2b519dfcf306bc03c7
https://github.com/feduxorg/the_array_comparator/blob/66cdaf953909a34366cbee2b519dfcf306bc03c7/lib/the_array_comparator/comparator.rb#L89-L97
train
jinx/migrate
examples/family/lib/shims.rb
Family.Parent.migrate
def migrate(row, migrated) super if spouse then spouse.household = migrated.detect { |m| Household === m } end end
ruby
def migrate(row, migrated) super if spouse then spouse.household = migrated.detect { |m| Household === m } end end
[ "def", "migrate", "(", "row", ",", "migrated", ")", "super", "if", "spouse", "then", "spouse", ".", "household", "=", "migrated", ".", "detect", "{", "|", "m", "|", "Household", "===", "m", "}", "end", "end" ]
Augments the migration by setting the spouse household. @param [{Symbol => Object}] row the input row field => value hash @param [<Resource>] migrated the migrated instances
[ "Augments", "the", "migration", "by", "setting", "the", "spouse", "household", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/examples/family/lib/shims.rb#L10-L15
train
jns/Aims
lib/aims/output.rb
Aims.Timings.add!
def add!(timings) timings.descriptions.each{|d| add_cpu_time(d, timings.cpu_time(d)) add_wall_time(d, timings.wall_time(d)) } end
ruby
def add!(timings) timings.descriptions.each{|d| add_cpu_time(d, timings.cpu_time(d)) add_wall_time(d, timings.wall_time(d)) } end
[ "def", "add!", "(", "timings", ")", "timings", ".", "descriptions", ".", "each", "{", "|", "d", "|", "add_cpu_time", "(", "d", ",", "timings", ".", "cpu_time", "(", "d", ")", ")", "add_wall_time", "(", "d", ",", "timings", ".", "wall_time", "(", "d", ")", ")", "}", "end" ]
Add another timings object to this one
[ "Add", "another", "timings", "object", "to", "this", "one" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/output.rb#L98-L103
train
jns/Aims
lib/aims/output.rb
Aims.AimsOutput.total_energy
def total_energy etot = self.geometry_steps.collect{|gs| gs.total_energy }.compact.last if etot.nil? Float::NAN else etot end end
ruby
def total_energy etot = self.geometry_steps.collect{|gs| gs.total_energy }.compact.last if etot.nil? Float::NAN else etot end end
[ "def", "total_energy", "etot", "=", "self", ".", "geometry_steps", ".", "collect", "{", "|", "gs", "|", "gs", ".", "total_energy", "}", ".", "compact", ".", "last", "if", "etot", ".", "nil?", "Float", "::", "NAN", "else", "etot", "end", "end" ]
Returns the best available value of the total energy
[ "Returns", "the", "best", "available", "value", "of", "the", "total", "energy" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/output.rb#L240-L247
train
itisnotdone/gogetit
lib/executionhooks.rb
Gogetit.ExecutionHooks.method_added
def method_added(method_name) # do nothing if the method that was added was an actual hook method, or # if it already had hooks added to it return if hooks.include?(method_name) || hooked_methods.include?(method_name) add_hooks_to(method_name) end
ruby
def method_added(method_name) # do nothing if the method that was added was an actual hook method, or # if it already had hooks added to it return if hooks.include?(method_name) || hooked_methods.include?(method_name) add_hooks_to(method_name) end
[ "def", "method_added", "(", "method_name", ")", "return", "if", "hooks", ".", "include?", "(", "method_name", ")", "||", "hooked_methods", ".", "include?", "(", "method_name", ")", "add_hooks_to", "(", "method_name", ")", "end" ]
this method is invoked whenever a new instance method is added to a class
[ "this", "method", "is", "invoked", "whenever", "a", "new", "instance", "method", "is", "added", "to", "a", "class" ]
62628c04c0310567178c4738aa5b64645ed5c4bd
https://github.com/itisnotdone/gogetit/blob/62628c04c0310567178c4738aa5b64645ed5c4bd/lib/executionhooks.rb#L5-L10
train
burlesona/nform
lib/nform/core_ext.rb
NForm.Hashable.hash_of
def hash_of(*keys) keys.each.with_object({}){|k,h| h[k] = send(k) } end
ruby
def hash_of(*keys) keys.each.with_object({}){|k,h| h[k] = send(k) } end
[ "def", "hash_of", "(", "*", "keys", ")", "keys", ".", "each", ".", "with_object", "(", "{", "}", ")", "{", "|", "k", ",", "h", "|", "h", "[", "k", "]", "=", "send", "(", "k", ")", "}", "end" ]
A convenience method for making a hash with the given methods on self as the keys and return for the given methods as the values
[ "A", "convenience", "method", "for", "making", "a", "hash", "with", "the", "given", "methods", "on", "self", "as", "the", "keys", "and", "return", "for", "the", "given", "methods", "as", "the", "values" ]
3ba467b55e9fbb480856d069c1792c2ad41da921
https://github.com/burlesona/nform/blob/3ba467b55e9fbb480856d069c1792c2ad41da921/lib/nform/core_ext.rb#L8-L10
train
blambeau/yargi
lib/yargi/element_set.rb
Yargi.ElementSet.set_mark
def set_mark(key, value, dup=true) self.each {|elm| elm.set_mark(key, (dup and not(Symbol===value)) ? value.dup : value)} end
ruby
def set_mark(key, value, dup=true) self.each {|elm| elm.set_mark(key, (dup and not(Symbol===value)) ? value.dup : value)} end
[ "def", "set_mark", "(", "key", ",", "value", ",", "dup", "=", "true", ")", "self", ".", "each", "{", "|", "elm", "|", "elm", ".", "set_mark", "(", "key", ",", "(", "dup", "and", "not", "(", "Symbol", "===", "value", ")", ")", "?", "value", ".", "dup", ":", "value", ")", "}", "end" ]
Fired to each element of the group. Values are duplicated by default. Put dup to false to avoid this behavior.
[ "Fired", "to", "each", "element", "of", "the", "group", ".", "Values", "are", "duplicated", "by", "default", ".", "Put", "dup", "to", "false", "to", "avoid", "this", "behavior", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/element_set.rb#L125-L127
train
openplaces/bigindex
lib/big_index/model.rb
BigIndex.Model.rebuild_index
def rebuild_index(options={}, finder_options={}) logger.info "=== Rebuilding index for: #{self.index_type}" unless options[:silent] if options[:drop] logger.info "Dropping index for: #{self.index_type}" unless options[:silent] index_adapter.drop_index(self) end finder_options[:batch_size] ||= 100 finder_options[:view] ||= :all finder_options[:bypass_index] = true options[:batch_size] ||= 100 options[:commit] = true unless options.has_key?(:commit) options[:optimize] = true unless options.has_key?(:optimize) logger.info "Offset: #{finder_options[:offset]}" unless options[:silent] logger.info "Stop row: #{finder_options[:stop_row]}" unless options[:silent] buffer = [] items_processed = 0 loop = 0 # Depending on whether the model has a scan or find method, use that. # scan is from Bigrecord models, and find is from Activerecord. if self.respond_to?(:scan) self.scan(finder_options) do |r| items_processed += 1 buffer << r if buffer.size > options[:batch_size] loop += 1 index_adapter.process_index_batch(buffer, loop, options) buffer.clear end end index_adapter.process_index_batch(buffer, loop, options) unless buffer.empty? elsif self.respond_to?(:find) ar_options = {:limit => finder_options[:batch_size]} while loop += 1 buffer = self.find_without_index(:all, ar_options) break if buffer.empty? items_processed += buffer.size index_adapter.process_index_batch(buffer, loop, options) break if buffer.size < finder_options[:batch_size] buffer.clear ar_options[:offset] = (loop * finder_options[:batch_size])+1 end else raise "Your model needs at least a scan() or find() method" end if items_processed > 0 logger.info "Index for #{self.index_type} has been rebuilt (#{items_processed} records)." unless options[:silent] else logger.info "Nothing to index for #{self.index_type}." unless options[:silent] end logger.info "=== Finished rebuilding index for: #{self.index_type}" unless options[:silent] return items_processed end
ruby
def rebuild_index(options={}, finder_options={}) logger.info "=== Rebuilding index for: #{self.index_type}" unless options[:silent] if options[:drop] logger.info "Dropping index for: #{self.index_type}" unless options[:silent] index_adapter.drop_index(self) end finder_options[:batch_size] ||= 100 finder_options[:view] ||= :all finder_options[:bypass_index] = true options[:batch_size] ||= 100 options[:commit] = true unless options.has_key?(:commit) options[:optimize] = true unless options.has_key?(:optimize) logger.info "Offset: #{finder_options[:offset]}" unless options[:silent] logger.info "Stop row: #{finder_options[:stop_row]}" unless options[:silent] buffer = [] items_processed = 0 loop = 0 # Depending on whether the model has a scan or find method, use that. # scan is from Bigrecord models, and find is from Activerecord. if self.respond_to?(:scan) self.scan(finder_options) do |r| items_processed += 1 buffer << r if buffer.size > options[:batch_size] loop += 1 index_adapter.process_index_batch(buffer, loop, options) buffer.clear end end index_adapter.process_index_batch(buffer, loop, options) unless buffer.empty? elsif self.respond_to?(:find) ar_options = {:limit => finder_options[:batch_size]} while loop += 1 buffer = self.find_without_index(:all, ar_options) break if buffer.empty? items_processed += buffer.size index_adapter.process_index_batch(buffer, loop, options) break if buffer.size < finder_options[:batch_size] buffer.clear ar_options[:offset] = (loop * finder_options[:batch_size])+1 end else raise "Your model needs at least a scan() or find() method" end if items_processed > 0 logger.info "Index for #{self.index_type} has been rebuilt (#{items_processed} records)." unless options[:silent] else logger.info "Nothing to index for #{self.index_type}." unless options[:silent] end logger.info "=== Finished rebuilding index for: #{self.index_type}" unless options[:silent] return items_processed end
[ "def", "rebuild_index", "(", "options", "=", "{", "}", ",", "finder_options", "=", "{", "}", ")", "logger", ".", "info", "\"=== Rebuilding index for: #{self.index_type}\"", "unless", "options", "[", ":silent", "]", "if", "options", "[", ":drop", "]", "logger", ".", "info", "\"Dropping index for: #{self.index_type}\"", "unless", "options", "[", ":silent", "]", "index_adapter", ".", "drop_index", "(", "self", ")", "end", "finder_options", "[", ":batch_size", "]", "||=", "100", "finder_options", "[", ":view", "]", "||=", ":all", "finder_options", "[", ":bypass_index", "]", "=", "true", "options", "[", ":batch_size", "]", "||=", "100", "options", "[", ":commit", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":commit", ")", "options", "[", ":optimize", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":optimize", ")", "logger", ".", "info", "\"Offset: #{finder_options[:offset]}\"", "unless", "options", "[", ":silent", "]", "logger", ".", "info", "\"Stop row: #{finder_options[:stop_row]}\"", "unless", "options", "[", ":silent", "]", "buffer", "=", "[", "]", "items_processed", "=", "0", "loop", "=", "0", "if", "self", ".", "respond_to?", "(", ":scan", ")", "self", ".", "scan", "(", "finder_options", ")", "do", "|", "r", "|", "items_processed", "+=", "1", "buffer", "<<", "r", "if", "buffer", ".", "size", ">", "options", "[", ":batch_size", "]", "loop", "+=", "1", "index_adapter", ".", "process_index_batch", "(", "buffer", ",", "loop", ",", "options", ")", "buffer", ".", "clear", "end", "end", "index_adapter", ".", "process_index_batch", "(", "buffer", ",", "loop", ",", "options", ")", "unless", "buffer", ".", "empty?", "elsif", "self", ".", "respond_to?", "(", ":find", ")", "ar_options", "=", "{", ":limit", "=>", "finder_options", "[", ":batch_size", "]", "}", "while", "loop", "+=", "1", "buffer", "=", "self", ".", "find_without_index", "(", ":all", ",", "ar_options", ")", "break", "if", "buffer", ".", "empty?", "items_processed", "+=", "buffer", ".", "size", "index_adapter", ".", "process_index_batch", "(", "buffer", ",", "loop", ",", "options", ")", "break", "if", "buffer", ".", "size", "<", "finder_options", "[", ":batch_size", "]", "buffer", ".", "clear", "ar_options", "[", ":offset", "]", "=", "(", "loop", "*", "finder_options", "[", ":batch_size", "]", ")", "+", "1", "end", "else", "raise", "\"Your model needs at least a scan() or find() method\"", "end", "if", "items_processed", ">", "0", "logger", ".", "info", "\"Index for #{self.index_type} has been rebuilt (#{items_processed} records).\"", "unless", "options", "[", ":silent", "]", "else", "logger", ".", "info", "\"Nothing to index for #{self.index_type}.\"", "unless", "options", "[", ":silent", "]", "end", "logger", ".", "info", "\"=== Finished rebuilding index for: #{self.index_type}\"", "unless", "options", "[", ":silent", "]", "return", "items_processed", "end" ]
Dispatches a command to the current adapter to rebuild the index. @return <Integer> representing number of items processed.
[ "Dispatches", "a", "command", "to", "the", "current", "adapter", "to", "rebuild", "the", "index", "." ]
c2612327b31dfd3271dfcde17389f0852459f565
https://github.com/openplaces/bigindex/blob/c2612327b31dfd3271dfcde17389f0852459f565/lib/big_index/model.rb#L102-L169
train
openplaces/bigindex
lib/big_index/model.rb
BigIndex.Model.index
def index(*params, &block) index_field = IndexField.new(params, block) add_index_field(index_field) # Create the attribute finder method define_finder index_field[:finder_name] end
ruby
def index(*params, &block) index_field = IndexField.new(params, block) add_index_field(index_field) # Create the attribute finder method define_finder index_field[:finder_name] end
[ "def", "index", "(", "*", "params", ",", "&", "block", ")", "index_field", "=", "IndexField", ".", "new", "(", "params", ",", "block", ")", "add_index_field", "(", "index_field", ")", "define_finder", "index_field", "[", ":finder_name", "]", "end" ]
Macro for defining a class attribute as an indexed field. Also creates the corresponding attribute finder method, which defaults to the field name. This can be defined with the :finder_name => "anothername" option. Refer to {IndexField} for more information on defining fields.
[ "Macro", "for", "defining", "a", "class", "attribute", "as", "an", "indexed", "field", "." ]
c2612327b31dfd3271dfcde17389f0852459f565
https://github.com/openplaces/bigindex/blob/c2612327b31dfd3271dfcde17389f0852459f565/lib/big_index/model.rb#L227-L234
train
DigitPaint/html_mockup
lib/html_mockup/server.rb
HtmlMockup.Server.application
def application return @app if @app @stack.use Rack::HtmlValidator if self.options[:validate] @stack.run Rack::HtmlMockup.new(self.project) @app = @stack end
ruby
def application return @app if @app @stack.use Rack::HtmlValidator if self.options[:validate] @stack.run Rack::HtmlMockup.new(self.project) @app = @stack end
[ "def", "application", "return", "@app", "if", "@app", "@stack", ".", "use", "Rack", "::", "HtmlValidator", "if", "self", ".", "options", "[", ":validate", "]", "@stack", ".", "run", "Rack", "::", "HtmlMockup", ".", "new", "(", "self", ".", "project", ")", "@app", "=", "@stack", "end" ]
Build the final application that get's run by the Rack Handler
[ "Build", "the", "final", "application", "that", "get", "s", "run", "by", "the", "Rack", "Handler" ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/server.rb#L73-L80
train
briandamaged/unobservable
lib/unobservable.rb
Unobservable.ModuleSupport.define_event
def define_event(name, args = {}) args = {:create_method => true}.merge(args) name = name.to_sym if args[:create_method] define_method name do return event(name) end end @unobservable_instance_events ||= Set.new if @unobservable_instance_events.include? name return false else @unobservable_instance_events.add name return true end end
ruby
def define_event(name, args = {}) args = {:create_method => true}.merge(args) name = name.to_sym if args[:create_method] define_method name do return event(name) end end @unobservable_instance_events ||= Set.new if @unobservable_instance_events.include? name return false else @unobservable_instance_events.add name return true end end
[ "def", "define_event", "(", "name", ",", "args", "=", "{", "}", ")", "args", "=", "{", ":create_method", "=>", "true", "}", ".", "merge", "(", "args", ")", "name", "=", "name", ".", "to_sym", "if", "args", "[", ":create_method", "]", "define_method", "name", "do", "return", "event", "(", "name", ")", "end", "end", "@unobservable_instance_events", "||=", "Set", ".", "new", "if", "@unobservable_instance_events", ".", "include?", "name", "return", "false", "else", "@unobservable_instance_events", ".", "add", "name", "return", "true", "end", "end" ]
Returns true if the instance event is defined. Returns false otherwise.
[ "Returns", "true", "if", "the", "instance", "event", "is", "defined", ".", "Returns", "false", "otherwise", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L84-L101
train
briandamaged/unobservable
lib/unobservable.rb
Unobservable.ModuleSupport.attr_event
def attr_event(*names) args = (names[-1].is_a? Hash) ? names.pop : {} names.each {|n| define_event(n, args) } return nil end
ruby
def attr_event(*names) args = (names[-1].is_a? Hash) ? names.pop : {} names.each {|n| define_event(n, args) } return nil end
[ "def", "attr_event", "(", "*", "names", ")", "args", "=", "(", "names", "[", "-", "1", "]", ".", "is_a?", "Hash", ")", "?", "names", ".", "pop", ":", "{", "}", "names", ".", "each", "{", "|", "n", "|", "define_event", "(", "n", ",", "args", ")", "}", "return", "nil", "end" ]
This helper method is similar to attr_reader and attr_accessor. It allows for instance events to be declared inside the body of the class.
[ "This", "helper", "method", "is", "similar", "to", "attr_reader", "and", "attr_accessor", ".", "It", "allows", "for", "instance", "events", "to", "be", "declared", "inside", "the", "body", "of", "the", "class", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L106-L110
train
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Support.singleton_events
def singleton_events(all = true) if all contributors = self.singleton_class.included_modules contributors -= self.class.included_modules contributors.push self.singleton_class Unobservable.collect_instance_events_defined_by(contributors) else Unobservable.collect_instance_events_defined_by([self.singleton_class]) end end
ruby
def singleton_events(all = true) if all contributors = self.singleton_class.included_modules contributors -= self.class.included_modules contributors.push self.singleton_class Unobservable.collect_instance_events_defined_by(contributors) else Unobservable.collect_instance_events_defined_by([self.singleton_class]) end end
[ "def", "singleton_events", "(", "all", "=", "true", ")", "if", "all", "contributors", "=", "self", ".", "singleton_class", ".", "included_modules", "contributors", "-=", "self", ".", "class", ".", "included_modules", "contributors", ".", "push", "self", ".", "singleton_class", "Unobservable", ".", "collect_instance_events_defined_by", "(", "contributors", ")", "else", "Unobservable", ".", "collect_instance_events_defined_by", "(", "[", "self", ".", "singleton_class", "]", ")", "end", "end" ]
Obtains the list of events that are unique to this object. If all = true, then this list will also include events that were defined within a module that the object extended.
[ "Obtains", "the", "list", "of", "events", "that", "are", "unique", "to", "this", "object", ".", "If", "all", "=", "true", "then", "this", "list", "will", "also", "include", "events", "that", "were", "defined", "within", "a", "module", "that", "the", "object", "extended", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L135-L144
train
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Support.event
def event(name) @unobservable_events_map ||= {} e = @unobservable_events_map[name] if not e if self.events.include? name e = Event.new @unobservable_events_map[name] = e else raise NameError, "Undefined event: #{name}" end end return e end
ruby
def event(name) @unobservable_events_map ||= {} e = @unobservable_events_map[name] if not e if self.events.include? name e = Event.new @unobservable_events_map[name] = e else raise NameError, "Undefined event: #{name}" end end return e end
[ "def", "event", "(", "name", ")", "@unobservable_events_map", "||=", "{", "}", "e", "=", "@unobservable_events_map", "[", "name", "]", "if", "not", "e", "if", "self", ".", "events", ".", "include?", "name", "e", "=", "Event", ".", "new", "@unobservable_events_map", "[", "name", "]", "=", "e", "else", "raise", "NameError", ",", "\"Undefined event: #{name}\"", "end", "end", "return", "e", "end" ]
Returns the Event that has the specified name. A NameError will be raised if the object does not define any event that has the given name.
[ "Returns", "the", "Event", "that", "has", "the", "specified", "name", ".", "A", "NameError", "will", "be", "raised", "if", "the", "object", "does", "not", "define", "any", "event", "that", "has", "the", "given", "name", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L161-L173
train
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Event.register
def register(*args, &block) h = Unobservable.handler_for(*args, &block) @handlers << h return h end
ruby
def register(*args, &block) h = Unobservable.handler_for(*args, &block) @handlers << h return h end
[ "def", "register", "(", "*", "args", ",", "&", "block", ")", "h", "=", "Unobservable", ".", "handler_for", "(", "*", "args", ",", "&", "block", ")", "@handlers", "<<", "h", "return", "h", "end" ]
Registers the given event handler so that it will be invoked when the event is raised.
[ "Registers", "the", "given", "event", "handler", "so", "that", "it", "will", "be", "invoked", "when", "the", "event", "is", "raised", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L209-L213
train
briandamaged/unobservable
lib/unobservable.rb
Unobservable.Event.unregister
def unregister(*args, &block) h = Unobservable.handler_for(*args, &block) index = @handlers.index(h) if index @handlers.slice!(index) return h else return nil end end
ruby
def unregister(*args, &block) h = Unobservable.handler_for(*args, &block) index = @handlers.index(h) if index @handlers.slice!(index) return h else return nil end end
[ "def", "unregister", "(", "*", "args", ",", "&", "block", ")", "h", "=", "Unobservable", ".", "handler_for", "(", "*", "args", ",", "&", "block", ")", "index", "=", "@handlers", ".", "index", "(", "h", ")", "if", "index", "@handlers", ".", "slice!", "(", "index", ")", "return", "h", "else", "return", "nil", "end", "end" ]
Removes a single instance of the specified event handler from the list of event handlers. Therefore, if you've registered the same event handler 3 times, then you will need to unregister it 3 times as well.
[ "Removes", "a", "single", "instance", "of", "the", "specified", "event", "handler", "from", "the", "list", "of", "event", "handlers", ".", "Therefore", "if", "you", "ve", "registered", "the", "same", "event", "handler", "3", "times", "then", "you", "will", "need", "to", "unregister", "it", "3", "times", "as", "well", "." ]
787b02d08019b269c472cb7f2c63526774762796
https://github.com/briandamaged/unobservable/blob/787b02d08019b269c472cb7f2c63526774762796/lib/unobservable.rb#L222-L231
train
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.is_month_archive?
def is_month_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[2].blank? && segments[3].blank?) ? true : false end
ruby
def is_month_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[2].blank? && segments[3].blank?) ? true : false end
[ "def", "is_month_archive?", "segments", "=", "params", "[", ":slug", "]", ".", "split", "(", "'/'", ")", "(", "get_type_by_url", "==", "'AR'", "&&", "!", "segments", "[", "2", "]", ".", "blank?", "&&", "segments", "[", "3", "]", ".", "blank?", ")", "?", "true", ":", "false", "end" ]
returns a boolean as to whether the current view is a month archive
[ "returns", "a", "boolean", "as", "to", "whether", "the", "current", "view", "is", "a", "month", "archive" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L653-L656
train
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.is_year_archive?
def is_year_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[1].blank? && segments[2].blank? && segments[3].blank?) ? true : false end
ruby
def is_year_archive? segments = params[:slug].split('/') (get_type_by_url == 'AR' && !segments[1].blank? && segments[2].blank? && segments[3].blank?) ? true : false end
[ "def", "is_year_archive?", "segments", "=", "params", "[", ":slug", "]", ".", "split", "(", "'/'", ")", "(", "get_type_by_url", "==", "'AR'", "&&", "!", "segments", "[", "1", "]", ".", "blank?", "&&", "segments", "[", "2", "]", ".", "blank?", "&&", "segments", "[", "3", "]", ".", "blank?", ")", "?", "true", ":", "false", "end" ]
returns a boolean as to whether the current view is a year archive
[ "returns", "a", "boolean", "as", "to", "whether", "the", "current", "view", "is", "a", "year", "archive" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L660-L663
train
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.is_homepage?
def is_homepage? return false if (!defined?(@content.length).blank? || @content.blank?) @content.id == Setting.get('home_page').to_i ? true : false end
ruby
def is_homepage? return false if (!defined?(@content.length).blank? || @content.blank?) @content.id == Setting.get('home_page').to_i ? true : false end
[ "def", "is_homepage?", "return", "false", "if", "(", "!", "defined?", "(", "@content", ".", "length", ")", ".", "blank?", "||", "@content", ".", "blank?", ")", "@content", ".", "id", "==", "Setting", ".", "get", "(", "'home_page'", ")", ".", "to_i", "?", "true", ":", "false", "end" ]
returns a boolean as to whether the current view is the homepage
[ "returns", "a", "boolean", "as", "to", "whether", "the", "current", "view", "is", "the", "homepage" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L680-L683
train
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.obtain_comments_form
def obtain_comments_form if Setting.get('article_comments') == 'Y' type = Setting.get('article_comment_type') @new_comment = Comment.new if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/comments_form." + get_theme_ext) render(:template => "themes/#{current_theme}/comments_form." + get_theme_ext , :layout => nil, :locals => { type: type }).to_s else render :inline => 'comments_form.html.erb does not exist in current theme' end end end
ruby
def obtain_comments_form if Setting.get('article_comments') == 'Y' type = Setting.get('article_comment_type') @new_comment = Comment.new if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/comments_form." + get_theme_ext) render(:template => "themes/#{current_theme}/comments_form." + get_theme_ext , :layout => nil, :locals => { type: type }).to_s else render :inline => 'comments_form.html.erb does not exist in current theme' end end end
[ "def", "obtain_comments_form", "if", "Setting", ".", "get", "(", "'article_comments'", ")", "==", "'Y'", "type", "=", "Setting", ".", "get", "(", "'article_comment_type'", ")", "@new_comment", "=", "Comment", ".", "new", "if", "File", ".", "exists?", "(", "\"#{Rails.root}/app/views/themes/#{current_theme}/comments_form.\"", "+", "get_theme_ext", ")", "render", "(", ":template", "=>", "\"themes/#{current_theme}/comments_form.\"", "+", "get_theme_ext", ",", ":layout", "=>", "nil", ",", ":locals", "=>", "{", "type", ":", "type", "}", ")", ".", "to_s", "else", "render", ":inline", "=>", "'comments_form.html.erb does not exist in current theme'", "end", "end", "end" ]
returns the comment form that is created in the theme folder.
[ "returns", "the", "comment", "form", "that", "is", "created", "in", "the", "theme", "folder", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L837-L849
train
mrsimonfletcher/roroacms
app/helpers/roroacms/view_helper.rb
Roroacms.ViewHelper.obtain_term_type
def obtain_term_type return nil if params[:slug].blank? segments = params[:slug].split('/') if !segments[1].blank? term = TermAnatomy.where(:taxonomy => segments[1]).last term.taxonomy if !term.blank? else nil end end
ruby
def obtain_term_type return nil if params[:slug].blank? segments = params[:slug].split('/') if !segments[1].blank? term = TermAnatomy.where(:taxonomy => segments[1]).last term.taxonomy if !term.blank? else nil end end
[ "def", "obtain_term_type", "return", "nil", "if", "params", "[", ":slug", "]", ".", "blank?", "segments", "=", "params", "[", ":slug", "]", ".", "split", "(", "'/'", ")", "if", "!", "segments", "[", "1", "]", ".", "blank?", "term", "=", "TermAnatomy", ".", "where", "(", ":taxonomy", "=>", "segments", "[", "1", "]", ")", ".", "last", "term", ".", "taxonomy", "if", "!", "term", ".", "blank?", "else", "nil", "end", "end" ]
return what type of taxonomy it is either - category or tag
[ "return", "what", "type", "of", "taxonomy", "it", "is", "either", "-", "category", "or", "tag" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/view_helper.rb#L918-L929
train
fugroup/pushfile
lib/pushfile/data.rb
Pushfile.Data.mimetype
def mimetype(path) extension = File.basename(path).split('.')[-1] Rack::Mime.mime_type(".#{extension}") end
ruby
def mimetype(path) extension = File.basename(path).split('.')[-1] Rack::Mime.mime_type(".#{extension}") end
[ "def", "mimetype", "(", "path", ")", "extension", "=", "File", ".", "basename", "(", "path", ")", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "Rack", "::", "Mime", ".", "mime_type", "(", "\".#{extension}\"", ")", "end" ]
Get the mime type from a file name
[ "Get", "the", "mime", "type", "from", "a", "file", "name" ]
dd06bd6b023514a1446544986b1ce85b7bae3f78
https://github.com/fugroup/pushfile/blob/dd06bd6b023514a1446544986b1ce85b7bae3f78/lib/pushfile/data.rb#L74-L77
train
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.process
def process document return unless document.valid # If we're debugging, output the canonical_url emitter.log(document.url.canonical_url.colorize(:green)) # Attach the emitter to the document document.emitter = emitter # enqueue any other pages being linked to enqueue(document.links) # rewrite all absolute links, asset urls, etc # to use local, relative paths # document.rewrite # Write the document to file document.write! # Mark this document's canonical_url as processed processed_urls << document.url.canonical_url end
ruby
def process document return unless document.valid # If we're debugging, output the canonical_url emitter.log(document.url.canonical_url.colorize(:green)) # Attach the emitter to the document document.emitter = emitter # enqueue any other pages being linked to enqueue(document.links) # rewrite all absolute links, asset urls, etc # to use local, relative paths # document.rewrite # Write the document to file document.write! # Mark this document's canonical_url as processed processed_urls << document.url.canonical_url end
[ "def", "process", "document", "return", "unless", "document", ".", "valid", "emitter", ".", "log", "(", "document", ".", "url", ".", "canonical_url", ".", "colorize", "(", ":green", ")", ")", "document", ".", "emitter", "=", "emitter", "enqueue", "(", "document", ".", "links", ")", "document", ".", "write!", "processed_urls", "<<", "document", ".", "url", ".", "canonical_url", "end" ]
Process a document, fetching its content and enqueueing it for sub processing
[ "Process", "a", "document", "fetching", "its", "content", "and", "enqueueing", "it", "for", "sub", "processing" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L40-L58
train
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.enqueue
def enqueue links # Loop over each document links.each_with_index do |document, index| next unless can_be_enqueued?(document) emitter.log("> Enqueueing: #{document.url.canonical_url}") unprocessed_documents << document unprocessed_urls << document.url.canonical_url end end
ruby
def enqueue links # Loop over each document links.each_with_index do |document, index| next unless can_be_enqueued?(document) emitter.log("> Enqueueing: #{document.url.canonical_url}") unprocessed_documents << document unprocessed_urls << document.url.canonical_url end end
[ "def", "enqueue", "links", "links", ".", "each_with_index", "do", "|", "document", ",", "index", "|", "next", "unless", "can_be_enqueued?", "(", "document", ")", "emitter", ".", "log", "(", "\"> Enqueueing: #{document.url.canonical_url}\"", ")", "unprocessed_documents", "<<", "document", "unprocessed_urls", "<<", "document", ".", "url", ".", "canonical_url", "end", "end" ]
Enqueue new documents for each link found in the current document
[ "Enqueue", "new", "documents", "for", "each", "link", "found", "in", "the", "current", "document" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L62-L72
train
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.can_be_enqueued?
def can_be_enqueued?(document) archivable?(document) && # ensure the next document is on an allowable domain valid_domains.include?(document.url.host) && # ensure the next document hasn't been processed yet !processed_urls.include?(document.url.canonical_url) && # ensure the next document hasn't been enqueued yet !unprocessed_urls.include?(document.url.canonical_url) end
ruby
def can_be_enqueued?(document) archivable?(document) && # ensure the next document is on an allowable domain valid_domains.include?(document.url.host) && # ensure the next document hasn't been processed yet !processed_urls.include?(document.url.canonical_url) && # ensure the next document hasn't been enqueued yet !unprocessed_urls.include?(document.url.canonical_url) end
[ "def", "can_be_enqueued?", "(", "document", ")", "archivable?", "(", "document", ")", "&&", "valid_domains", ".", "include?", "(", "document", ".", "url", ".", "host", ")", "&&", "!", "processed_urls", ".", "include?", "(", "document", ".", "url", ".", "canonical_url", ")", "&&", "!", "unprocessed_urls", ".", "include?", "(", "document", ".", "url", ".", "canonical_url", ")", "end" ]
Determine if a document can be enqueued
[ "Determine", "if", "a", "document", "can", "be", "enqueued" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L75-L83
train
cbetta/snapshotify
lib/snapshotify/scraper.rb
Snapshotify.Scraper.archivable?
def archivable?(document) # check if the document is likely to be a html page archivable_document = document.url.valid # check of the document hasn't already been evaluated and discarded has_been_marked_as_invalid = self.invalid_urls.include?(document.url.raw_url) # Add the dpcument to the list of needed if !archivable_document && !has_been_marked_as_invalid emitter.warning("> Invalid URL: #{document.url.raw_url}") invalid_urls << document.url.raw_url end archivable_document end
ruby
def archivable?(document) # check if the document is likely to be a html page archivable_document = document.url.valid # check of the document hasn't already been evaluated and discarded has_been_marked_as_invalid = self.invalid_urls.include?(document.url.raw_url) # Add the dpcument to the list of needed if !archivable_document && !has_been_marked_as_invalid emitter.warning("> Invalid URL: #{document.url.raw_url}") invalid_urls << document.url.raw_url end archivable_document end
[ "def", "archivable?", "(", "document", ")", "archivable_document", "=", "document", ".", "url", ".", "valid", "has_been_marked_as_invalid", "=", "self", ".", "invalid_urls", ".", "include?", "(", "document", ".", "url", ".", "raw_url", ")", "if", "!", "archivable_document", "&&", "!", "has_been_marked_as_invalid", "emitter", ".", "warning", "(", "\"> Invalid URL: #{document.url.raw_url}\"", ")", "invalid_urls", "<<", "document", ".", "url", ".", "raw_url", "end", "archivable_document", "end" ]
Determine if a document is actually the type of document that can be archived
[ "Determine", "if", "a", "document", "is", "actually", "the", "type", "of", "document", "that", "can", "be", "archived" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/scraper.rb#L87-L100
train
arvicco/amqp-spec
lib/amqp-spec/evented_example.rb
AMQP.SpecHelper.done
def done(delay=nil) super(delay) do yield if block_given? EM.next_tick do run_em_hooks :amqp_after if AMQP.conn and not AMQP.closing AMQP.stop_connection do AMQP.cleanup_state finish_em_loop end else AMQP.cleanup_state finish_em_loop end end end end
ruby
def done(delay=nil) super(delay) do yield if block_given? EM.next_tick do run_em_hooks :amqp_after if AMQP.conn and not AMQP.closing AMQP.stop_connection do AMQP.cleanup_state finish_em_loop end else AMQP.cleanup_state finish_em_loop end end end end
[ "def", "done", "(", "delay", "=", "nil", ")", "super", "(", "delay", ")", "do", "yield", "if", "block_given?", "EM", ".", "next_tick", "do", "run_em_hooks", ":amqp_after", "if", "AMQP", ".", "conn", "and", "not", "AMQP", ".", "closing", "AMQP", ".", "stop_connection", "do", "AMQP", ".", "cleanup_state", "finish_em_loop", "end", "else", "AMQP", ".", "cleanup_state", "finish_em_loop", "end", "end", "end", "end" ]
Breaks the event loop and finishes the spec. It yields to any given block first, then stops AMQP, EM event loop and cleans up AMQP state.
[ "Breaks", "the", "event", "loop", "and", "finishes", "the", "spec", ".", "It", "yields", "to", "any", "given", "block", "first", "then", "stops", "AMQP", "EM", "event", "loop", "and", "cleans", "up", "AMQP", "state", "." ]
db0bd8670259b81f085ed6e28b62ad0b76df752f
https://github.com/arvicco/amqp-spec/blob/db0bd8670259b81f085ed6e28b62ad0b76df752f/lib/amqp-spec/evented_example.rb#L135-L151
train
barkerest/barkest_core
app/models/barkest_core/user_manager.rb
BarkestCore.UserManager.primary_source
def primary_source return :ldap if using_ldap? && !using_db? return :db if using_db? && !using_ldap? source = @options[:primary_source] source = source.to_sym if source.is_a?(String) return source if [:ldap, :db].include?(source) return :ldap if using_ldap? :db end
ruby
def primary_source return :ldap if using_ldap? && !using_db? return :db if using_db? && !using_ldap? source = @options[:primary_source] source = source.to_sym if source.is_a?(String) return source if [:ldap, :db].include?(source) return :ldap if using_ldap? :db end
[ "def", "primary_source", "return", ":ldap", "if", "using_ldap?", "&&", "!", "using_db?", "return", ":db", "if", "using_db?", "&&", "!", "using_ldap?", "source", "=", "@options", "[", ":primary_source", "]", "source", "=", "source", ".", "to_sym", "if", "source", ".", "is_a?", "(", "String", ")", "return", "source", "if", "[", ":ldap", ",", ":db", "]", ".", "include?", "(", "source", ")", "return", ":ldap", "if", "using_ldap?", ":db", "end" ]
Gets the first authentication source for this user manager.
[ "Gets", "the", "first", "authentication", "source", "for", "this", "user", "manager", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/user_manager.rb#L47-L59
train
barkerest/barkest_core
app/models/barkest_core/user_manager.rb
BarkestCore.UserManager.authenticate
def authenticate(email, password, client_ip) return nil unless email && BarkestCore::EmailTester.valid_email?(email, false) email = email.downcase sources.each do |source| if source == :ldap entry = @ldap.search(filter: "(&(objectClass=user)(mail=#{email}))") if entry && entry.count == 1 # we found a match. user = User.find_by(email: email, ldap: true) # make sure it authenticates correctly. entry = @ldap.bind_as(filter: "(&(objectClass=user)(mail=#{email}))", password: password) # do not allow authenticating against the DB now. unless entry && entry.count == 1 add_failure_to user || email, '(LDAP) failed to authenticate', client_ip return nil end # load the user and return. user = load_ldap_user(entry.first, true, client_ip) unless user.enabled? add_failure_to user, '(LDAP) account disabled', client_ip return nil end add_success_to user, '(LDAP)', client_ip return user end else user = User.find_by(email: email) if user # user must be enabled, cannot be LDAP, and the password must match. if user.ldap? add_failure_to user, '(DB) cannot authenticate LDAP user', client_ip return nil end unless user.enabled? add_failure_to user, '(DB) account disabled', client_ip return nil end if user.authenticate(password) add_success_to user, '(DB)', client_ip return user else add_failure_to user, '(DB) invalid password', client_ip return nil end end end end add_failure_to email, 'invalid email', client_ip nil end
ruby
def authenticate(email, password, client_ip) return nil unless email && BarkestCore::EmailTester.valid_email?(email, false) email = email.downcase sources.each do |source| if source == :ldap entry = @ldap.search(filter: "(&(objectClass=user)(mail=#{email}))") if entry && entry.count == 1 # we found a match. user = User.find_by(email: email, ldap: true) # make sure it authenticates correctly. entry = @ldap.bind_as(filter: "(&(objectClass=user)(mail=#{email}))", password: password) # do not allow authenticating against the DB now. unless entry && entry.count == 1 add_failure_to user || email, '(LDAP) failed to authenticate', client_ip return nil end # load the user and return. user = load_ldap_user(entry.first, true, client_ip) unless user.enabled? add_failure_to user, '(LDAP) account disabled', client_ip return nil end add_success_to user, '(LDAP)', client_ip return user end else user = User.find_by(email: email) if user # user must be enabled, cannot be LDAP, and the password must match. if user.ldap? add_failure_to user, '(DB) cannot authenticate LDAP user', client_ip return nil end unless user.enabled? add_failure_to user, '(DB) account disabled', client_ip return nil end if user.authenticate(password) add_success_to user, '(DB)', client_ip return user else add_failure_to user, '(DB) invalid password', client_ip return nil end end end end add_failure_to email, 'invalid email', client_ip nil end
[ "def", "authenticate", "(", "email", ",", "password", ",", "client_ip", ")", "return", "nil", "unless", "email", "&&", "BarkestCore", "::", "EmailTester", ".", "valid_email?", "(", "email", ",", "false", ")", "email", "=", "email", ".", "downcase", "sources", ".", "each", "do", "|", "source", "|", "if", "source", "==", ":ldap", "entry", "=", "@ldap", ".", "search", "(", "filter", ":", "\"(&(objectClass=user)(mail=#{email}))\"", ")", "if", "entry", "&&", "entry", ".", "count", "==", "1", "user", "=", "User", ".", "find_by", "(", "email", ":", "email", ",", "ldap", ":", "true", ")", "entry", "=", "@ldap", ".", "bind_as", "(", "filter", ":", "\"(&(objectClass=user)(mail=#{email}))\"", ",", "password", ":", "password", ")", "unless", "entry", "&&", "entry", ".", "count", "==", "1", "add_failure_to", "user", "||", "email", ",", "'(LDAP) failed to authenticate'", ",", "client_ip", "return", "nil", "end", "user", "=", "load_ldap_user", "(", "entry", ".", "first", ",", "true", ",", "client_ip", ")", "unless", "user", ".", "enabled?", "add_failure_to", "user", ",", "'(LDAP) account disabled'", ",", "client_ip", "return", "nil", "end", "add_success_to", "user", ",", "'(LDAP)'", ",", "client_ip", "return", "user", "end", "else", "user", "=", "User", ".", "find_by", "(", "email", ":", "email", ")", "if", "user", "if", "user", ".", "ldap?", "add_failure_to", "user", ",", "'(DB) cannot authenticate LDAP user'", ",", "client_ip", "return", "nil", "end", "unless", "user", ".", "enabled?", "add_failure_to", "user", ",", "'(DB) account disabled'", ",", "client_ip", "return", "nil", "end", "if", "user", ".", "authenticate", "(", "password", ")", "add_success_to", "user", ",", "'(DB)'", ",", "client_ip", "return", "user", "else", "add_failure_to", "user", ",", "'(DB) invalid password'", ",", "client_ip", "return", "nil", "end", "end", "end", "end", "add_failure_to", "email", ",", "'invalid email'", ",", "client_ip", "nil", "end" ]
Attempts to authenticate the user and returns the model on success.
[ "Attempts", "to", "authenticate", "the", "user", "and", "returns", "the", "model", "on", "success", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/user_manager.rb#L69-L122
train
barkerest/barkest_core
app/models/barkest_core/user_manager.rb
BarkestCore.UserManager.ldap_system_admin_groups
def ldap_system_admin_groups @ldap_system_admin_groups ||= begin val = @options[:ldap_system_admin_groups] val.blank? ? [] : val.strip.gsub(',', ';').split(';').map{|v| v.strip.upcase} end end
ruby
def ldap_system_admin_groups @ldap_system_admin_groups ||= begin val = @options[:ldap_system_admin_groups] val.blank? ? [] : val.strip.gsub(',', ';').split(';').map{|v| v.strip.upcase} end end
[ "def", "ldap_system_admin_groups", "@ldap_system_admin_groups", "||=", "begin", "val", "=", "@options", "[", ":ldap_system_admin_groups", "]", "val", ".", "blank?", "?", "[", "]", ":", "val", ".", "strip", ".", "gsub", "(", "','", ",", "';'", ")", ".", "split", "(", "';'", ")", ".", "map", "{", "|", "v", "|", "v", ".", "strip", ".", "upcase", "}", "end", "end" ]
Gets the list of ldap groups that map to system administrators.
[ "Gets", "the", "list", "of", "ldap", "groups", "that", "map", "to", "system", "administrators", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/user_manager.rb#L144-L150
train
byu/serf
lib/serf/serfer.rb
Serf.Serfer.call
def call(parcel) # 1. Execute interactor response_kind, response_message, response_headers = interactor.call parcel # 2. Extract a possible version embedded in the response_kind. # This is sugar syntax for kind and version. if response_kind kind_part, version_part = response_kind.split '#', 2 response_kind = kind_part if version_part if version_part response_headers ||= {} response_headers[:version] = version_part end end # 3. Return a new response parcel with: # a. uuids set from parent parcel # b. kind set to response kind # c. the message set to response_message # d. add extra headers to the parcel return parcel_factory.create( parent: parcel, kind: response_kind, message: response_message, headers: response_headers) end
ruby
def call(parcel) # 1. Execute interactor response_kind, response_message, response_headers = interactor.call parcel # 2. Extract a possible version embedded in the response_kind. # This is sugar syntax for kind and version. if response_kind kind_part, version_part = response_kind.split '#', 2 response_kind = kind_part if version_part if version_part response_headers ||= {} response_headers[:version] = version_part end end # 3. Return a new response parcel with: # a. uuids set from parent parcel # b. kind set to response kind # c. the message set to response_message # d. add extra headers to the parcel return parcel_factory.create( parent: parcel, kind: response_kind, message: response_message, headers: response_headers) end
[ "def", "call", "(", "parcel", ")", "response_kind", ",", "response_message", ",", "response_headers", "=", "interactor", ".", "call", "parcel", "if", "response_kind", "kind_part", ",", "version_part", "=", "response_kind", ".", "split", "'#'", ",", "2", "response_kind", "=", "kind_part", "if", "version_part", "if", "version_part", "response_headers", "||=", "{", "}", "response_headers", "[", ":version", "]", "=", "version_part", "end", "end", "return", "parcel_factory", ".", "create", "(", "parent", ":", "parcel", ",", "kind", ":", "response_kind", ",", "message", ":", "response_message", ",", "headers", ":", "response_headers", ")", "end" ]
Rack-like call to run the Interactor's use-case.
[ "Rack", "-", "like", "call", "to", "run", "the", "Interactor", "s", "use", "-", "case", "." ]
0ab177be4784846e0b8ed093cc8580c877184bbf
https://github.com/byu/serf/blob/0ab177be4784846e0b8ed093cc8580c877184bbf/lib/serf/serfer.rb#L27-L52
train
factor-io/pivotal-api
lib/pivotal_api/client.rb
PivotalApi.Client.me
def me data = get("/me").body Resources::Me.new({ client: self }.merge(data)) end
ruby
def me data = get("/me").body Resources::Me.new({ client: self }.merge(data)) end
[ "def", "me", "data", "=", "get", "(", "\"/me\"", ")", ".", "body", "Resources", "::", "Me", ".", "new", "(", "{", "client", ":", "self", "}", ".", "merge", "(", "data", ")", ")", "end" ]
Get information about the authenticated user @return [PivotalApi::Resources::Me]
[ "Get", "information", "about", "the", "authenticated", "user" ]
e51d16689ad49894cba7f136e02d6758cc38fde0
https://github.com/factor-io/pivotal-api/blob/e51d16689ad49894cba7f136e02d6758cc38fde0/lib/pivotal_api/client.rb#L131-L135
train
jgoizueta/numerals
lib/numerals/format/symbols.rb
Numerals.Format::Symbols.regexp
def regexp(*args) options = args.pop if args.last.is_a?(Hash) options ||= {} symbols = args digits = symbols.delete(:digits) grouped_digits = symbols.delete(:grouped_digits) symbols = symbols.map { |s| s.is_a?(Symbol) ? send(s) : s } if grouped_digits symbols += [group_separator, insignificant_digit] elsif digits symbols += [insignificant_digit] end if digits || grouped_digits symbols += @digits.digits(options) end regexp_group(symbols, options) end
ruby
def regexp(*args) options = args.pop if args.last.is_a?(Hash) options ||= {} symbols = args digits = symbols.delete(:digits) grouped_digits = symbols.delete(:grouped_digits) symbols = symbols.map { |s| s.is_a?(Symbol) ? send(s) : s } if grouped_digits symbols += [group_separator, insignificant_digit] elsif digits symbols += [insignificant_digit] end if digits || grouped_digits symbols += @digits.digits(options) end regexp_group(symbols, options) end
[ "def", "regexp", "(", "*", "args", ")", "options", "=", "args", ".", "pop", "if", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "options", "||=", "{", "}", "symbols", "=", "args", "digits", "=", "symbols", ".", "delete", "(", ":digits", ")", "grouped_digits", "=", "symbols", ".", "delete", "(", ":grouped_digits", ")", "symbols", "=", "symbols", ".", "map", "{", "|", "s", "|", "s", ".", "is_a?", "(", "Symbol", ")", "?", "send", "(", "s", ")", ":", "s", "}", "if", "grouped_digits", "symbols", "+=", "[", "group_separator", ",", "insignificant_digit", "]", "elsif", "digits", "symbols", "+=", "[", "insignificant_digit", "]", "end", "if", "digits", "||", "grouped_digits", "symbols", "+=", "@digits", ".", "digits", "(", "options", ")", "end", "regexp_group", "(", "symbols", ",", "options", ")", "end" ]
Generate a regular expression to match any of the passed symbols. symbols.regexp(:nan, :plus, :minus) #=> "(NaN|+|-)" The special symbol :digits can also be passed to generate all the digits, in which case the :base option can be used to generate digits only for some base smaller than the maximum defined for digits. symbols.regexp(:digits, :point, base: 10) # => "(0|1|...|9)" The option :no_capture can be used to avoid generating a capturing group; otherwise the result is captured group (surrounded by parenthesis) symbols.regexp(:digits, no_capture: true) # => "(?:...)" The :case_sensitivity option is used to generate a regular expression that matches the case of the text as defined by ghe case_sensitive attribute of the Symbols. If this option is used the result should not be used in a case-insensitive regular expression (/.../i). /#{symbols.regexp(:digits, case_sensitivity: true)}/ If the options is not used, than the regular expression should be be made case-insensitive according to the Symbols: if symbols.case_sensitive? /#{symbols.regexp(:digits)}/ else /#{symbols.regexp(:digits)}/i
[ "Generate", "a", "regular", "expression", "to", "match", "any", "of", "the", "passed", "symbols", "." ]
a195e75f689af926537f791441bf8d11590c99c0
https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/format/symbols.rb#L343-L361
train
octopress/filters
lib/octopress-filters.rb
Octopress.Filters.expand_url
def expand_url(input, url=nil) url ||= root url = if input.start_with?("http", url) input else File.join(url, input) end smart_slash(url) end
ruby
def expand_url(input, url=nil) url ||= root url = if input.start_with?("http", url) input else File.join(url, input) end smart_slash(url) end
[ "def", "expand_url", "(", "input", ",", "url", "=", "nil", ")", "url", "||=", "root", "url", "=", "if", "input", ".", "start_with?", "(", "\"http\"", ",", "url", ")", "input", "else", "File", ".", "join", "(", "url", ",", "input", ")", "end", "smart_slash", "(", "url", ")", "end" ]
Prepends input with a url fragment input - An absolute url, e.g. /images/awesome.gif url - The fragment to prepend the input, e.g. /blog Returns the modified url, e.g /blog
[ "Prepends", "input", "with", "a", "url", "fragment" ]
c39238f40881c66db9a7ea648f81df5560cf872e
https://github.com/octopress/filters/blob/c39238f40881c66db9a7ea648f81df5560cf872e/lib/octopress-filters.rb#L124-L134
train