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
wr0ngway/lumber
lib/lumber/level_util.rb
Lumber.LevelUtil.backup_levels
def backup_levels(loggers) synchronize do loggers.each do |name| outputter = Log4r::Outputter[name] if outputter @original_outputter_levels[name] ||= outputter.level else logger = Lumber.find_or_create_logger(name) # only store the old level if we haven't overriden it's logger yet @original_levels[name] ||= logger.level end end end end
ruby
def backup_levels(loggers) synchronize do loggers.each do |name| outputter = Log4r::Outputter[name] if outputter @original_outputter_levels[name] ||= outputter.level else logger = Lumber.find_or_create_logger(name) # only store the old level if we haven't overriden it's logger yet @original_levels[name] ||= logger.level end end end end
[ "def", "backup_levels", "(", "loggers", ")", "synchronize", "do", "loggers", ".", "each", "do", "|", "name", "|", "outputter", "=", "Log4r", "::", "Outputter", "[", "name", "]", "if", "outputter", "@original_outputter_levels", "[", "name", "]", "||=", "outputter", ".", "level", "else", "logger", "=", "Lumber", ".", "find_or_create_logger", "(", "name", ")", "@original_levels", "[", "name", "]", "||=", "logger", ".", "level", "end", "end", "end", "end" ]
Backs up original values of logger levels before we overwrite them This is better in local memory since we shouldn't reset loggers that we haven't set @param [Enumerable<String>] The logger names to backup
[ "Backs", "up", "original", "values", "of", "logger", "levels", "before", "we", "overwrite", "them", "This", "is", "better", "in", "local", "memory", "since", "we", "shouldn", "t", "reset", "loggers", "that", "we", "haven", "t", "set" ]
6a483ea44f496d4e98f5698590be59941b58fe9b
https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/level_util.rb#L109-L122
train
wr0ngway/lumber
lib/lumber/level_util.rb
Lumber.LevelUtil.restore_levels
def restore_levels synchronize do @original_outputter_levels.each do |name, level| outputter = Log4r::Outputter[name] outputter.level = level if outputter.level != level end @original_outputter_levels.clear @original_levels.each do |name, level| logger = Lumber.find_or_create_logger(name) logger.level = level if logger.level != level end @original_levels.clear end end
ruby
def restore_levels synchronize do @original_outputter_levels.each do |name, level| outputter = Log4r::Outputter[name] outputter.level = level if outputter.level != level end @original_outputter_levels.clear @original_levels.each do |name, level| logger = Lumber.find_or_create_logger(name) logger.level = level if logger.level != level end @original_levels.clear end end
[ "def", "restore_levels", "synchronize", "do", "@original_outputter_levels", ".", "each", "do", "|", "name", ",", "level", "|", "outputter", "=", "Log4r", "::", "Outputter", "[", "name", "]", "outputter", ".", "level", "=", "level", "if", "outputter", ".", "level", "!=", "level", "end", "@original_outputter_levels", ".", "clear", "@original_levels", ".", "each", "do", "|", "name", ",", "level", "|", "logger", "=", "Lumber", ".", "find_or_create_logger", "(", "name", ")", "logger", ".", "level", "=", "level", "if", "logger", ".", "level", "!=", "level", "end", "@original_levels", ".", "clear", "end", "end" ]
Restores original values of logger levels after expiration
[ "Restores", "original", "values", "of", "logger", "levels", "after", "expiration" ]
6a483ea44f496d4e98f5698590be59941b58fe9b
https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/level_util.rb#L125-L139
train
weenhanceit/gaapi
lib/gaapi/row.rb
GAAPI.Row.method_missing
def method_missing(method, *args) if (i = dimension_method_names.find_index(method)) define_singleton_method(method) do dimensions[i] end send(method) elsif (i = metric_method_names.find_index(method)) define_singleton_method(method) do convert_metric(i) end send(method) else super end end
ruby
def method_missing(method, *args) if (i = dimension_method_names.find_index(method)) define_singleton_method(method) do dimensions[i] end send(method) elsif (i = metric_method_names.find_index(method)) define_singleton_method(method) do convert_metric(i) end send(method) else super end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ")", "if", "(", "i", "=", "dimension_method_names", ".", "find_index", "(", "method", ")", ")", "define_singleton_method", "(", "method", ")", "do", "dimensions", "[", "i", "]", "end", "send", "(", "method", ")", "elsif", "(", "i", "=", "metric_method_names", ".", "find_index", "(", "method", ")", ")", "define_singleton_method", "(", "method", ")", "do", "convert_metric", "(", "i", ")", "end", "send", "(", "method", ")", "else", "super", "end", "end" ]
Define and call methods to return the value of the dimensions and metrics in the report. @!macro method_missing
[ "Define", "and", "call", "methods", "to", "return", "the", "value", "of", "the", "dimensions", "and", "metrics", "in", "the", "report", "." ]
20d25bd06b2e0cccc86ca1ea1baaac6be045355a
https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/row.rb#L37-L51
train
weenhanceit/gaapi
lib/gaapi/row.rb
GAAPI.Row.convert_metric
def convert_metric(i) case report.metric_type(i) when "INTEGER" # INTEGER Integer metric. metrics[i].to_i when "FLOAT", "PERCENT" # FLOAT Float metric. # PERCENT Percentage metric. metrics[i].to_f when "CURRENCY" # CURRENCY Currency metric. # TODO: Do this better. metrics[i].to_f when "TIME" # Google documentation claims to following: # TIME Time metric in HH:MM:SS format. # It also says it's seconds, and that's what I see in real results. # So comment out the following: # (metrics[i][0..1].to_i + # metrics[i][3..4].to_i * 60 + # metrics[i][6..7].to_i * 24 * 60) # Simply make it a float. metrics[i].to_f else # METRIC_TYPE_UNSPECIFIED Metric type is unspecified. metric[i] end end
ruby
def convert_metric(i) case report.metric_type(i) when "INTEGER" # INTEGER Integer metric. metrics[i].to_i when "FLOAT", "PERCENT" # FLOAT Float metric. # PERCENT Percentage metric. metrics[i].to_f when "CURRENCY" # CURRENCY Currency metric. # TODO: Do this better. metrics[i].to_f when "TIME" # Google documentation claims to following: # TIME Time metric in HH:MM:SS format. # It also says it's seconds, and that's what I see in real results. # So comment out the following: # (metrics[i][0..1].to_i + # metrics[i][3..4].to_i * 60 + # metrics[i][6..7].to_i * 24 * 60) # Simply make it a float. metrics[i].to_f else # METRIC_TYPE_UNSPECIFIED Metric type is unspecified. metric[i] end end
[ "def", "convert_metric", "(", "i", ")", "case", "report", ".", "metric_type", "(", "i", ")", "when", "\"INTEGER\"", "metrics", "[", "i", "]", ".", "to_i", "when", "\"FLOAT\"", ",", "\"PERCENT\"", "metrics", "[", "i", "]", ".", "to_f", "when", "\"CURRENCY\"", "metrics", "[", "i", "]", ".", "to_f", "when", "\"TIME\"", "metrics", "[", "i", "]", ".", "to_f", "else", "metric", "[", "i", "]", "end", "end" ]
Convert metric to the right type.
[ "Convert", "metric", "to", "the", "right", "type", "." ]
20d25bd06b2e0cccc86ca1ea1baaac6be045355a
https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/row.rb#L87-L114
train
PeterCamilleri/mini_term
lib/mini_term/common/mapper.rb
MiniTerm.Mapper.[]=
def []=(indexes, value) indexes = [indexes] unless indexes.is_a?(Range) indexes.each do |index| process_non_terminals(index) if @map.has_key?(index) fail MiniTermKME, "Duplicate entry #{index.inspect}" end @map[index] = [value, index] end end
ruby
def []=(indexes, value) indexes = [indexes] unless indexes.is_a?(Range) indexes.each do |index| process_non_terminals(index) if @map.has_key?(index) fail MiniTermKME, "Duplicate entry #{index.inspect}" end @map[index] = [value, index] end end
[ "def", "[]=", "(", "indexes", ",", "value", ")", "indexes", "=", "[", "indexes", "]", "unless", "indexes", ".", "is_a?", "(", "Range", ")", "indexes", ".", "each", "do", "|", "index", "|", "process_non_terminals", "(", "index", ")", "if", "@map", ".", "has_key?", "(", "index", ")", "fail", "MiniTermKME", ",", "\"Duplicate entry #{index.inspect}\"", "end", "@map", "[", "index", "]", "=", "[", "value", ",", "index", "]", "end", "end" ]
Set up the keystroke mapper. Add a map entry
[ "Set", "up", "the", "keystroke", "mapper", ".", "Add", "a", "map", "entry" ]
71c179e82d3a353144d7e100ee0df89c2d71fac8
https://github.com/PeterCamilleri/mini_term/blob/71c179e82d3a353144d7e100ee0df89c2d71fac8/lib/mini_term/common/mapper.rb#L16-L28
train
PeterCamilleri/mini_term
lib/mini_term/common/mapper.rb
MiniTerm.Mapper.process_non_terminals
def process_non_terminals(index) seq = "" index.chop.chars.each do |char| seq << char if @map.has_key?(seq) && @map[seq] fail MiniTermKME, "Ambiguous entry #{index.inspect}" end @map[seq] = false end end
ruby
def process_non_terminals(index) seq = "" index.chop.chars.each do |char| seq << char if @map.has_key?(seq) && @map[seq] fail MiniTermKME, "Ambiguous entry #{index.inspect}" end @map[seq] = false end end
[ "def", "process_non_terminals", "(", "index", ")", "seq", "=", "\"\"", "index", ".", "chop", ".", "chars", ".", "each", "do", "|", "char", "|", "seq", "<<", "char", "if", "@map", ".", "has_key?", "(", "seq", ")", "&&", "@map", "[", "seq", "]", "fail", "MiniTermKME", ",", "\"Ambiguous entry #{index.inspect}\"", "end", "@map", "[", "seq", "]", "=", "false", "end", "end" ]
Handle the preamble characters in the command sequence.
[ "Handle", "the", "preamble", "characters", "in", "the", "command", "sequence", "." ]
71c179e82d3a353144d7e100ee0df89c2d71fac8
https://github.com/PeterCamilleri/mini_term/blob/71c179e82d3a353144d7e100ee0df89c2d71fac8/lib/mini_term/common/mapper.rb#L31-L43
train
Bweeb/malcolm
lib/malcolm/request/soap_builder.rb
Malcolm.SOAPBuilder.wrap
def wrap(data) "<?xml version=\"1.0\" encoding=\"UTF-8\"?><env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"><env:Body>".tap do |soap_envelope| unless data.blank? soap_envelope << (data.is_a?(Hash) ? Gyoku.xml(data) : data) end soap_envelope << "</env:Body></env:Envelope>" end end
ruby
def wrap(data) "<?xml version=\"1.0\" encoding=\"UTF-8\"?><env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"><env:Body>".tap do |soap_envelope| unless data.blank? soap_envelope << (data.is_a?(Hash) ? Gyoku.xml(data) : data) end soap_envelope << "</env:Body></env:Envelope>" end end
[ "def", "wrap", "(", "data", ")", "\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><env:Envelope xmlns:env=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\"><env:Body>\"", ".", "tap", "do", "|", "soap_envelope", "|", "unless", "data", ".", "blank?", "soap_envelope", "<<", "(", "data", ".", "is_a?", "(", "Hash", ")", "?", "Gyoku", ".", "xml", "(", "data", ")", ":", "data", ")", "end", "soap_envelope", "<<", "\"</env:Body></env:Envelope>\"", "end", "end" ]
Builds an XML document around request data
[ "Builds", "an", "XML", "document", "around", "request", "data" ]
8a6253ec72a6c15a25fb765d4fceb4d0ede165e7
https://github.com/Bweeb/malcolm/blob/8a6253ec72a6c15a25fb765d4fceb4d0ede165e7/lib/malcolm/request/soap_builder.rb#L14-L21
train
dfhoughton/list_matcher
lib/list_matcher.rb
List.Matcher.bud
def bud(opts={}) opts = { atomic: @atomic, backtracking: @backtracking, bound: @_bound, strip: @strip, case_insensitive: @case_insensitive, multiline: @multiline, not_extended: @not_extended, normalize_whitespace: @normalize_whitespace, symbols: @symbols, name: @name, vet: @vet && opts[:symbols] }.merge opts self.class.new(**opts) end
ruby
def bud(opts={}) opts = { atomic: @atomic, backtracking: @backtracking, bound: @_bound, strip: @strip, case_insensitive: @case_insensitive, multiline: @multiline, not_extended: @not_extended, normalize_whitespace: @normalize_whitespace, symbols: @symbols, name: @name, vet: @vet && opts[:symbols] }.merge opts self.class.new(**opts) end
[ "def", "bud", "(", "opts", "=", "{", "}", ")", "opts", "=", "{", "atomic", ":", "@atomic", ",", "backtracking", ":", "@backtracking", ",", "bound", ":", "@_bound", ",", "strip", ":", "@strip", ",", "case_insensitive", ":", "@case_insensitive", ",", "multiline", ":", "@multiline", ",", "not_extended", ":", "@not_extended", ",", "normalize_whitespace", ":", "@normalize_whitespace", ",", "symbols", ":", "@symbols", ",", "name", ":", "@name", ",", "vet", ":", "@vet", "&&", "opts", "[", ":symbols", "]", "}", ".", "merge", "opts", "self", ".", "class", ".", "new", "(", "**", "opts", ")", "end" ]
returns a new pattern matcher differing from the original only in the options specified
[ "returns", "a", "new", "pattern", "matcher", "differing", "from", "the", "original", "only", "in", "the", "options", "specified" ]
cbc2368251e8a69ac99aea84fbd64034c1ff7c88
https://github.com/dfhoughton/list_matcher/blob/cbc2368251e8a69ac99aea84fbd64034c1ff7c88/lib/list_matcher.rb#L126-L141
train
dfhoughton/list_matcher
lib/list_matcher.rb
List.Matcher.pattern
def pattern( list, opts={} ) return '(?!)' unless list.any? return bud(opts).pattern list unless opts.empty? list = list.compact.map(&:to_s).select{ |s| s.length > 0 } list.map!(&:strip).select!{ |s| s.length > 0 } if strip list.map!{ |s| s.gsub %r/\s++/, ' ' } if normalize_whitespace return nil if list.empty? specializer = Special.new self, @symbols, list list = specializer.normalize root = tree list, specializer root.root = true root.flatten rx = root.convert if m = modifiers rx = "(?#{m}:#{rx})" grouped = true end if name rx = "(?<#{name}>#{rx})" grouped = true end return rx if grouped && backtracking if atomic && !root.atomic? wrap rx else rx end end
ruby
def pattern( list, opts={} ) return '(?!)' unless list.any? return bud(opts).pattern list unless opts.empty? list = list.compact.map(&:to_s).select{ |s| s.length > 0 } list.map!(&:strip).select!{ |s| s.length > 0 } if strip list.map!{ |s| s.gsub %r/\s++/, ' ' } if normalize_whitespace return nil if list.empty? specializer = Special.new self, @symbols, list list = specializer.normalize root = tree list, specializer root.root = true root.flatten rx = root.convert if m = modifiers rx = "(?#{m}:#{rx})" grouped = true end if name rx = "(?<#{name}>#{rx})" grouped = true end return rx if grouped && backtracking if atomic && !root.atomic? wrap rx else rx end end
[ "def", "pattern", "(", "list", ",", "opts", "=", "{", "}", ")", "return", "'(?!)'", "unless", "list", ".", "any?", "return", "bud", "(", "opts", ")", ".", "pattern", "list", "unless", "opts", ".", "empty?", "list", "=", "list", ".", "compact", ".", "map", "(", "&", ":to_s", ")", ".", "select", "{", "|", "s", "|", "s", ".", "length", ">", "0", "}", "list", ".", "map!", "(", "&", ":strip", ")", ".", "select!", "{", "|", "s", "|", "s", ".", "length", ">", "0", "}", "if", "strip", "list", ".", "map!", "{", "|", "s", "|", "s", ".", "gsub", "%r/", "\\s", "/", ",", "' '", "}", "if", "normalize_whitespace", "return", "nil", "if", "list", ".", "empty?", "specializer", "=", "Special", ".", "new", "self", ",", "@symbols", ",", "list", "list", "=", "specializer", ".", "normalize", "root", "=", "tree", "list", ",", "specializer", "root", ".", "root", "=", "true", "root", ".", "flatten", "rx", "=", "root", ".", "convert", "if", "m", "=", "modifiers", "rx", "=", "\"(?#{m}:#{rx})\"", "grouped", "=", "true", "end", "if", "name", "rx", "=", "\"(?<#{name}>#{rx})\"", "grouped", "=", "true", "end", "return", "rx", "if", "grouped", "&&", "backtracking", "if", "atomic", "&&", "!", "root", ".", "atomic?", "wrap", "rx", "else", "rx", "end", "end" ]
converst list into a string representing a regex pattern suitable for inclusion in a larger regex
[ "converst", "list", "into", "a", "string", "representing", "a", "regex", "pattern", "suitable", "for", "inclusion", "in", "a", "larger", "regex" ]
cbc2368251e8a69ac99aea84fbd64034c1ff7c88
https://github.com/dfhoughton/list_matcher/blob/cbc2368251e8a69ac99aea84fbd64034c1ff7c88/lib/list_matcher.rb#L144-L172
train
MustWin/missinglink
app/models/missinglink/survey_question.rb
Missinglink.SurveyQuestion.possible_responses
def possible_responses(search_other = false) {}.tap do |hash| survey_response_answers.each do |sra| sa_row = (sra.row_survey_answer_id ? SurveyAnswer.find(sra.row_survey_answer_id) : nil) sa_col = (sra.col_survey_answer_id ? SurveyAnswer.find(sra.col_survey_answer_id) : nil) sa_col_choice = (sra.col_choice_survey_answer_id ? SurveyAnswer.find(sra.col_choice_survey_answer_id) : nil) case answer_strategy when "first_survey_response_answer_text" hash[sra.text] = sra.id unless (sra.text.nil? || hash[sra.text]) when "answer_row_for_subquestion" other_text = (sra.text.nil? ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }") hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) when "answer_row_for_response" other_text = ((!search_other || sra.text.nil?) ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }") hash[sa_row.text] = sra.id unless (sa_row.nil? || hash[sa_row.text]) hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) when "answer_row_and_column_for_response" main_text = "#{ sa_row.try(:text) }: #{ sa_col.try(:text) }" other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }") hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || hash[main_text]) hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) when "answer_row_column_choice_for_response" main_text = "#{ sa_row.try(:text) }, #{ sa_col.try(:text) }: #{ sa_col_choice.try(:text) }" other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }") hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || sa_col_choice.nil? || hash[main_text]) hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) end end end end
ruby
def possible_responses(search_other = false) {}.tap do |hash| survey_response_answers.each do |sra| sa_row = (sra.row_survey_answer_id ? SurveyAnswer.find(sra.row_survey_answer_id) : nil) sa_col = (sra.col_survey_answer_id ? SurveyAnswer.find(sra.col_survey_answer_id) : nil) sa_col_choice = (sra.col_choice_survey_answer_id ? SurveyAnswer.find(sra.col_choice_survey_answer_id) : nil) case answer_strategy when "first_survey_response_answer_text" hash[sra.text] = sra.id unless (sra.text.nil? || hash[sra.text]) when "answer_row_for_subquestion" other_text = (sra.text.nil? ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }") hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) when "answer_row_for_response" other_text = ((!search_other || sra.text.nil?) ? nil : "#{ (sa_row.try(:text) || "Other") }: #{ sra.text }") hash[sa_row.text] = sra.id unless (sa_row.nil? || hash[sa_row.text]) hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) when "answer_row_and_column_for_response" main_text = "#{ sa_row.try(:text) }: #{ sa_col.try(:text) }" other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }") hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || hash[main_text]) hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) when "answer_row_column_choice_for_response" main_text = "#{ sa_row.try(:text) }, #{ sa_col.try(:text) }: #{ sa_col_choice.try(:text) }" other_text = ((!search_other || sra.text.nil? || !sa_row.nil?) ? nil : "Other: #{ sra.text }") hash[main_text] = sra.id unless (sa_row.nil? || sa_col.nil? || sa_col_choice.nil? || hash[main_text]) hash[other_text] = sra.id unless (other_text.nil? || hash[other_text]) end end end end
[ "def", "possible_responses", "(", "search_other", "=", "false", ")", "{", "}", ".", "tap", "do", "|", "hash", "|", "survey_response_answers", ".", "each", "do", "|", "sra", "|", "sa_row", "=", "(", "sra", ".", "row_survey_answer_id", "?", "SurveyAnswer", ".", "find", "(", "sra", ".", "row_survey_answer_id", ")", ":", "nil", ")", "sa_col", "=", "(", "sra", ".", "col_survey_answer_id", "?", "SurveyAnswer", ".", "find", "(", "sra", ".", "col_survey_answer_id", ")", ":", "nil", ")", "sa_col_choice", "=", "(", "sra", ".", "col_choice_survey_answer_id", "?", "SurveyAnswer", ".", "find", "(", "sra", ".", "col_choice_survey_answer_id", ")", ":", "nil", ")", "case", "answer_strategy", "when", "\"first_survey_response_answer_text\"", "hash", "[", "sra", ".", "text", "]", "=", "sra", ".", "id", "unless", "(", "sra", ".", "text", ".", "nil?", "||", "hash", "[", "sra", ".", "text", "]", ")", "when", "\"answer_row_for_subquestion\"", "other_text", "=", "(", "sra", ".", "text", ".", "nil?", "?", "nil", ":", "\"#{ (sa_row.try(:text) || \"Other\") }: #{ sra.text }\"", ")", "hash", "[", "other_text", "]", "=", "sra", ".", "id", "unless", "(", "other_text", ".", "nil?", "||", "hash", "[", "other_text", "]", ")", "when", "\"answer_row_for_response\"", "other_text", "=", "(", "(", "!", "search_other", "||", "sra", ".", "text", ".", "nil?", ")", "?", "nil", ":", "\"#{ (sa_row.try(:text) || \"Other\") }: #{ sra.text }\"", ")", "hash", "[", "sa_row", ".", "text", "]", "=", "sra", ".", "id", "unless", "(", "sa_row", ".", "nil?", "||", "hash", "[", "sa_row", ".", "text", "]", ")", "hash", "[", "other_text", "]", "=", "sra", ".", "id", "unless", "(", "other_text", ".", "nil?", "||", "hash", "[", "other_text", "]", ")", "when", "\"answer_row_and_column_for_response\"", "main_text", "=", "\"#{ sa_row.try(:text) }: #{ sa_col.try(:text) }\"", "other_text", "=", "(", "(", "!", "search_other", "||", "sra", ".", "text", ".", "nil?", "||", "!", "sa_row", ".", "nil?", ")", "?", "nil", ":", "\"Other: #{ sra.text }\"", ")", "hash", "[", "main_text", "]", "=", "sra", ".", "id", "unless", "(", "sa_row", ".", "nil?", "||", "sa_col", ".", "nil?", "||", "hash", "[", "main_text", "]", ")", "hash", "[", "other_text", "]", "=", "sra", ".", "id", "unless", "(", "other_text", ".", "nil?", "||", "hash", "[", "other_text", "]", ")", "when", "\"answer_row_column_choice_for_response\"", "main_text", "=", "\"#{ sa_row.try(:text) }, #{ sa_col.try(:text) }: #{ sa_col_choice.try(:text) }\"", "other_text", "=", "(", "(", "!", "search_other", "||", "sra", ".", "text", ".", "nil?", "||", "!", "sa_row", ".", "nil?", ")", "?", "nil", ":", "\"Other: #{ sra.text }\"", ")", "hash", "[", "main_text", "]", "=", "sra", ".", "id", "unless", "(", "sa_row", ".", "nil?", "||", "sa_col", ".", "nil?", "||", "sa_col_choice", ".", "nil?", "||", "hash", "[", "main_text", "]", ")", "hash", "[", "other_text", "]", "=", "sra", ".", "id", "unless", "(", "other_text", ".", "nil?", "||", "hash", "[", "other_text", "]", ")", "end", "end", "end", "end" ]
for reference, when searching, listing all possible responses is logical, but it is impossible to track all survey response answers that match the desired answer. therefore, we only track one example, and later find all similar response answers based on the question strategy
[ "for", "reference", "when", "searching", "listing", "all", "possible", "responses", "is", "logical", "but", "it", "is", "impossible", "to", "track", "all", "survey", "response", "answers", "that", "match", "the", "desired", "answer", ".", "therefore", "we", "only", "track", "one", "example", "and", "later", "find", "all", "similar", "response", "answers", "based", "on", "the", "question", "strategy" ]
732f362cc802a73946a36aa5b469957e6487f48a
https://github.com/MustWin/missinglink/blob/732f362cc802a73946a36aa5b469957e6487f48a/app/models/missinglink/survey_question.rb#L41-L71
train
SquareSquash/uploader
lib/squash/uploader.rb
Squash.Uploader.http_post
def http_post(url, headers, bodies) uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') http.open_timeout = options[:open_timeout] http.read_timeout = options[:read_timeout] http.verify_mode = OpenSSL::SSL::VERIFY_NONE if options[:skip_verification] http.start do |session| bodies.each do |body| request = Net::HTTP::Post.new(uri.request_uri) headers.each { |k, v| request.add_field k, v } request.body = body response = session.request(request) if options[:success].none? { |cl| if cl.kind_of?(Class) response.kind_of?(cl) elsif cl.kind_of?(Fixnum) || cl.kind_of?(String) response.code.to_i == cl.to_i else raise ArgumentError, "Unknown :success value #{cl}" end } raise "Unexpected response from Squash host: #{response.code}" end end end end
ruby
def http_post(url, headers, bodies) uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') http.open_timeout = options[:open_timeout] http.read_timeout = options[:read_timeout] http.verify_mode = OpenSSL::SSL::VERIFY_NONE if options[:skip_verification] http.start do |session| bodies.each do |body| request = Net::HTTP::Post.new(uri.request_uri) headers.each { |k, v| request.add_field k, v } request.body = body response = session.request(request) if options[:success].none? { |cl| if cl.kind_of?(Class) response.kind_of?(cl) elsif cl.kind_of?(Fixnum) || cl.kind_of?(String) response.code.to_i == cl.to_i else raise ArgumentError, "Unknown :success value #{cl}" end } raise "Unexpected response from Squash host: #{response.code}" end end end end
[ "def", "http_post", "(", "url", ",", "headers", ",", "bodies", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "(", "uri", ".", "scheme", "==", "'https'", ")", "http", ".", "open_timeout", "=", "options", "[", ":open_timeout", "]", "http", ".", "read_timeout", "=", "options", "[", ":read_timeout", "]", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "if", "options", "[", ":skip_verification", "]", "http", ".", "start", "do", "|", "session", "|", "bodies", ".", "each", "do", "|", "body", "|", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ")", "headers", ".", "each", "{", "|", "k", ",", "v", "|", "request", ".", "add_field", "k", ",", "v", "}", "request", ".", "body", "=", "body", "response", "=", "session", ".", "request", "(", "request", ")", "if", "options", "[", ":success", "]", ".", "none?", "{", "|", "cl", "|", "if", "cl", ".", "kind_of?", "(", "Class", ")", "response", ".", "kind_of?", "(", "cl", ")", "elsif", "cl", ".", "kind_of?", "(", "Fixnum", ")", "||", "cl", ".", "kind_of?", "(", "String", ")", "response", ".", "code", ".", "to_i", "==", "cl", ".", "to_i", "else", "raise", "ArgumentError", ",", "\"Unknown :success value #{cl}\"", "end", "}", "raise", "\"Unexpected response from Squash host: #{response.code}\"", "end", "end", "end", "end" ]
Override this method to use your favorite HTTP library. This method receives an array of bodies. It is intended that each element of the array be transmitted as a separate POST request, _not_ that the bodies be concatenated and sent as one request. A response of code found in the `:success` option is considered successful. @param [String] url The URL to POST to. @param [Hash<String, String>] headers The request headers. @param [Array<String>] bodies The bodies of each request to POST. @raise [StandardError] If a response other than 2xx or 422 is returned.
[ "Override", "this", "method", "to", "use", "your", "favorite", "HTTP", "library", ".", "This", "method", "receives", "an", "array", "of", "bodies", ".", "It", "is", "intended", "that", "each", "element", "of", "the", "array", "be", "transmitted", "as", "a", "separate", "POST", "request", "_not_", "that", "the", "bodies", "be", "concatenated", "and", "sent", "as", "one", "request", "." ]
6a0aa2b5ca6298492fcf11b7b07458e2cadb5c92
https://github.com/SquareSquash/uploader/blob/6a0aa2b5ca6298492fcf11b7b07458e2cadb5c92/lib/squash/uploader.rb#L88-L116
train
rtjoseph11/modernizer
lib/modernizer.rb
Modernize.Modernizer.translate
def translate(context, hash) # makes sure that the context is a hash raise ArgumentError.new('did not pass a hash for the context') unless context.is_a?(Hash) raise ArgumentError.new('cannot provide include hash in context') if context[:hash] # create the context instance for instance variables struct = StructContext.new(context, hash) # instantiate MapMethods to perform translations and define lambda # for how to tranlate a field # translate = lambda { |t| MapMethods.send(t[:name], struct, t[:field], t[:block]) } # determine the version of the incoming hash # struct_version = struct.instance_exec(&@migrations.version) raise StandardError.new('calculated version is not valid') unless Gem::Version.correct?(struct_version) # gets a list of the potential versions # migration_versions = @migrations.translations.keys migration_versions.delete(:first) migration_versions.delete(:last) # get the first and last translations # firsts = @migrations.translations[:first] lasts = @migrations.translations[:last] # sorts the versions # migration_versions.sort! do |x,y| Gem::Version.new(x) <=> Gem::Version.new(y) end # reverse order if descending was specified # migration_versions = @migrations.order == :descending ? migration_versions.reverse : migration_versions # run the first translations if they exist # firsts.each(&translate) if firsts # determine the first version to run translations # first_index = @migrations.order == :ascending ? migration_versions.find_index(struct_version) : nil last_index = @migrations.order == :descending ? migration_versions.find_index(struct_version) : nil # run all subsequent version translations # migration_versions.each_with_index do |version, index| next unless !first_index || index >= first_index next unless !last_index || index <= last_index @migrations.translations[version].each(&translate) end # run the first translations if they exist # lasts.each(&translate) if lasts # return hash # struct.hash end
ruby
def translate(context, hash) # makes sure that the context is a hash raise ArgumentError.new('did not pass a hash for the context') unless context.is_a?(Hash) raise ArgumentError.new('cannot provide include hash in context') if context[:hash] # create the context instance for instance variables struct = StructContext.new(context, hash) # instantiate MapMethods to perform translations and define lambda # for how to tranlate a field # translate = lambda { |t| MapMethods.send(t[:name], struct, t[:field], t[:block]) } # determine the version of the incoming hash # struct_version = struct.instance_exec(&@migrations.version) raise StandardError.new('calculated version is not valid') unless Gem::Version.correct?(struct_version) # gets a list of the potential versions # migration_versions = @migrations.translations.keys migration_versions.delete(:first) migration_versions.delete(:last) # get the first and last translations # firsts = @migrations.translations[:first] lasts = @migrations.translations[:last] # sorts the versions # migration_versions.sort! do |x,y| Gem::Version.new(x) <=> Gem::Version.new(y) end # reverse order if descending was specified # migration_versions = @migrations.order == :descending ? migration_versions.reverse : migration_versions # run the first translations if they exist # firsts.each(&translate) if firsts # determine the first version to run translations # first_index = @migrations.order == :ascending ? migration_versions.find_index(struct_version) : nil last_index = @migrations.order == :descending ? migration_versions.find_index(struct_version) : nil # run all subsequent version translations # migration_versions.each_with_index do |version, index| next unless !first_index || index >= first_index next unless !last_index || index <= last_index @migrations.translations[version].each(&translate) end # run the first translations if they exist # lasts.each(&translate) if lasts # return hash # struct.hash end
[ "def", "translate", "(", "context", ",", "hash", ")", "raise", "ArgumentError", ".", "new", "(", "'did not pass a hash for the context'", ")", "unless", "context", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ".", "new", "(", "'cannot provide include hash in context'", ")", "if", "context", "[", ":hash", "]", "struct", "=", "StructContext", ".", "new", "(", "context", ",", "hash", ")", "translate", "=", "lambda", "{", "|", "t", "|", "MapMethods", ".", "send", "(", "t", "[", ":name", "]", ",", "struct", ",", "t", "[", ":field", "]", ",", "t", "[", ":block", "]", ")", "}", "struct_version", "=", "struct", ".", "instance_exec", "(", "&", "@migrations", ".", "version", ")", "raise", "StandardError", ".", "new", "(", "'calculated version is not valid'", ")", "unless", "Gem", "::", "Version", ".", "correct?", "(", "struct_version", ")", "migration_versions", "=", "@migrations", ".", "translations", ".", "keys", "migration_versions", ".", "delete", "(", ":first", ")", "migration_versions", ".", "delete", "(", ":last", ")", "firsts", "=", "@migrations", ".", "translations", "[", ":first", "]", "lasts", "=", "@migrations", ".", "translations", "[", ":last", "]", "migration_versions", ".", "sort!", "do", "|", "x", ",", "y", "|", "Gem", "::", "Version", ".", "new", "(", "x", ")", "<=>", "Gem", "::", "Version", ".", "new", "(", "y", ")", "end", "migration_versions", "=", "@migrations", ".", "order", "==", ":descending", "?", "migration_versions", ".", "reverse", ":", "migration_versions", "firsts", ".", "each", "(", "&", "translate", ")", "if", "firsts", "first_index", "=", "@migrations", ".", "order", "==", ":ascending", "?", "migration_versions", ".", "find_index", "(", "struct_version", ")", ":", "nil", "last_index", "=", "@migrations", ".", "order", "==", ":descending", "?", "migration_versions", ".", "find_index", "(", "struct_version", ")", ":", "nil", "migration_versions", ".", "each_with_index", "do", "|", "version", ",", "index", "|", "next", "unless", "!", "first_index", "||", "index", ">=", "first_index", "next", "unless", "!", "last_index", "||", "index", "<=", "last_index", "@migrations", ".", "translations", "[", "version", "]", ".", "each", "(", "&", "translate", ")", "end", "lasts", ".", "each", "(", "&", "translate", ")", "if", "lasts", "struct", ".", "hash", "end" ]
Generates the set of migrations by parsing the passed in block Translates a hash based on defined migrations with a given context and returns the hash. This will modify whatever gets passed in.
[ "Generates", "the", "set", "of", "migrations", "by", "parsing", "the", "passed", "in", "block" ]
5700b61815731f41146248d7e3fe8eca0e647ef3
https://github.com/rtjoseph11/modernizer/blob/5700b61815731f41146248d7e3fe8eca0e647ef3/lib/modernizer.rb#L20-L85
train
stvvan/hoiio-ruby
lib/hoiio-ruby/util/request_util.rb
Hoiio.RequestUtil.check_nil_or_empty
def check_nil_or_empty(required_param_names=[], params) required_param_names.each { |p| if params[p].nil? || params[p].empty? raise Hoiio::RequestError.new "Param " << p << " is missing" end } end
ruby
def check_nil_or_empty(required_param_names=[], params) required_param_names.each { |p| if params[p].nil? || params[p].empty? raise Hoiio::RequestError.new "Param " << p << " is missing" end } end
[ "def", "check_nil_or_empty", "(", "required_param_names", "=", "[", "]", ",", "params", ")", "required_param_names", ".", "each", "{", "|", "p", "|", "if", "params", "[", "p", "]", ".", "nil?", "||", "params", "[", "p", "]", ".", "empty?", "raise", "Hoiio", "::", "RequestError", ".", "new", "\"Param \"", "<<", "p", "<<", "\" is missing\"", "end", "}", "end" ]
Utility methods Check if any required parameter is missing in params hash @param required_param_names array of names of required parameters that need to be checked @param params hash of params that will be used to check the presence of each required_param_name @return Hoiio::InputError if a required param is missing
[ "Utility", "methods", "Check", "if", "any", "required", "parameter", "is", "missing", "in", "params", "hash" ]
7f6840b94c5f61c221619ca069bc008d502dd339
https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/util/request_util.rb#L35-L41
train
stvvan/hoiio-ruby
lib/hoiio-ruby/util/request_util.rb
Hoiio.RequestUtil.check_for_mutual_exclusivity
def check_for_mutual_exclusivity(required_param_names=[], params) i = 0 required_param_names.each { |p| if !params[p].nil? && !params[p].empty? i += 1 end } if i == 0 raise Hoiio::RequestError.new "All required params are missing" elsif i > 1 raise Hoiio::RequestError.new "More than 1 required, mutually exclusive param are present." end end
ruby
def check_for_mutual_exclusivity(required_param_names=[], params) i = 0 required_param_names.each { |p| if !params[p].nil? && !params[p].empty? i += 1 end } if i == 0 raise Hoiio::RequestError.new "All required params are missing" elsif i > 1 raise Hoiio::RequestError.new "More than 1 required, mutually exclusive param are present." end end
[ "def", "check_for_mutual_exclusivity", "(", "required_param_names", "=", "[", "]", ",", "params", ")", "i", "=", "0", "required_param_names", ".", "each", "{", "|", "p", "|", "if", "!", "params", "[", "p", "]", ".", "nil?", "&&", "!", "params", "[", "p", "]", ".", "empty?", "i", "+=", "1", "end", "}", "if", "i", "==", "0", "raise", "Hoiio", "::", "RequestError", ".", "new", "\"All required params are missing\"", "elsif", "i", ">", "1", "raise", "Hoiio", "::", "RequestError", ".", "new", "\"More than 1 required, mutually exclusive param are present.\"", "end", "end" ]
Check that only 1 required parameter is needed for specific API calls @param required_param_names array of names of required parameters that need to be checked @param params hash of params that will be used to check the presence of each required_param_name @return Hoiio::InputError if a required param is missing or if all required params are present
[ "Check", "that", "only", "1", "required", "parameter", "is", "needed", "for", "specific", "API", "calls" ]
7f6840b94c5f61c221619ca069bc008d502dd339
https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/util/request_util.rb#L49-L62
train
dennisvandehoef/easy-html-creator
lib/generator/haml_generator.rb
Generator.Context.render_partial
def render_partial(file_name) # The "default" version of the partial. file_to_render = "#{@input_folder}/partials/#{file_name.to_s}.haml" if @scope # Look for a partial prefixed with the current "scope" (which is just the name of the # primary template being rendered). scope_file = "#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml" # Use it if it's there. file_to_render = scope_file if File.exists? scope_file end # If we found a matching partial (either the scoped one or the default), render it now. if File.exists? file_to_render partial = Haml::Engine.new(File.read(file_to_render), @options) partial.render self else nil end rescue Exception => e raise $!, "#{$!} PARTIAL::#{file_name} ", $!.backtrace end
ruby
def render_partial(file_name) # The "default" version of the partial. file_to_render = "#{@input_folder}/partials/#{file_name.to_s}.haml" if @scope # Look for a partial prefixed with the current "scope" (which is just the name of the # primary template being rendered). scope_file = "#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml" # Use it if it's there. file_to_render = scope_file if File.exists? scope_file end # If we found a matching partial (either the scoped one or the default), render it now. if File.exists? file_to_render partial = Haml::Engine.new(File.read(file_to_render), @options) partial.render self else nil end rescue Exception => e raise $!, "#{$!} PARTIAL::#{file_name} ", $!.backtrace end
[ "def", "render_partial", "(", "file_name", ")", "file_to_render", "=", "\"#{@input_folder}/partials/#{file_name.to_s}.haml\"", "if", "@scope", "scope_file", "=", "\"#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml\"", "file_to_render", "=", "scope_file", "if", "File", ".", "exists?", "scope_file", "end", "if", "File", ".", "exists?", "file_to_render", "partial", "=", "Haml", "::", "Engine", ".", "new", "(", "File", ".", "read", "(", "file_to_render", ")", ",", "@options", ")", "partial", ".", "render", "self", "else", "nil", "end", "rescue", "Exception", "=>", "e", "raise", "$!", ",", "\"#{$!} PARTIAL::#{file_name} \"", ",", "$!", ".", "backtrace", "end" ]
This function is no different from the "copyright_year" function above. It just uses some conventions to render another template file when it's called.
[ "This", "function", "is", "no", "different", "from", "the", "copyright_year", "function", "above", ".", "It", "just", "uses", "some", "conventions", "to", "render", "another", "template", "file", "when", "it", "s", "called", "." ]
54f1e5f2898e6411a0a944359fa959ff2c57cc44
https://github.com/dennisvandehoef/easy-html-creator/blob/54f1e5f2898e6411a0a944359fa959ff2c57cc44/lib/generator/haml_generator.rb#L89-L108
train
henkm/shake-the-counter
lib/shake_the_counter/client.rb
ShakeTheCounter.Client.access_token
def access_token @access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)["access_token"] end
ruby
def access_token @access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)["access_token"] end
[ "def", "access_token", "@access_token", "||=", "ShakeTheCounter", "::", "Authentication", ".", "renew_access_token", "(", "client_id", ":", "id", ",", "client_secret", ":", "secret", ",", "refresh_token", ":", "refresh_token", ")", "[", "\"access_token\"", "]", "end" ]
Retrieves a new authentication token to use for this client or reuse the same one from memory.
[ "Retrieves", "a", "new", "authentication", "token", "to", "use", "for", "this", "client", "or", "reuse", "the", "same", "one", "from", "memory", "." ]
094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e
https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/client.rb#L48-L50
train
henkm/shake-the-counter
lib/shake_the_counter/client.rb
ShakeTheCounter.Client.call
def call(path, http_method: :get, body: {}, header: {}) # add bearer token to header header[:authorization] = "Bearer #{access_token}" return ShakeTheCounter::API.call(path, http_method: http_method, body: body, header: header) end
ruby
def call(path, http_method: :get, body: {}, header: {}) # add bearer token to header header[:authorization] = "Bearer #{access_token}" return ShakeTheCounter::API.call(path, http_method: http_method, body: body, header: header) end
[ "def", "call", "(", "path", ",", "http_method", ":", ":get", ",", "body", ":", "{", "}", ",", "header", ":", "{", "}", ")", "header", "[", ":authorization", "]", "=", "\"Bearer #{access_token}\"", "return", "ShakeTheCounter", "::", "API", ".", "call", "(", "path", ",", "http_method", ":", "http_method", ",", "body", ":", "body", ",", "header", ":", "header", ")", "end" ]
Make an API with access_token
[ "Make", "an", "API", "with", "access_token" ]
094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e
https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/client.rb#L56-L60
train
henkm/shake-the-counter
lib/shake_the_counter/client.rb
ShakeTheCounter.Client.start_payment
def start_payment(reservation_key) path = "reservation/#{reservation_key}/payment" result = call(path, http_method: :post) if result.code.to_i == 200 return true else raise ShakeTheCounterError.new "Payment failed" end end
ruby
def start_payment(reservation_key) path = "reservation/#{reservation_key}/payment" result = call(path, http_method: :post) if result.code.to_i == 200 return true else raise ShakeTheCounterError.new "Payment failed" end end
[ "def", "start_payment", "(", "reservation_key", ")", "path", "=", "\"reservation/#{reservation_key}/payment\"", "result", "=", "call", "(", "path", ",", "http_method", ":", ":post", ")", "if", "result", ".", "code", ".", "to_i", "==", "200", "return", "true", "else", "raise", "ShakeTheCounterError", ".", "new", "\"Payment failed\"", "end", "end" ]
Send a message to STC that a payment has started. @return String status
[ "Send", "a", "message", "to", "STC", "that", "a", "payment", "has", "started", "." ]
094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e
https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/client.rb#L96-L104
train
psusmars/MyJohnDeere-RubyGem
lib/myjohndeere/api_support_item.rb
MyJohnDeere.APISupportItem.to_hash
def to_hash() ret_hash = {} self.class.json_attributes.each do |attrib| ret_hash[attrib] = self.send(attrib.to_s.underscore) end return ret_hash end
ruby
def to_hash() ret_hash = {} self.class.json_attributes.each do |attrib| ret_hash[attrib] = self.send(attrib.to_s.underscore) end return ret_hash end
[ "def", "to_hash", "(", ")", "ret_hash", "=", "{", "}", "self", ".", "class", ".", "json_attributes", ".", "each", "do", "|", "attrib", "|", "ret_hash", "[", "attrib", "]", "=", "self", ".", "send", "(", "attrib", ".", "to_s", ".", "underscore", ")", "end", "return", "ret_hash", "end" ]
see attributes_to_pull_from_json for the order if creating yourself
[ "see", "attributes_to_pull_from_json", "for", "the", "order", "if", "creating", "yourself" ]
0af129dc55f3a93eb61a0cb08a1af550289f4a7e
https://github.com/psusmars/MyJohnDeere-RubyGem/blob/0af129dc55f3a93eb61a0cb08a1af550289f4a7e/lib/myjohndeere/api_support_item.rb#L19-L25
train
akerl/userinput
lib/userinput/prompt.rb
UserInput.Prompt.ask
def ask @fd.print full_message disable_echo if @secret input = _ask return input if valid(input) check_counter ask ensure enable_echo if @secret end
ruby
def ask @fd.print full_message disable_echo if @secret input = _ask return input if valid(input) check_counter ask ensure enable_echo if @secret end
[ "def", "ask", "@fd", ".", "print", "full_message", "disable_echo", "if", "@secret", "input", "=", "_ask", "return", "input", "if", "valid", "(", "input", ")", "check_counter", "ask", "ensure", "enable_echo", "if", "@secret", "end" ]
Build new prompt object and set defaults Request user input
[ "Build", "new", "prompt", "object", "and", "set", "defaults" ]
098d4ac91e91dd6f3f062b45027ef6d10c43476f
https://github.com/akerl/userinput/blob/098d4ac91e91dd6f3f062b45027ef6d10c43476f/lib/userinput/prompt.rb#L21-L32
train
akerl/userinput
lib/userinput/prompt.rb
UserInput.Prompt.valid
def valid(input) return true unless @validation _, method = VALIDATIONS.find { |klass, _| @validation.is_a? klass } return @validation.send(method, input) if method raise "Supported validation type not provided #{@validation.class}" end
ruby
def valid(input) return true unless @validation _, method = VALIDATIONS.find { |klass, _| @validation.is_a? klass } return @validation.send(method, input) if method raise "Supported validation type not provided #{@validation.class}" end
[ "def", "valid", "(", "input", ")", "return", "true", "unless", "@validation", "_", ",", "method", "=", "VALIDATIONS", ".", "find", "{", "|", "klass", ",", "_", "|", "@validation", ".", "is_a?", "klass", "}", "return", "@validation", ".", "send", "(", "method", ",", "input", ")", "if", "method", "raise", "\"Supported validation type not provided #{@validation.class}\"", "end" ]
Validate user input
[ "Validate", "user", "input" ]
098d4ac91e91dd6f3f062b45027ef6d10c43476f
https://github.com/akerl/userinput/blob/098d4ac91e91dd6f3f062b45027ef6d10c43476f/lib/userinput/prompt.rb#L47-L52
train
akerl/userinput
lib/userinput/prompt.rb
UserInput.Prompt._ask
def _ask input = STDIN.gets.chomp input = @default if input.empty? && @default @fd.puts if @secret input end
ruby
def _ask input = STDIN.gets.chomp input = @default if input.empty? && @default @fd.puts if @secret input end
[ "def", "_ask", "input", "=", "STDIN", ".", "gets", ".", "chomp", "input", "=", "@default", "if", "input", ".", "empty?", "&&", "@default", "@fd", ".", "puts", "if", "@secret", "input", "end" ]
Parse user input
[ "Parse", "user", "input" ]
098d4ac91e91dd6f3f062b45027ef6d10c43476f
https://github.com/akerl/userinput/blob/098d4ac91e91dd6f3f062b45027ef6d10c43476f/lib/userinput/prompt.rb#L56-L61
train
drish/hyperb
lib/hyperb/utils.rb
Hyperb.Utils.check_arguments
def check_arguments(params, *args) contains = true args.each do |arg| contains = false unless params.key? arg.to_sym end contains end
ruby
def check_arguments(params, *args) contains = true args.each do |arg| contains = false unless params.key? arg.to_sym end contains end
[ "def", "check_arguments", "(", "params", ",", "*", "args", ")", "contains", "=", "true", "args", ".", "each", "do", "|", "arg", "|", "contains", "=", "false", "unless", "params", ".", "key?", "arg", ".", "to_sym", "end", "contains", "end" ]
checks if all args are keys into the hash @return [Boolean] @param params [Hash] hash to check. @option *args [String] array of strings to check against the hash
[ "checks", "if", "all", "args", "are", "keys", "into", "the", "hash" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/utils.rb#L16-L22
train
drish/hyperb
lib/hyperb/utils.rb
Hyperb.Utils.prepare_json
def prepare_json(params = {}) json = {} params.each do |key, value| value = prepare_json(value) if value.is_a?(Hash) json[camelize(key)] = value end json end
ruby
def prepare_json(params = {}) json = {} params.each do |key, value| value = prepare_json(value) if value.is_a?(Hash) json[camelize(key)] = value end json end
[ "def", "prepare_json", "(", "params", "=", "{", "}", ")", "json", "=", "{", "}", "params", ".", "each", "do", "|", "key", ",", "value", "|", "value", "=", "prepare_json", "(", "value", ")", "if", "value", ".", "is_a?", "(", "Hash", ")", "json", "[", "camelize", "(", "key", ")", "]", "=", "value", "end", "json", "end" ]
prepares all json payloads before sending to hyper input: { foo_bar: 'test' } output: {'FooBar': 'test' }
[ "prepares", "all", "json", "payloads", "before", "sending", "to", "hyper" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/utils.rb#L49-L56
train
void-main/tily.rb
lib/tily/utils/tile_system.rb
Tily.TileSystem.each_tile
def each_tile level size = tile_size level (0...size).each do |y| (0...size).each do |x| yield(x, y) if block_given? end end end
ruby
def each_tile level size = tile_size level (0...size).each do |y| (0...size).each do |x| yield(x, y) if block_given? end end end
[ "def", "each_tile", "level", "size", "=", "tile_size", "level", "(", "0", "...", "size", ")", ".", "each", "do", "|", "y", "|", "(", "0", "...", "size", ")", ".", "each", "do", "|", "x", "|", "yield", "(", "x", ",", "y", ")", "if", "block_given?", "end", "end", "end" ]
Builds the "x, y" pairs, and returns these pairs in block
[ "Builds", "the", "x", "y", "pairs", "and", "returns", "these", "pairs", "in", "block" ]
5ff21e172ef0d62eaea59573aa429522080ae326
https://github.com/void-main/tily.rb/blob/5ff21e172ef0d62eaea59573aa429522080ae326/lib/tily/utils/tile_system.rb#L77-L84
train
void-main/tily.rb
lib/tily/utils/tile_system.rb
Tily.TileSystem.each_tile_with_index
def each_tile_with_index level idx = 0 size = tile_size level (0...size).each do |y| (0...size).each do |x| yield(x, y, idx) if block_given? idx += 1 end end end
ruby
def each_tile_with_index level idx = 0 size = tile_size level (0...size).each do |y| (0...size).each do |x| yield(x, y, idx) if block_given? idx += 1 end end end
[ "def", "each_tile_with_index", "level", "idx", "=", "0", "size", "=", "tile_size", "level", "(", "0", "...", "size", ")", ".", "each", "do", "|", "y", "|", "(", "0", "...", "size", ")", ".", "each", "do", "|", "x", "|", "yield", "(", "x", ",", "y", ",", "idx", ")", "if", "block_given?", "idx", "+=", "1", "end", "end", "end" ]
Builds the "x, y, index" pairs, and returns these pairs in block
[ "Builds", "the", "x", "y", "index", "pairs", "and", "returns", "these", "pairs", "in", "block" ]
5ff21e172ef0d62eaea59573aa429522080ae326
https://github.com/void-main/tily.rb/blob/5ff21e172ef0d62eaea59573aa429522080ae326/lib/tily/utils/tile_system.rb#L87-L96
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.parse
def parse(message) @result = {} @scanner = StringScanner.new(message.strip) begin lines rescue ParserError => pe error_msg = "SimplePoParser::ParserError" error_msg += pe.message error_msg += "\nParseing result before error: '#{@result}'" error_msg += "\nSimplePoParser filtered backtrace: SimplePoParser::ParserError" backtrace = "#{pe.backtrace.select{|i| i =~ /lib\/simple_po_parser/}.join("\n\tfrom ")}" raise ParserError, error_msg, backtrace end @result end
ruby
def parse(message) @result = {} @scanner = StringScanner.new(message.strip) begin lines rescue ParserError => pe error_msg = "SimplePoParser::ParserError" error_msg += pe.message error_msg += "\nParseing result before error: '#{@result}'" error_msg += "\nSimplePoParser filtered backtrace: SimplePoParser::ParserError" backtrace = "#{pe.backtrace.select{|i| i =~ /lib\/simple_po_parser/}.join("\n\tfrom ")}" raise ParserError, error_msg, backtrace end @result end
[ "def", "parse", "(", "message", ")", "@result", "=", "{", "}", "@scanner", "=", "StringScanner", ".", "new", "(", "message", ".", "strip", ")", "begin", "lines", "rescue", "ParserError", "=>", "pe", "error_msg", "=", "\"SimplePoParser::ParserError\"", "error_msg", "+=", "pe", ".", "message", "error_msg", "+=", "\"\\nParseing result before error: '#{@result}'\"", "error_msg", "+=", "\"\\nSimplePoParser filtered backtrace: SimplePoParser::ParserError\"", "backtrace", "=", "\"#{pe.backtrace.select{|i| i =~ /lib\\/simple_po_parser/}.join(\"\\n\\tfrom \")}\"", "raise", "ParserError", ",", "error_msg", ",", "backtrace", "end", "@result", "end" ]
parse a single message of the PO format. @param message a single PO message in String format without leading or trailing whitespace @return [Hash] parsed PO message information in Hash format
[ "parse", "a", "single", "message", "of", "the", "PO", "format", "." ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L21-L35
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.msgctxt
def msgctxt begin if @scanner.scan(/msgctxt/) skip_whitespace text = message_line add_result(:msgctxt, text) message_multiline(:msgctxt) if text.empty? end msgid rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgctxt\n" + pe.message, pe.backtrace end end
ruby
def msgctxt begin if @scanner.scan(/msgctxt/) skip_whitespace text = message_line add_result(:msgctxt, text) message_multiline(:msgctxt) if text.empty? end msgid rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgctxt\n" + pe.message, pe.backtrace end end
[ "def", "msgctxt", "begin", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "skip_whitespace", "text", "=", "message_line", "add_result", "(", ":msgctxt", ",", "text", ")", "message_multiline", "(", ":msgctxt", ")", "if", "text", ".", "empty?", "end", "msgid", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in msgctxt\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
matches the msgctxt line and will continue to check for msgid afterwards msgctxt is optional
[ "matches", "the", "msgctxt", "line", "and", "will", "continue", "to", "check", "for", "msgid", "afterwards" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L106-L118
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.msgid
def msgid begin if @scanner.scan(/msgid/) skip_whitespace text = message_line add_result(:msgid, text) message_multiline(:msgid) if text.empty? if msgid_plural msgstr_plural else msgstr end else err_msg = "Message without msgid is not allowed." err_msg += "The Line started unexpectedly with #{@scanner.peek(10).inspect}." raise PoSyntaxError, err_msg end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace end end
ruby
def msgid begin if @scanner.scan(/msgid/) skip_whitespace text = message_line add_result(:msgid, text) message_multiline(:msgid) if text.empty? if msgid_plural msgstr_plural else msgstr end else err_msg = "Message without msgid is not allowed." err_msg += "The Line started unexpectedly with #{@scanner.peek(10).inspect}." raise PoSyntaxError, err_msg end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace end end
[ "def", "msgid", "begin", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "skip_whitespace", "text", "=", "message_line", "add_result", "(", ":msgid", ",", "text", ")", "message_multiline", "(", ":msgid", ")", "if", "text", ".", "empty?", "if", "msgid_plural", "msgstr_plural", "else", "msgstr", "end", "else", "err_msg", "=", "\"Message without msgid is not allowed.\"", "err_msg", "+=", "\"The Line started unexpectedly with #{@scanner.peek(10).inspect}.\"", "raise", "PoSyntaxError", ",", "err_msg", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in msgid\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
matches the msgid line. Will check for optional msgid_plural. Will advance to msgstr or msgstr_plural based on msgid_plural msgid is required
[ "matches", "the", "msgid", "line", ".", "Will", "check", "for", "optional", "msgid_plural", ".", "Will", "advance", "to", "msgstr", "or", "msgstr_plural", "based", "on", "msgid_plural" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L124-L145
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.msgid_plural
def msgid_plural begin if @scanner.scan(/msgid_plural/) skip_whitespace text = message_line add_result(:msgid_plural, text) message_multiline(:msgid_plural) if text.empty? true else false end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace end end
ruby
def msgid_plural begin if @scanner.scan(/msgid_plural/) skip_whitespace text = message_line add_result(:msgid_plural, text) message_multiline(:msgid_plural) if text.empty? true else false end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgid\n" + pe.message, pe.backtrace end end
[ "def", "msgid_plural", "begin", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "skip_whitespace", "text", "=", "message_line", "add_result", "(", ":msgid_plural", ",", "text", ")", "message_multiline", "(", ":msgid_plural", ")", "if", "text", ".", "empty?", "true", "else", "false", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in msgid\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
matches the msgid_plural line. msgid_plural is optional @return [boolean] true if msgid_plural is present, false otherwise
[ "matches", "the", "msgid_plural", "line", "." ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L152-L166
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.msgstr
def msgstr begin if @scanner.scan(/msgstr/) skip_whitespace text = message_line add_result(:msgstr, text) message_multiline(:msgstr) if text.empty? skip_whitespace raise PoSyntaxError, "Unexpected content after expected message end #{@scanner.peek(10).inspect}" unless @scanner.eos? else raise PoSyntaxError, "Singular message without msgstr is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}." end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgstr\n" + pe.message, pe.backtrace end end
ruby
def msgstr begin if @scanner.scan(/msgstr/) skip_whitespace text = message_line add_result(:msgstr, text) message_multiline(:msgstr) if text.empty? skip_whitespace raise PoSyntaxError, "Unexpected content after expected message end #{@scanner.peek(10).inspect}" unless @scanner.eos? else raise PoSyntaxError, "Singular message without msgstr is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}." end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgstr\n" + pe.message, pe.backtrace end end
[ "def", "msgstr", "begin", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "skip_whitespace", "text", "=", "message_line", "add_result", "(", ":msgstr", ",", "text", ")", "message_multiline", "(", ":msgstr", ")", "if", "text", ".", "empty?", "skip_whitespace", "raise", "PoSyntaxError", ",", "\"Unexpected content after expected message end #{@scanner.peek(10).inspect}\"", "unless", "@scanner", ".", "eos?", "else", "raise", "PoSyntaxError", ",", "\"Singular message without msgstr is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}.\"", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in msgstr\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
parses the msgstr singular line msgstr is required in singular translations
[ "parses", "the", "msgstr", "singular", "line" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L171-L186
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.msgstr_plural
def msgstr_plural(num = 0) begin msgstr_key = @scanner.scan(/msgstr\[\d\]/) # matches 'msgstr[0]' to 'msgstr[9]' if msgstr_key # msgstr plurals must come in 0-based index in order msgstr_num = msgstr_key.match(/\d/)[0].to_i raise PoSyntaxError, "Bad 'msgstr[index]' index." if msgstr_num != num skip_whitespace text = message_line add_result(msgstr_key, text) message_multiline(msgstr_key) if text.empty? msgstr_plural(num+1) elsif num == 0 # and msgstr_key was false raise PoSyntaxError, "Plural message without msgstr[0] is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}." else raise PoSyntaxError, "End of message was expected, but line started unexpectedly with #{@scanner.peek(10).inspect}" unless @scanner.eos? end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgstr_plural\n" + pe.message, pe.backtrace end end
ruby
def msgstr_plural(num = 0) begin msgstr_key = @scanner.scan(/msgstr\[\d\]/) # matches 'msgstr[0]' to 'msgstr[9]' if msgstr_key # msgstr plurals must come in 0-based index in order msgstr_num = msgstr_key.match(/\d/)[0].to_i raise PoSyntaxError, "Bad 'msgstr[index]' index." if msgstr_num != num skip_whitespace text = message_line add_result(msgstr_key, text) message_multiline(msgstr_key) if text.empty? msgstr_plural(num+1) elsif num == 0 # and msgstr_key was false raise PoSyntaxError, "Plural message without msgstr[0] is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}." else raise PoSyntaxError, "End of message was expected, but line started unexpectedly with #{@scanner.peek(10).inspect}" unless @scanner.eos? end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in msgstr_plural\n" + pe.message, pe.backtrace end end
[ "def", "msgstr_plural", "(", "num", "=", "0", ")", "begin", "msgstr_key", "=", "@scanner", ".", "scan", "(", "/", "\\[", "\\d", "\\]", "/", ")", "if", "msgstr_key", "msgstr_num", "=", "msgstr_key", ".", "match", "(", "/", "\\d", "/", ")", "[", "0", "]", ".", "to_i", "raise", "PoSyntaxError", ",", "\"Bad 'msgstr[index]' index.\"", "if", "msgstr_num", "!=", "num", "skip_whitespace", "text", "=", "message_line", "add_result", "(", "msgstr_key", ",", "text", ")", "message_multiline", "(", "msgstr_key", ")", "if", "text", ".", "empty?", "msgstr_plural", "(", "num", "+", "1", ")", "elsif", "num", "==", "0", "raise", "PoSyntaxError", ",", "\"Plural message without msgstr[0] is not allowed. Line started unexpectedly with #{@scanner.peek(10).inspect}.\"", "else", "raise", "PoSyntaxError", ",", "\"End of message was expected, but line started unexpectedly with #{@scanner.peek(10).inspect}\"", "unless", "@scanner", ".", "eos?", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in msgstr_plural\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
parses the msgstr plural lines msgstr plural lines are used when there is msgid_plural. They have the format msgstr[N] where N is incremental number starting from zero representing the plural number as specified in the headers "Plural-Forms" entry. Most languages, like the English language only have two plural forms (singular and plural), but there are languages with more plurals
[ "parses", "the", "msgstr", "plural", "lines" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L195-L215
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.previous_comments
def previous_comments begin # next part must be msgctxt, msgid or msgid_plural if @scanner.scan(/msg/) if @scanner.scan(/id/) if @scanner.scan(/_plural/) key = :previous_msgid_plural else key = :previous_msgid end elsif @scanner.scan(/ctxt/) key = :previous_msgctxt else raise PoSyntaxError, "Previous comment type #{("msg" + @scanner.peek(10)).inspect} unknown." end skip_whitespace text = message_line add_result(key, text) previous_multiline(key) if text.empty? else raise PoSyntaxError, "Previous comments must start with '#| msg'. #{@scanner.peek(10).inspect} unknown." end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in previous_comments\n" + pe.message, pe.backtrace end end
ruby
def previous_comments begin # next part must be msgctxt, msgid or msgid_plural if @scanner.scan(/msg/) if @scanner.scan(/id/) if @scanner.scan(/_plural/) key = :previous_msgid_plural else key = :previous_msgid end elsif @scanner.scan(/ctxt/) key = :previous_msgctxt else raise PoSyntaxError, "Previous comment type #{("msg" + @scanner.peek(10)).inspect} unknown." end skip_whitespace text = message_line add_result(key, text) previous_multiline(key) if text.empty? else raise PoSyntaxError, "Previous comments must start with '#| msg'. #{@scanner.peek(10).inspect} unknown." end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in previous_comments\n" + pe.message, pe.backtrace end end
[ "def", "previous_comments", "begin", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "key", "=", ":previous_msgid_plural", "else", "key", "=", ":previous_msgid", "end", "elsif", "@scanner", ".", "scan", "(", "/", "/", ")", "key", "=", ":previous_msgctxt", "else", "raise", "PoSyntaxError", ",", "\"Previous comment type #{(\"msg\" + @scanner.peek(10)).inspect} unknown.\"", "end", "skip_whitespace", "text", "=", "message_line", "add_result", "(", "key", ",", "text", ")", "previous_multiline", "(", "key", ")", "if", "text", ".", "empty?", "else", "raise", "PoSyntaxError", ",", "\"Previous comments must start with '#| msg'. #{@scanner.peek(10).inspect} unknown.\"", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in previous_comments\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
parses previous comments, which provide additional information on fuzzy matching previous comments are: * #| msgctxt * #| msgid * #| msgid_plural
[ "parses", "previous", "comments", "which", "provide", "additional", "information", "on", "fuzzy", "matching" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L223-L248
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.previous_multiline
def previous_multiline(key) begin # scan multilines until no further multiline is hit # /#\|\p{Blank}"/ needs to catch the double quote to ensure it hits a previous # multiline and not another line type. if @scanner.scan(/#\|\p{Blank}*"/) @scanner.pos = @scanner.pos - 1 # go one character back, so we can reuse the "message line" method add_result(key, message_line) previous_multiline(key) # go on until we no longer hit a multiline line end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in previous_multiline\n" + pe.message, pe.backtrace end end
ruby
def previous_multiline(key) begin # scan multilines until no further multiline is hit # /#\|\p{Blank}"/ needs to catch the double quote to ensure it hits a previous # multiline and not another line type. if @scanner.scan(/#\|\p{Blank}*"/) @scanner.pos = @scanner.pos - 1 # go one character back, so we can reuse the "message line" method add_result(key, message_line) previous_multiline(key) # go on until we no longer hit a multiline line end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in previous_multiline\n" + pe.message, pe.backtrace end end
[ "def", "previous_multiline", "(", "key", ")", "begin", "if", "@scanner", ".", "scan", "(", "/", "\\|", "\\p", "/", ")", "@scanner", ".", "pos", "=", "@scanner", ".", "pos", "-", "1", "add_result", "(", "key", ",", "message_line", ")", "previous_multiline", "(", "key", ")", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in previous_multiline\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
parses the multiline messages of the previous comment lines
[ "parses", "the", "multiline", "messages", "of", "the", "previous", "comment", "lines" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L251-L264
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.message_multiline
def message_multiline(key) begin skip_whitespace if @scanner.check(/"/) add_result(key, message_line) message_multiline(key) end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in message_multiline with key '#{key}'\n" + pe.message, pe.backtrace end end
ruby
def message_multiline(key) begin skip_whitespace if @scanner.check(/"/) add_result(key, message_line) message_multiline(key) end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in message_multiline with key '#{key}'\n" + pe.message, pe.backtrace end end
[ "def", "message_multiline", "(", "key", ")", "begin", "skip_whitespace", "if", "@scanner", ".", "check", "(", "/", "/", ")", "add_result", "(", "key", ",", "message_line", ")", "message_multiline", "(", "key", ")", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in message_multiline with key '#{key}'\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
parses a multiline message multiline messages are indicated by an empty content as first line and the next line starting with the double quote character
[ "parses", "a", "multiline", "message" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L270-L280
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.message_line
def message_line begin if @scanner.getch == '"' text = message_text unless @scanner.getch == '"' err_msg = "The message text '#{text}' must be finished with the double quote character '\"'." raise PoSyntaxError, err_msg end skip_whitespace unless end_of_line err_msg = "There should be only whitespace until the end of line" err_msg += " after the double quote character of a message text." raise PoSyntaxError.new(err_msg) end text else @scanner.pos = @scanner.pos - 1 err_msg = "A message text needs to start with the double quote character '\"'," err_msg += " but this was found: #{@scanner.peek(10).inspect}" raise PoSyntaxError, err_msg end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in message_line\n" + pe.message, pe.backtrace end end
ruby
def message_line begin if @scanner.getch == '"' text = message_text unless @scanner.getch == '"' err_msg = "The message text '#{text}' must be finished with the double quote character '\"'." raise PoSyntaxError, err_msg end skip_whitespace unless end_of_line err_msg = "There should be only whitespace until the end of line" err_msg += " after the double quote character of a message text." raise PoSyntaxError.new(err_msg) end text else @scanner.pos = @scanner.pos - 1 err_msg = "A message text needs to start with the double quote character '\"'," err_msg += " but this was found: #{@scanner.peek(10).inspect}" raise PoSyntaxError, err_msg end rescue PoSyntaxError => pe raise PoSyntaxError, "Syntax error in message_line\n" + pe.message, pe.backtrace end end
[ "def", "message_line", "begin", "if", "@scanner", ".", "getch", "==", "'\"'", "text", "=", "message_text", "unless", "@scanner", ".", "getch", "==", "'\"'", "err_msg", "=", "\"The message text '#{text}' must be finished with the double quote character '\\\"'.\"", "raise", "PoSyntaxError", ",", "err_msg", "end", "skip_whitespace", "unless", "end_of_line", "err_msg", "=", "\"There should be only whitespace until the end of line\"", "err_msg", "+=", "\" after the double quote character of a message text.\"", "raise", "PoSyntaxError", ".", "new", "(", "err_msg", ")", "end", "text", "else", "@scanner", ".", "pos", "=", "@scanner", ".", "pos", "-", "1", "err_msg", "=", "\"A message text needs to start with the double quote character '\\\"',\"", "err_msg", "+=", "\" but this was found: #{@scanner.peek(10).inspect}\"", "raise", "PoSyntaxError", ",", "err_msg", "end", "rescue", "PoSyntaxError", "=>", "pe", "raise", "PoSyntaxError", ",", "\"Syntax error in message_line\\n\"", "+", "pe", ".", "message", ",", "pe", ".", "backtrace", "end", "end" ]
identifies a message line and returns it's text or raises an error @return [String] message_text
[ "identifies", "a", "message", "line", "and", "returns", "it", "s", "text", "or", "raises", "an", "error" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L285-L309
train
experteer/simple_po_parser
lib/simple_po_parser/parser.rb
SimplePoParser.Parser.add_result
def add_result(key, text) if @result[key] if @result[key].is_a? Array @result[key].push(text) else @result[key] = [@result[key], text] end else @result[key] = text end end
ruby
def add_result(key, text) if @result[key] if @result[key].is_a? Array @result[key].push(text) else @result[key] = [@result[key], text] end else @result[key] = text end end
[ "def", "add_result", "(", "key", ",", "text", ")", "if", "@result", "[", "key", "]", "if", "@result", "[", "key", "]", ".", "is_a?", "Array", "@result", "[", "key", "]", ".", "push", "(", "text", ")", "else", "@result", "[", "key", "]", "=", "[", "@result", "[", "key", "]", ",", "text", "]", "end", "else", "@result", "[", "key", "]", "=", "text", "end", "end" ]
adds text to the given key in results creates an array if the given key already has a result
[ "adds", "text", "to", "the", "given", "key", "in", "results", "creates", "an", "array", "if", "the", "given", "key", "already", "has", "a", "result" ]
b0ab9f76a12273b13869fd7f44231253d116ee8a
https://github.com/experteer/simple_po_parser/blob/b0ab9f76a12273b13869fd7f44231253d116ee8a/lib/simple_po_parser/parser.rb#L364-L374
train
social-snippet/social-snippet
lib/social_snippet/resolvers/base_resolver.rb
SocialSnippet.Resolvers::BaseResolver.resolve_tag_repo_ref!
def resolve_tag_repo_ref!(tag) return unless tag.has_repo? repo = core.repo_manager.find_repository(tag.repo) # set latest version if tag.has_ref? === false if repo.has_package_versions? tag.set_ref repo.latest_package_version else tag.set_ref repo.current_ref end else unless repo.has_ref?(tag.ref) new_ref = repo.latest_version(tag.ref) raise "error" if new_ref.nil? tag.set_ref new_ref end end end
ruby
def resolve_tag_repo_ref!(tag) return unless tag.has_repo? repo = core.repo_manager.find_repository(tag.repo) # set latest version if tag.has_ref? === false if repo.has_package_versions? tag.set_ref repo.latest_package_version else tag.set_ref repo.current_ref end else unless repo.has_ref?(tag.ref) new_ref = repo.latest_version(tag.ref) raise "error" if new_ref.nil? tag.set_ref new_ref end end end
[ "def", "resolve_tag_repo_ref!", "(", "tag", ")", "return", "unless", "tag", ".", "has_repo?", "repo", "=", "core", ".", "repo_manager", ".", "find_repository", "(", "tag", ".", "repo", ")", "if", "tag", ".", "has_ref?", "===", "false", "if", "repo", ".", "has_package_versions?", "tag", ".", "set_ref", "repo", ".", "latest_package_version", "else", "tag", ".", "set_ref", "repo", ".", "current_ref", "end", "else", "unless", "repo", ".", "has_ref?", "(", "tag", ".", "ref", ")", "new_ref", "=", "repo", ".", "latest_version", "(", "tag", ".", "ref", ")", "raise", "\"error\"", "if", "new_ref", ".", "nil?", "tag", ".", "set_ref", "new_ref", "end", "end", "end" ]
Resolve tag's ref
[ "Resolve", "tag", "s", "ref" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/base_resolver.rb#L77-L94
train
featureflow/featureflow-ruby-sdk
lib/featureflow/events_client.rb
Featureflow.EventsClient.register_features
def register_features(with_features) Thread.new do features = [] features = with_features.each do | feature | features.push(key: feature[:key], variants: feature[:variants], failoverVariant: feature[:failover_variant]) end send_event 'Register Features', :put, '/api/sdk/v1/register', features end end
ruby
def register_features(with_features) Thread.new do features = [] features = with_features.each do | feature | features.push(key: feature[:key], variants: feature[:variants], failoverVariant: feature[:failover_variant]) end send_event 'Register Features', :put, '/api/sdk/v1/register', features end end
[ "def", "register_features", "(", "with_features", ")", "Thread", ".", "new", "do", "features", "=", "[", "]", "features", "=", "with_features", ".", "each", "do", "|", "feature", "|", "features", ".", "push", "(", "key", ":", "feature", "[", ":key", "]", ",", "variants", ":", "feature", "[", ":variants", "]", ",", "failoverVariant", ":", "feature", "[", ":failover_variant", "]", ")", "end", "send_event", "'Register Features'", ",", ":put", ",", "'/api/sdk/v1/register'", ",", "features", "end", "end" ]
register features are not queued and go straight out
[ "register", "features", "are", "not", "queued", "and", "go", "straight", "out" ]
ec3c1304a62b66711f633753fad4c21137460a03
https://github.com/featureflow/featureflow-ruby-sdk/blob/ec3c1304a62b66711f633753fad4c21137460a03/lib/featureflow/events_client.rb#L29-L39
train
gareth/ruby_hid_api
lib/hid_api/device_info.rb
HidApi.DeviceInfo.each
def each return enum_for(:each) unless block_given? pointer = self loop do break if pointer.null? yield pointer pointer = pointer.next end end
ruby
def each return enum_for(:each) unless block_given? pointer = self loop do break if pointer.null? yield pointer pointer = pointer.next end end
[ "def", "each", "return", "enum_for", "(", ":each", ")", "unless", "block_given?", "pointer", "=", "self", "loop", "do", "break", "if", "pointer", ".", "null?", "yield", "pointer", "pointer", "=", "pointer", ".", "next", "end", "end" ]
Exposes the linked list structure in an Enumerable-compatible format
[ "Exposes", "the", "linked", "list", "structure", "in", "an", "Enumerable", "-", "compatible", "format" ]
dff5eb6e649f50e634b7a3acc83dc4828e514fe6
https://github.com/gareth/ruby_hid_api/blob/dff5eb6e649f50e634b7a3acc83dc4828e514fe6/lib/hid_api/device_info.rb#L44-L53
train
probedock/probedock-cucumber-ruby
lib/probe_dock_cucumber/formatter.rb
ProbeDockCucumber.Formatter.comment_line
def comment_line(comment) # Take care of annotation only if matched if comment.match(ProbeDockProbe::Annotation::ANNOTATION_REGEXP) # If the feature already started, the annotations are for scenarios if @current_feature_started @annotation = ProbeDockProbe::Annotation.new(comment) else @feature_annotation = ProbeDockProbe::Annotation.new(comment) end end end
ruby
def comment_line(comment) # Take care of annotation only if matched if comment.match(ProbeDockProbe::Annotation::ANNOTATION_REGEXP) # If the feature already started, the annotations are for scenarios if @current_feature_started @annotation = ProbeDockProbe::Annotation.new(comment) else @feature_annotation = ProbeDockProbe::Annotation.new(comment) end end end
[ "def", "comment_line", "(", "comment", ")", "if", "comment", ".", "match", "(", "ProbeDockProbe", "::", "Annotation", "::", "ANNOTATION_REGEXP", ")", "if", "@current_feature_started", "@annotation", "=", "ProbeDockProbe", "::", "Annotation", ".", "new", "(", "comment", ")", "else", "@feature_annotation", "=", "ProbeDockProbe", "::", "Annotation", ".", "new", "(", "comment", ")", "end", "end", "end" ]
Called for each comment line
[ "Called", "for", "each", "comment", "line" ]
9554da1a565c354b50994d0bfd567915adc3c108
https://github.com/probedock/probedock-cucumber-ruby/blob/9554da1a565c354b50994d0bfd567915adc3c108/lib/probe_dock_cucumber/formatter.rb#L100-L110
train
smileart/network_utils
lib/network_utils/url_info.rb
NetworkUtils.UrlInfo.is?
def is?(type) return false if type.to_s.empty? expected_types = Array.wrap(type).map(&:to_s) content_type && expected_types.select do |t| content_type.select { |ct| ct.start_with?(t) } end.any? end
ruby
def is?(type) return false if type.to_s.empty? expected_types = Array.wrap(type).map(&:to_s) content_type && expected_types.select do |t| content_type.select { |ct| ct.start_with?(t) } end.any? end
[ "def", "is?", "(", "type", ")", "return", "false", "if", "type", ".", "to_s", ".", "empty?", "expected_types", "=", "Array", ".", "wrap", "(", "type", ")", ".", "map", "(", "&", ":to_s", ")", "content_type", "&&", "expected_types", ".", "select", "do", "|", "t", "|", "content_type", ".", "select", "{", "|", "ct", "|", "ct", ".", "start_with?", "(", "t", ")", "}", "end", ".", "any?", "end" ]
Initialise a UrlInfo for a particular URL @param [String] url the URL you want to get info about @param [Integer] request_timeout Max time to wait for headers from the server Check the Content-Type of the resource @param [String, Symbol, Array] type the prefix (before "/") or full Content-Type content @return [Boolean] true if Content-Type matches something from the types list
[ "Initialise", "a", "UrlInfo", "for", "a", "particular", "URL" ]
3a4a8b58f9898d9bacf168ed45721db2e52abf9b
https://github.com/smileart/network_utils/blob/3a4a8b58f9898d9bacf168ed45721db2e52abf9b/lib/network_utils/url_info.rb#L32-L39
train
raskhadafi/vesr
lib/vesr/prawn/esr_recipe.rb
Prawn.EsrRecipe.esr9_format_account_id
def esr9_format_account_id(account_id) (pre, main, post) = account_id.split('-') sprintf('%02i%06i%1i', pre.to_i, main.to_i, post.to_i) end
ruby
def esr9_format_account_id(account_id) (pre, main, post) = account_id.split('-') sprintf('%02i%06i%1i', pre.to_i, main.to_i, post.to_i) end
[ "def", "esr9_format_account_id", "(", "account_id", ")", "(", "pre", ",", "main", ",", "post", ")", "=", "account_id", ".", "split", "(", "'-'", ")", "sprintf", "(", "'%02i%06i%1i'", ",", "pre", ".", "to_i", ",", "main", ".", "to_i", ",", "post", ".", "to_i", ")", "end" ]
Formats an account number for ESR Account numbers for ESR should have the following format: XXYYYYYYZ, where the number of digits is fixed. We support providing the number in the format XX-YYYY-Z which is more common in written communication.
[ "Formats", "an", "account", "number", "for", "ESR" ]
303d250355ef725bd5b384f9390949620652a3e2
https://github.com/raskhadafi/vesr/blob/303d250355ef725bd5b384f9390949620652a3e2/lib/vesr/prawn/esr_recipe.rb#L143-L147
train
IUBLibTech/ldap_groups_lookup
lib/ldap_groups_lookup/configuration.rb
LDAPGroupsLookup.Configuration.config
def config if @config.nil? if defined? Rails configure(Rails.root.join('config', 'ldap_groups_lookup.yml').to_s) else configure(File.join(__dir__, '..', '..', 'config', 'ldap_groups_lookup.yml').to_s) end end @config end
ruby
def config if @config.nil? if defined? Rails configure(Rails.root.join('config', 'ldap_groups_lookup.yml').to_s) else configure(File.join(__dir__, '..', '..', 'config', 'ldap_groups_lookup.yml').to_s) end end @config end
[ "def", "config", "if", "@config", ".", "nil?", "if", "defined?", "Rails", "configure", "(", "Rails", ".", "root", ".", "join", "(", "'config'", ",", "'ldap_groups_lookup.yml'", ")", ".", "to_s", ")", "else", "configure", "(", "File", ".", "join", "(", "__dir__", ",", "'..'", ",", "'..'", ",", "'config'", ",", "'ldap_groups_lookup.yml'", ")", ".", "to_s", ")", "end", "end", "@config", "end" ]
Loads LDAP host and authentication configuration
[ "Loads", "LDAP", "host", "and", "authentication", "configuration" ]
430ff8e1dd084fdc7113fbfe85b6422900b39184
https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/configuration.rb#L19-L28
train
desktoppr/cached_counts
lib/cached_counts/cache.rb
CachedCounts.Cache.clear
def clear invalid_keys = all_keys.select { |key| key.include?(@scope.table_name.downcase) } invalid_keys.each { |key| Rails.cache.delete(key) } Rails.cache.write(list_key, all_keys - invalid_keys) end
ruby
def clear invalid_keys = all_keys.select { |key| key.include?(@scope.table_name.downcase) } invalid_keys.each { |key| Rails.cache.delete(key) } Rails.cache.write(list_key, all_keys - invalid_keys) end
[ "def", "clear", "invalid_keys", "=", "all_keys", ".", "select", "{", "|", "key", "|", "key", ".", "include?", "(", "@scope", ".", "table_name", ".", "downcase", ")", "}", "invalid_keys", ".", "each", "{", "|", "key", "|", "Rails", ".", "cache", ".", "delete", "(", "key", ")", "}", "Rails", ".", "cache", ".", "write", "(", "list_key", ",", "all_keys", "-", "invalid_keys", ")", "end" ]
Clear out any count caches which have SQL that includes the scopes table
[ "Clear", "out", "any", "count", "caches", "which", "have", "SQL", "that", "includes", "the", "scopes", "table" ]
e859d1b4b0751a9dd76d3d213d79004c1efa0bc2
https://github.com/desktoppr/cached_counts/blob/e859d1b4b0751a9dd76d3d213d79004c1efa0bc2/lib/cached_counts/cache.rb#L14-L19
train
tbpgr/qiita_scouter
lib/qiita_scouter_core.rb
QiitaScouter.Core.analyze
def analyze(target_user) user = read_user(target_user) articles = read_articles(target_user) calc_power_levels(user, articles) end
ruby
def analyze(target_user) user = read_user(target_user) articles = read_articles(target_user) calc_power_levels(user, articles) end
[ "def", "analyze", "(", "target_user", ")", "user", "=", "read_user", "(", "target_user", ")", "articles", "=", "read_articles", "(", "target_user", ")", "calc_power_levels", "(", "user", ",", "articles", ")", "end" ]
Generate QiitaScouter markdown file.
[ "Generate", "QiitaScouter", "markdown", "file", "." ]
55a0504d292dabb27c8c75be2669c48adcfc2cbe
https://github.com/tbpgr/qiita_scouter/blob/55a0504d292dabb27c8c75be2669c48adcfc2cbe/lib/qiita_scouter_core.rb#L13-L17
train
JavonDavis/parallel_appium
lib/parallel_appium/ios.rb
ParallelAppium.IOS.simulator_information
def simulator_information re = /\([0-9]+\.[0-9](\.[0-9])?\) \[[0-9A-Z-]+\]/m # Filter out simulator info for iPhone platform version and udid @simulators.select { |simulator_data| simulator_data.include?('iPhone') && !simulator_data.include?('Apple Watch') } .map { |simulator_data| simulator_data.match(re).to_s.tr('()[]', '').split }[0, ENV['THREADS'].to_i] end
ruby
def simulator_information re = /\([0-9]+\.[0-9](\.[0-9])?\) \[[0-9A-Z-]+\]/m # Filter out simulator info for iPhone platform version and udid @simulators.select { |simulator_data| simulator_data.include?('iPhone') && !simulator_data.include?('Apple Watch') } .map { |simulator_data| simulator_data.match(re).to_s.tr('()[]', '').split }[0, ENV['THREADS'].to_i] end
[ "def", "simulator_information", "re", "=", "/", "\\(", "\\.", "\\.", "\\)", "\\[", "\\]", "/m", "@simulators", ".", "select", "{", "|", "simulator_data", "|", "simulator_data", ".", "include?", "(", "'iPhone'", ")", "&&", "!", "simulator_data", ".", "include?", "(", "'Apple Watch'", ")", "}", ".", "map", "{", "|", "simulator_data", "|", "simulator_data", ".", "match", "(", "re", ")", ".", "to_s", ".", "tr", "(", "'()[]'", ",", "''", ")", ".", "split", "}", "[", "0", ",", "ENV", "[", "'THREADS'", "]", ".", "to_i", "]", "end" ]
Filter simulator data
[ "Filter", "simulator", "data" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/ios.rb#L11-L17
train
mpalmer/frankenstein
lib/frankenstein/request.rb
Frankenstein.Request.measure
def measure(labels = {}) start_time = Time.now unless block_given? raise NoBlockError, "No block passed to #{self.class}#measure" end @requests.increment(labels, 1) @mutex.synchronize { @current.set(labels, (@current.get(labels) || 0) + 1) } res_labels = labels.dup begin yield(res_labels).tap do elapsed_time = Time.now - start_time @durations.observe(res_labels, elapsed_time) end rescue Exception => ex @exceptions.increment(labels.merge(class: ex.class.to_s), 1) raise ensure @mutex.synchronize { @current.set(labels, @current.get(labels) - 1) } end end
ruby
def measure(labels = {}) start_time = Time.now unless block_given? raise NoBlockError, "No block passed to #{self.class}#measure" end @requests.increment(labels, 1) @mutex.synchronize { @current.set(labels, (@current.get(labels) || 0) + 1) } res_labels = labels.dup begin yield(res_labels).tap do elapsed_time = Time.now - start_time @durations.observe(res_labels, elapsed_time) end rescue Exception => ex @exceptions.increment(labels.merge(class: ex.class.to_s), 1) raise ensure @mutex.synchronize { @current.set(labels, @current.get(labels) - 1) } end end
[ "def", "measure", "(", "labels", "=", "{", "}", ")", "start_time", "=", "Time", ".", "now", "unless", "block_given?", "raise", "NoBlockError", ",", "\"No block passed to #{self.class}#measure\"", "end", "@requests", ".", "increment", "(", "labels", ",", "1", ")", "@mutex", ".", "synchronize", "{", "@current", ".", "set", "(", "labels", ",", "(", "@current", ".", "get", "(", "labels", ")", "||", "0", ")", "+", "1", ")", "}", "res_labels", "=", "labels", ".", "dup", "begin", "yield", "(", "res_labels", ")", ".", "tap", "do", "elapsed_time", "=", "Time", ".", "now", "-", "start_time", "@durations", ".", "observe", "(", "res_labels", ",", "elapsed_time", ")", "end", "rescue", "Exception", "=>", "ex", "@exceptions", ".", "increment", "(", "labels", ".", "merge", "(", "class", ":", "ex", ".", "class", ".", "to_s", ")", ",", "1", ")", "raise", "ensure", "@mutex", ".", "synchronize", "{", "@current", ".", "set", "(", "labels", ",", "@current", ".", "get", "(", "labels", ")", "-", "1", ")", "}", "end", "end" ]
Create a new request instrumentation package. A "request", for the purposes of this discussion, is a distinct interaction with an external system, typically either the receipt of some sort of communication from another system which needs a response by this system (the one being instrumented), or else the communication to another system from this one for which we are expecting an answer. Each instance of this class should be used to instrument all requests of a particular type. For each instance of this class, the following metrics will be created: * `<prefix>_requests_total` -- a counter indicating the total number of requests started (initiated or received by the system). Labels on this metric are taken from the label set passed to #measure. * `<prefix>_request_duration_seconds` -- a histogram for the response times of successful responses (that is, where no exception was raised). You can get the count of total successful responses from `<prefix>_request_duration_seconds_count`. Labels on this metric are taken from the labels set generated during the measured run (as generated by manipulating the hash yielded to your block). * `<prefix>_exceptions_total` -- a count of the number of exceptions raised during processing. A label, `class`, indicates the class of the exception raised. Labels on this metric are taken from the label set passed to #measure, along with a special label `class` to indicate the class of the exception raised. * `<prefix>_in_progress_count` -- a gauge indicating how many requests are currently in progress as at the time of the scrape. Labels on this metric are taken from the label set passed to #measure. @param prefix [#to_s] the string that will be prepended to all of the Prometheus metric names generated for this instrumentation. The prefix you choose should include both the application name (typically the first word) as well as a unique identifier for the request type itself. Multiple words should be underscore separated. @param outgoing [Boolean] whether this Request instance is collecting data on incoming requests or outgoing requests (the default, as usually there is one incoming request handler, but there can easily be several outgoing request types). It is only used to customise the metric description text for the metrics, so it's not crucially important. @param description [#to_s] a short explanation of what this is measuring. It should be a singular and indefinite noun phrase, to maximise the chances that it will fit neatly into the generated description text. @param registry [Prometheus::Client::Registry] the client registry in which all the metrics will be created. The default will put all the metrics in the Prometheus Client's default registry, which may or may not be what you're up for. If you're using Frankenstein::Server, you want `stats_server.registry`. Instrument an instance of the request. Each time a particular external communication occurs, it should be wrapped by a call to this method. Request-related statistics (that the request has been made or received) are updated before the passed block is executed, and then after the block completes, response-related statistics (duration or exception) are recorded. The number of currently-in-progress instances of the request are also kept track of. @param labels [Hash] a set of labels that can help to differentiate different sorts of requests. These labels are applied to the `<prefix>_requests_total` and `<prefix>_in_progress_count` metrics, as well as the `<prefix>_exceptions_total` metric, if an exception is raised. Don't get too fancy with this label set -- it's unusual that this is actually useful in practice. However it is provided for those unusual cases where it isn't a bad idea. Your go-to solution should be to label the `<prefix>_request_duration_seconds` metric (by modifying the hash yielded to the block you pass to #measure), rather than using this parameter with wild abandon. Serious talk time: I've been there. It seems like a great idea at first, to differentiate requests with lots of labels, but it usually just ends up turning into a giant mess. Primarily, due to the way that Prometheus deals with label sets, if you *ever* use a label on *any* of your requests, you need to set the same label to some value on *all* of your requests. So, unless you can say with certainty that every request you receive will logically have some meaningful value for a given label, you shouldn't use it. **NOTE**: the labelset you specify here will be the default labelset applied to the `<prefix>_request_duration_seconds` metric. If you need to remove a label from the response, use `labels.replace` or `labels.delete` to remove the key. @yield [Hash] the labels that will be applied to the `<Prefix>_request_duration_seconds` metric. In order for your label set to be applied, you must *mutate the hash that is yielded*, rather than overwriting it. That means, for example, that the following code **will not work**: req_stats.measure do |labels| labels = {foo: 'bar', baz: 'wombat'} ... Instead, you need to either set each key one by one, or use the handy-dandy Hash#replace method, like this: req_stats.measure do |labels| labels.replace(foo: 'bar', baz: 'wombat') ... If your labels are not being applied to your response histogram, check for any assignment to the yielded variable. It's *really* easy to do by mistake. **NOTE WELL**: The Prometheus specification (assuming it exists) apparently requires that all of the instances of a given metric have the same set of labels. If you fail to do this, an exception will be raised by Prometheus after the block is executed. @raise [Prometheus::Request::NoBlockError] if you didn't pass a block to call. There's nothing to instrument! @raise [Prometheus::Client::LabelSetValidator::LabelSetError] if you violate any written or unwritten rules about how Prometheus label sets should be constructed. @raise [Exception] any exception raised by the executed block will be re-raised by this method after statistics collection is complete. @return [Object] whatever was returned by the block passed.
[ "Create", "a", "new", "request", "instrumentation", "package", "." ]
1bbd9835233d0672af020da405ea1b29d55d105e
https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/request.rb#L165-L189
train
mpalmer/frankenstein
lib/frankenstein/collected_metric.rb
Frankenstein.CollectedMetric.values
def values begin @collector.call(self).tap do |results| unless results.is_a?(Hash) @logger.error(progname) { "Collector proc did not return a hash, got #{results.inspect}" } @errors_metric.increment(class: "NotAHashError") return {} end results.keys.each { |labelset| @validator.validate(labelset) } end rescue StandardError => ex @logger.error(progname) { (["Exception in collection: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } @errors_metric.increment(class: ex.class.to_s) {} end end
ruby
def values begin @collector.call(self).tap do |results| unless results.is_a?(Hash) @logger.error(progname) { "Collector proc did not return a hash, got #{results.inspect}" } @errors_metric.increment(class: "NotAHashError") return {} end results.keys.each { |labelset| @validator.validate(labelset) } end rescue StandardError => ex @logger.error(progname) { (["Exception in collection: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } @errors_metric.increment(class: ex.class.to_s) {} end end
[ "def", "values", "begin", "@collector", ".", "call", "(", "self", ")", ".", "tap", "do", "|", "results", "|", "unless", "results", ".", "is_a?", "(", "Hash", ")", "@logger", ".", "error", "(", "progname", ")", "{", "\"Collector proc did not return a hash, got #{results.inspect}\"", "}", "@errors_metric", ".", "increment", "(", "class", ":", "\"NotAHashError\"", ")", "return", "{", "}", "end", "results", ".", "keys", ".", "each", "{", "|", "labelset", "|", "@validator", ".", "validate", "(", "labelset", ")", "}", "end", "rescue", "StandardError", "=>", "ex", "@logger", ".", "error", "(", "progname", ")", "{", "(", "[", "\"Exception in collection: #{ex.message} (#{ex.class})\"", "]", "+", "ex", ".", "backtrace", ")", ".", "join", "(", "\"\\n \"", ")", "}", "@errors_metric", ".", "increment", "(", "class", ":", "ex", ".", "class", ".", "to_s", ")", "{", "}", "end", "end" ]
Retrieve a complete set of labels and values for the metric.
[ "Retrieve", "a", "complete", "set", "of", "labels", "and", "values", "for", "the", "metric", "." ]
1bbd9835233d0672af020da405ea1b29d55d105e
https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/collected_metric.rb#L121-L137
train
mpalmer/frankenstein
lib/frankenstein/collected_metric.rb
Frankenstein.CollectedMetric.validate_type
def validate_type(type) unless %i{gauge counter histogram summary}.include?(type) raise ArgumentError, "type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})" end end
ruby
def validate_type(type) unless %i{gauge counter histogram summary}.include?(type) raise ArgumentError, "type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})" end end
[ "def", "validate_type", "(", "type", ")", "unless", "%i{", "gauge", "counter", "histogram", "summary", "}", ".", "include?", "(", "type", ")", "raise", "ArgumentError", ",", "\"type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})\"", "end", "end" ]
Make sure that the type we were passed is one Prometheus is known to accept.
[ "Make", "sure", "that", "the", "type", "we", "were", "passed", "is", "one", "Prometheus", "is", "known", "to", "accept", "." ]
1bbd9835233d0672af020da405ea1b29d55d105e
https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/collected_metric.rb#L143-L147
train
raygao/asf-soap-adapter
lib/salesforce/chatter_feed.rb
Salesforce.ChatterFeed.search_chatter_feeds
def search_chatter_feeds(object_type, query_string, binding, limit=100) return get_all_chatter_feeds_with_attachments(nil, object_type, binding, 'no-attachment-for-search', limit, false, query_string) end
ruby
def search_chatter_feeds(object_type, query_string, binding, limit=100) return get_all_chatter_feeds_with_attachments(nil, object_type, binding, 'no-attachment-for-search', limit, false, query_string) end
[ "def", "search_chatter_feeds", "(", "object_type", ",", "query_string", ",", "binding", ",", "limit", "=", "100", ")", "return", "get_all_chatter_feeds_with_attachments", "(", "nil", ",", "object_type", ",", "binding", ",", "'no-attachment-for-search'", ",", "limit", ",", "false", ",", "query_string", ")", "end" ]
find all chatter feeds based on object_type, query_string, and given binding
[ "find", "all", "chatter", "feeds", "based", "on", "object_type", "query_string", "and", "given", "binding" ]
ab96dc48d60a6410d620cafe68ae7add012dc9d4
https://github.com/raygao/asf-soap-adapter/blob/ab96dc48d60a6410d620cafe68ae7add012dc9d4/lib/salesforce/chatter_feed.rb#L66-L68
train
norman/phonology
lib/phonology/inventory.rb
Phonology.Inventory.with
def with(*features) pos, neg = mangle_args(*features) self.class.new(Hash[@sets.select do |key, val| !key.intersection(pos).empty? end]).without_any(neg) end
ruby
def with(*features) pos, neg = mangle_args(*features) self.class.new(Hash[@sets.select do |key, val| !key.intersection(pos).empty? end]).without_any(neg) end
[ "def", "with", "(", "*", "features", ")", "pos", ",", "neg", "=", "mangle_args", "(", "*", "features", ")", "self", ".", "class", ".", "new", "(", "Hash", "[", "@sets", ".", "select", "do", "|", "key", ",", "val", "|", "!", "key", ".", "intersection", "(", "pos", ")", ".", "empty?", "end", "]", ")", ".", "without_any", "(", "neg", ")", "end" ]
Return an instance of Sounds whose sets include any of the given features.
[ "Return", "an", "instance", "of", "Sounds", "whose", "sets", "include", "any", "of", "the", "given", "features", "." ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L48-L53
train
norman/phonology
lib/phonology/inventory.rb
Phonology.Inventory.with_all
def with_all(*features) pos, neg = mangle_args(*features) self.class.new(Hash[@sets.select do |key, val| pos.subset?(key) end]).without_any(neg) end
ruby
def with_all(*features) pos, neg = mangle_args(*features) self.class.new(Hash[@sets.select do |key, val| pos.subset?(key) end]).without_any(neg) end
[ "def", "with_all", "(", "*", "features", ")", "pos", ",", "neg", "=", "mangle_args", "(", "*", "features", ")", "self", ".", "class", ".", "new", "(", "Hash", "[", "@sets", ".", "select", "do", "|", "key", ",", "val", "|", "pos", ".", "subset?", "(", "key", ")", "end", "]", ")", ".", "without_any", "(", "neg", ")", "end" ]
Return feature sets that include all of the given features
[ "Return", "feature", "sets", "that", "include", "all", "of", "the", "given", "features" ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L56-L61
train
norman/phonology
lib/phonology/inventory.rb
Phonology.Inventory.without
def without(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| !features.subset?(key)}] end
ruby
def without(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| !features.subset?(key)}] end
[ "def", "without", "(", "*", "features", ")", "features", "=", "setify", "(", "*", "features", ")", "self", ".", "class", ".", "new", "Hash", "[", "@sets", ".", "select", "{", "|", "key", ",", "val", "|", "!", "features", ".", "subset?", "(", "key", ")", "}", "]", "end" ]
Return an instance of Sounds whose sets exclude any of the given features.
[ "Return", "an", "instance", "of", "Sounds", "whose", "sets", "exclude", "any", "of", "the", "given", "features", "." ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L65-L68
train
norman/phonology
lib/phonology/inventory.rb
Phonology.Inventory.without_any
def without_any(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| key.intersection(features).empty?}] end
ruby
def without_any(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| key.intersection(features).empty?}] end
[ "def", "without_any", "(", "*", "features", ")", "features", "=", "setify", "(", "*", "features", ")", "self", ".", "class", ".", "new", "Hash", "[", "@sets", ".", "select", "{", "|", "key", ",", "val", "|", "key", ".", "intersection", "(", "features", ")", ".", "empty?", "}", "]", "end" ]
Return an instance of Sounds whose sets exclude all of the given features.
[ "Return", "an", "instance", "of", "Sounds", "whose", "sets", "exclude", "all", "of", "the", "given", "features", "." ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L72-L75
train
tecfoundary/hicube
app/controllers/hicube/base_controller.rb
Hicube.BaseController.check_resource_params
def check_resource_params(options = {}) # Determine the name based on the current controller if not specified. resource_name = options[:name] || controller_name.singularize # Determine the class based on the resource name if not provided. #FIXME: Do not hardcode engine name resource_class = options[:class] || "Hicube::#{resource_name.singularize.camelize}".classify.constantize unless params.key?(resource_name) notify :error, ::I18n.t('messages.resource.missing_parameters', :type => resource_class.model_name.human ) case action_name.to_sym when :create redirect_to :action => :new when :update redirect_to :action => :edit, :id => params[:id] else redirect_to :action => :index end end end
ruby
def check_resource_params(options = {}) # Determine the name based on the current controller if not specified. resource_name = options[:name] || controller_name.singularize # Determine the class based on the resource name if not provided. #FIXME: Do not hardcode engine name resource_class = options[:class] || "Hicube::#{resource_name.singularize.camelize}".classify.constantize unless params.key?(resource_name) notify :error, ::I18n.t('messages.resource.missing_parameters', :type => resource_class.model_name.human ) case action_name.to_sym when :create redirect_to :action => :new when :update redirect_to :action => :edit, :id => params[:id] else redirect_to :action => :index end end end
[ "def", "check_resource_params", "(", "options", "=", "{", "}", ")", "resource_name", "=", "options", "[", ":name", "]", "||", "controller_name", ".", "singularize", "resource_class", "=", "options", "[", ":class", "]", "||", "\"Hicube::#{resource_name.singularize.camelize}\"", ".", "classify", ".", "constantize", "unless", "params", ".", "key?", "(", "resource_name", ")", "notify", ":error", ",", "::", "I18n", ".", "t", "(", "'messages.resource.missing_parameters'", ",", ":type", "=>", "resource_class", ".", "model_name", ".", "human", ")", "case", "action_name", ".", "to_sym", "when", ":create", "redirect_to", ":action", "=>", ":new", "when", ":update", "redirect_to", ":action", "=>", ":edit", ",", ":id", "=>", "params", "[", ":id", "]", "else", "redirect_to", ":action", "=>", ":index", "end", "end", "end" ]
Check resource params are present based on the current controller name.
[ "Check", "resource", "params", "are", "present", "based", "on", "the", "current", "controller", "name", "." ]
57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe
https://github.com/tecfoundary/hicube/blob/57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe/app/controllers/hicube/base_controller.rb#L31-L55
train
tsonntag/gitter
lib/gitter/column.rb
Gitter.Column.order_params
def order_params desc = !desc? p = grid.params.dup if ordered? p[:desc] = desc else p = p.merge order: name, desc: desc end grid.scoped_params p end
ruby
def order_params desc = !desc? p = grid.params.dup if ordered? p[:desc] = desc else p = p.merge order: name, desc: desc end grid.scoped_params p end
[ "def", "order_params", "desc", "=", "!", "desc?", "p", "=", "grid", ".", "params", ".", "dup", "if", "ordered?", "p", "[", ":desc", "]", "=", "desc", "else", "p", "=", "p", ".", "merge", "order", ":", "name", ",", "desc", ":", "desc", "end", "grid", ".", "scoped_params", "p", "end" ]
if current params contain order for this column then revert direction else add order_params for this column to current params
[ "if", "current", "params", "contain", "order", "for", "this", "column", "then", "revert", "direction", "else", "add", "order_params", "for", "this", "column", "to", "current", "params" ]
55c79a5d8012129517510d1d1758621f4baf5344
https://github.com/tsonntag/gitter/blob/55c79a5d8012129517510d1d1758621f4baf5344/lib/gitter/column.rb#L126-L134
train
faradayio/charisma
lib/charisma/curator.rb
Charisma.Curator.characteristics
def characteristics return @characteristics if @characteristics hsh = Hash.new do |_, key| if characterization = subject.class.characterization[key] Curation.new nil, characterization end end hsh.extend LooseEquality @characteristics = hsh end
ruby
def characteristics return @characteristics if @characteristics hsh = Hash.new do |_, key| if characterization = subject.class.characterization[key] Curation.new nil, characterization end end hsh.extend LooseEquality @characteristics = hsh end
[ "def", "characteristics", "return", "@characteristics", "if", "@characteristics", "hsh", "=", "Hash", ".", "new", "do", "|", "_", ",", "key", "|", "if", "characterization", "=", "subject", ".", "class", ".", "characterization", "[", "key", "]", "Curation", ".", "new", "nil", ",", "characterization", "end", "end", "hsh", ".", "extend", "LooseEquality", "@characteristics", "=", "hsh", "end" ]
Create a Curator. Typically this is done automatically when <tt>#characteristics</tt> is called on an instance of a characterized class for the first time. @param [Object] The subject of the curation -- an instance of a characterized class @see Charisma::Base#characteristics The special hash wrapped by the curator that actually stores the computed characteristics.
[ "Create", "a", "Curator", "." ]
87d26ff48c9611f99ebfd01cee9cd15b5d79cabe
https://github.com/faradayio/charisma/blob/87d26ff48c9611f99ebfd01cee9cd15b5d79cabe/lib/charisma/curator.rb#L28-L38
train
faradayio/charisma
lib/charisma/curator.rb
Charisma.Curator.[]=
def []=(key, value) characteristics[key] = Curation.new value, subject.class.characterization[key] end
ruby
def []=(key, value) characteristics[key] = Curation.new value, subject.class.characterization[key] end
[ "def", "[]=", "(", "key", ",", "value", ")", "characteristics", "[", "key", "]", "=", "Curation", ".", "new", "value", ",", "subject", ".", "class", ".", "characterization", "[", "key", "]", "end" ]
Store a late-defined characteristic, with a Charisma wrapper. @param [Symbol] key The name of the characteristic, which must match one defined in the class's characterization @param value The value of the characteristic
[ "Store", "a", "late", "-", "defined", "characteristic", "with", "a", "Charisma", "wrapper", "." ]
87d26ff48c9611f99ebfd01cee9cd15b5d79cabe
https://github.com/faradayio/charisma/blob/87d26ff48c9611f99ebfd01cee9cd15b5d79cabe/lib/charisma/curator.rb#L43-L45
train
jgoizueta/units-system
lib/units/measure.rb
Units.Measure.detailed_units
def detailed_units(all_levels = false) mag = @magnitude prev_units = self.units units = {} loop do compound = false prev_units.each_pair do |dim, (unit,mul)| ud = Units.unit(unit) if ud.decomposition compound = true mag *= ud.decomposition.magnitude ud.decomposition.units.each_pair do |d, (u,m)| mag *= self.class.combine(units, d, u, m*mul) end else mag *= self.class.combine(units, dim, unit, mul) end end if all_levels && compound prev_units = units units = {} else break end end Measure.new mag, units end
ruby
def detailed_units(all_levels = false) mag = @magnitude prev_units = self.units units = {} loop do compound = false prev_units.each_pair do |dim, (unit,mul)| ud = Units.unit(unit) if ud.decomposition compound = true mag *= ud.decomposition.magnitude ud.decomposition.units.each_pair do |d, (u,m)| mag *= self.class.combine(units, d, u, m*mul) end else mag *= self.class.combine(units, dim, unit, mul) end end if all_levels && compound prev_units = units units = {} else break end end Measure.new mag, units end
[ "def", "detailed_units", "(", "all_levels", "=", "false", ")", "mag", "=", "@magnitude", "prev_units", "=", "self", ".", "units", "units", "=", "{", "}", "loop", "do", "compound", "=", "false", "prev_units", ".", "each_pair", "do", "|", "dim", ",", "(", "unit", ",", "mul", ")", "|", "ud", "=", "Units", ".", "unit", "(", "unit", ")", "if", "ud", ".", "decomposition", "compound", "=", "true", "mag", "*=", "ud", ".", "decomposition", ".", "magnitude", "ud", ".", "decomposition", ".", "units", ".", "each_pair", "do", "|", "d", ",", "(", "u", ",", "m", ")", "|", "mag", "*=", "self", ".", "class", ".", "combine", "(", "units", ",", "d", ",", "u", ",", "m", "*", "mul", ")", "end", "else", "mag", "*=", "self", ".", "class", ".", "combine", "(", "units", ",", "dim", ",", "unit", ",", "mul", ")", "end", "end", "if", "all_levels", "&&", "compound", "prev_units", "=", "units", "units", "=", "{", "}", "else", "break", "end", "end", "Measure", ".", "new", "mag", ",", "units", "end" ]
decompose compound units
[ "decompose", "compound", "units" ]
7e9ee9fe217e399ef1950337a75be5a7473dff2a
https://github.com/jgoizueta/units-system/blob/7e9ee9fe217e399ef1950337a75be5a7473dff2a/lib/units/measure.rb#L87-L113
train
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.insert
def insert(text) raise "must be passed string" unless text.is_a?(String) snippet = Snippet.new_text(core, text) snippet.snippet_tags.each do |tag_info| visit tag_info[:tag] end context = Context.new(nil) insert_func(snippet, context).join($/) end
ruby
def insert(text) raise "must be passed string" unless text.is_a?(String) snippet = Snippet.new_text(core, text) snippet.snippet_tags.each do |tag_info| visit tag_info[:tag] end context = Context.new(nil) insert_func(snippet, context).join($/) end
[ "def", "insert", "(", "text", ")", "raise", "\"must be passed string\"", "unless", "text", ".", "is_a?", "(", "String", ")", "snippet", "=", "Snippet", ".", "new_text", "(", "core", ",", "text", ")", "snippet", ".", "snippet_tags", ".", "each", "do", "|", "tag_info", "|", "visit", "tag_info", "[", ":tag", "]", "end", "context", "=", "Context", ".", "new", "(", "nil", ")", "insert_func", "(", "snippet", ",", "context", ")", ".", "join", "(", "$/", ")", "end" ]
Insert snippets to given text @param text [String] The text of source code
[ "Insert", "snippets", "to", "given", "text" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L67-L77
train
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.insert_by_tag_and_context!
def insert_by_tag_and_context!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) src = insert_func(snippet, context, tag) options[:margin_top].times { inserter.insert "" } # @snip -> @snippet inserter.insert tag.to_snippet_tag unless snippet.no_tag? # insert snippet text inserter.insert src options[:margin_bottom].times { inserter.insert "" } visit tag end
ruby
def insert_by_tag_and_context!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) src = insert_func(snippet, context, tag) options[:margin_top].times { inserter.insert "" } # @snip -> @snippet inserter.insert tag.to_snippet_tag unless snippet.no_tag? # insert snippet text inserter.insert src options[:margin_bottom].times { inserter.insert "" } visit tag end
[ "def", "insert_by_tag_and_context!", "(", "inserter", ",", "snippet", ",", "context", ",", "tag", ")", "raise", "\"must be passed snippet\"", "unless", "snippet", ".", "is_a?", "(", "Snippet", ")", "src", "=", "insert_func", "(", "snippet", ",", "context", ",", "tag", ")", "options", "[", ":margin_top", "]", ".", "times", "{", "inserter", ".", "insert", "\"\"", "}", "inserter", ".", "insert", "tag", ".", "to_snippet_tag", "unless", "snippet", ".", "no_tag?", "inserter", ".", "insert", "src", "options", "[", ":margin_bottom", "]", ".", "times", "{", "inserter", ".", "insert", "\"\"", "}", "visit", "tag", "end" ]
Insert snippet by tag and context
[ "Insert", "snippet", "by", "tag", "and", "context" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L104-L117
train
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.insert_depended_snippets!
def insert_depended_snippets!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) dep_tags = deps_resolver.find(snippet, context, tag) dep_tags = sort_dep_tags_by_dep(dep_tags) dep_tags.each do |tag_info| sub_t = tag_info[:tag] sub_c = tag_info[:context] resolve_tag_repo_ref! sub_t visit(tag) if is_self(sub_t, sub_c) next if is_visited(sub_t) next_snippet = core.repo_manager.get_snippet(sub_c, sub_t) insert_by_tag_and_context! inserter, next_snippet, sub_c, sub_t end end
ruby
def insert_depended_snippets!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) dep_tags = deps_resolver.find(snippet, context, tag) dep_tags = sort_dep_tags_by_dep(dep_tags) dep_tags.each do |tag_info| sub_t = tag_info[:tag] sub_c = tag_info[:context] resolve_tag_repo_ref! sub_t visit(tag) if is_self(sub_t, sub_c) next if is_visited(sub_t) next_snippet = core.repo_manager.get_snippet(sub_c, sub_t) insert_by_tag_and_context! inserter, next_snippet, sub_c, sub_t end end
[ "def", "insert_depended_snippets!", "(", "inserter", ",", "snippet", ",", "context", ",", "tag", ")", "raise", "\"must be passed snippet\"", "unless", "snippet", ".", "is_a?", "(", "Snippet", ")", "dep_tags", "=", "deps_resolver", ".", "find", "(", "snippet", ",", "context", ",", "tag", ")", "dep_tags", "=", "sort_dep_tags_by_dep", "(", "dep_tags", ")", "dep_tags", ".", "each", "do", "|", "tag_info", "|", "sub_t", "=", "tag_info", "[", ":tag", "]", "sub_c", "=", "tag_info", "[", ":context", "]", "resolve_tag_repo_ref!", "sub_t", "visit", "(", "tag", ")", "if", "is_self", "(", "sub_t", ",", "sub_c", ")", "next", "if", "is_visited", "(", "sub_t", ")", "next_snippet", "=", "core", ".", "repo_manager", ".", "get_snippet", "(", "sub_c", ",", "sub_t", ")", "insert_by_tag_and_context!", "inserter", ",", "next_snippet", ",", "sub_c", ",", "sub_t", "end", "end" ]
Insert depended snippet
[ "Insert", "depended", "snippet" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L120-L137
train
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.sort_dep_tags_by_dep
def sort_dep_tags_by_dep(dep_tags) dep_tags_index = {} # map tag to index dep_tags.each.with_index do |tag_info, k| tag = tag_info[:tag] dep_tags_index[tag.to_path] = k end # generate dependency graph dep_tags_hash = TSortableHash.new dep_tags.each do |tag_info| tag = tag_info[:tag].to_path dep_ind = dep_tags_index[tag] dep_tags_hash[dep_ind] = deps_resolver.dep_to[tag].to_a.map {|tag| dep_tags_index[tag] }.reject(&:nil?) end dep_tags_hash.tsort.map {|k| dep_tags[k] } end
ruby
def sort_dep_tags_by_dep(dep_tags) dep_tags_index = {} # map tag to index dep_tags.each.with_index do |tag_info, k| tag = tag_info[:tag] dep_tags_index[tag.to_path] = k end # generate dependency graph dep_tags_hash = TSortableHash.new dep_tags.each do |tag_info| tag = tag_info[:tag].to_path dep_ind = dep_tags_index[tag] dep_tags_hash[dep_ind] = deps_resolver.dep_to[tag].to_a.map {|tag| dep_tags_index[tag] }.reject(&:nil?) end dep_tags_hash.tsort.map {|k| dep_tags[k] } end
[ "def", "sort_dep_tags_by_dep", "(", "dep_tags", ")", "dep_tags_index", "=", "{", "}", "dep_tags", ".", "each", ".", "with_index", "do", "|", "tag_info", ",", "k", "|", "tag", "=", "tag_info", "[", ":tag", "]", "dep_tags_index", "[", "tag", ".", "to_path", "]", "=", "k", "end", "dep_tags_hash", "=", "TSortableHash", ".", "new", "dep_tags", ".", "each", "do", "|", "tag_info", "|", "tag", "=", "tag_info", "[", ":tag", "]", ".", "to_path", "dep_ind", "=", "dep_tags_index", "[", "tag", "]", "dep_tags_hash", "[", "dep_ind", "]", "=", "deps_resolver", ".", "dep_to", "[", "tag", "]", ".", "to_a", ".", "map", "{", "|", "tag", "|", "dep_tags_index", "[", "tag", "]", "}", ".", "reject", "(", "&", ":nil?", ")", "end", "dep_tags_hash", ".", "tsort", ".", "map", "{", "|", "k", "|", "dep_tags", "[", "k", "]", "}", "end" ]
Sort by dependency
[ "Sort", "by", "dependency" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L140-L158
train
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.create
def create(label) create_atomic(label.to_s) or create_composite(label.to_s) or raise MeasurementError.new("Unit '#{label}' not found") end
ruby
def create(label) create_atomic(label.to_s) or create_composite(label.to_s) or raise MeasurementError.new("Unit '#{label}' not found") end
[ "def", "create", "(", "label", ")", "create_atomic", "(", "label", ".", "to_s", ")", "or", "create_composite", "(", "label", ".", "to_s", ")", "or", "raise", "MeasurementError", ".", "new", "(", "\"Unit '#{label}' not found\"", ")", "end" ]
Returns the unit with the given label. Creates a new unit if necessary. Raises MeasurementError if the unit could not be created.
[ "Returns", "the", "unit", "with", "the", "given", "label", ".", "Creates", "a", "new", "unit", "if", "necessary", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L14-L16
train
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.slice_atomic_unit
def slice_atomic_unit(str) label = '' str.scan(/_?[^_]+/) do |chunk| label << chunk unit = create_atomic(label) return label, unit if unit end raise MeasurementError.new("Unit '#{str}' not found") end
ruby
def slice_atomic_unit(str) label = '' str.scan(/_?[^_]+/) do |chunk| label << chunk unit = create_atomic(label) return label, unit if unit end raise MeasurementError.new("Unit '#{str}' not found") end
[ "def", "slice_atomic_unit", "(", "str", ")", "label", "=", "''", "str", ".", "scan", "(", "/", "/", ")", "do", "|", "chunk", "|", "label", "<<", "chunk", "unit", "=", "create_atomic", "(", "label", ")", "return", "label", ",", "unit", "if", "unit", "end", "raise", "MeasurementError", ".", "new", "(", "\"Unit '#{str}' not found\"", ")", "end" ]
Returns the Unit which matches the str prefix. Raises MeasurementError if the unit could not be determined.
[ "Returns", "the", "Unit", "which", "matches", "the", "str", "prefix", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L69-L77
train
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.match_scalar
def match_scalar(label) label = label.to_sym Factor.detect do |factor| return factor if factor.label == label or factor.abbreviation == label end end
ruby
def match_scalar(label) label = label.to_sym Factor.detect do |factor| return factor if factor.label == label or factor.abbreviation == label end end
[ "def", "match_scalar", "(", "label", ")", "label", "=", "label", ".", "to_sym", "Factor", ".", "detect", "do", "|", "factor", "|", "return", "factor", "if", "factor", ".", "label", "==", "label", "or", "factor", ".", "abbreviation", "==", "label", "end", "end" ]
Returns the Factor which matches the label, or nil if no match.
[ "Returns", "the", "Factor", "which", "matches", "the", "label", "or", "nil", "if", "no", "match", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L132-L137
train
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.suffix?
def suffix?(suffix, text) len = suffix.length len <= text.length and suffix == text[-len, len] end
ruby
def suffix?(suffix, text) len = suffix.length len <= text.length and suffix == text[-len, len] end
[ "def", "suffix?", "(", "suffix", ",", "text", ")", "len", "=", "suffix", ".", "length", "len", "<=", "text", ".", "length", "and", "suffix", "==", "text", "[", "-", "len", ",", "len", "]", "end" ]
Returns whether text ends in suffix.
[ "Returns", "whether", "text", "ends", "in", "suffix", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L140-L143
train
akerl/octoauth
lib/octoauth/configfile.rb
Octoauth.ConfigFile.write
def write new = get new[@note] = @token File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml } end
ruby
def write new = get new[@note] = @token File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml } end
[ "def", "write", "new", "=", "get", "new", "[", "@note", "]", "=", "@token", "File", ".", "open", "(", "@file", ",", "'w'", ",", "0o0600", ")", "{", "|", "fh", "|", "fh", ".", "write", "new", ".", "to_yaml", "}", "end" ]
Create new Config object, either ephemerally or from a file
[ "Create", "new", "Config", "object", "either", "ephemerally", "or", "from", "a", "file" ]
160bf0e86d82ce63a39e3c4b28abc429c5ea7aa9
https://github.com/akerl/octoauth/blob/160bf0e86d82ce63a39e3c4b28abc429c5ea7aa9/lib/octoauth/configfile.rb#L27-L31
train
KPB-US/swhd-api
lib/swhd_api.rb
SwhdApi.Manager.fetch
def fetch(resource, params = {}) method = :get page = 1 params[:page] = page partial = request(resource, method, params) while partial.is_a?(Array) && !partial.empty? results ||= [] results += partial page += 1 params[:page] = page partial = request(resource, method, params) end results = partial unless partial.nil? || partial.empty? results end
ruby
def fetch(resource, params = {}) method = :get page = 1 params[:page] = page partial = request(resource, method, params) while partial.is_a?(Array) && !partial.empty? results ||= [] results += partial page += 1 params[:page] = page partial = request(resource, method, params) end results = partial unless partial.nil? || partial.empty? results end
[ "def", "fetch", "(", "resource", ",", "params", "=", "{", "}", ")", "method", "=", ":get", "page", "=", "1", "params", "[", ":page", "]", "=", "page", "partial", "=", "request", "(", "resource", ",", "method", ",", "params", ")", "while", "partial", ".", "is_a?", "(", "Array", ")", "&&", "!", "partial", ".", "empty?", "results", "||=", "[", "]", "results", "+=", "partial", "page", "+=", "1", "params", "[", ":page", "]", "=", "page", "partial", "=", "request", "(", "resource", ",", "method", ",", "params", ")", "end", "results", "=", "partial", "unless", "partial", ".", "nil?", "||", "partial", ".", "empty?", "results", "end" ]
fetch all pages of results
[ "fetch", "all", "pages", "of", "results" ]
f4cd031d4ace7253d8e1943a81eb300121eb4f68
https://github.com/KPB-US/swhd-api/blob/f4cd031d4ace7253d8e1943a81eb300121eb4f68/lib/swhd_api.rb#L84-L100
train
ManojmoreS/mores_marvel
lib/mores_marvel/resource.rb
MoresMarvel.Resource.fetch_by_id
def fetch_by_id(model, id, filters = {}) get_resource("/v1/public/#{model}/#{id}", filters) if model_exists?(model) && validate_filters(filters) end
ruby
def fetch_by_id(model, id, filters = {}) get_resource("/v1/public/#{model}/#{id}", filters) if model_exists?(model) && validate_filters(filters) end
[ "def", "fetch_by_id", "(", "model", ",", "id", ",", "filters", "=", "{", "}", ")", "get_resource", "(", "\"/v1/public/#{model}/#{id}\"", ",", "filters", ")", "if", "model_exists?", "(", "model", ")", "&&", "validate_filters", "(", "filters", ")", "end" ]
fetch a record by id
[ "fetch", "a", "record", "by", "id" ]
b14b1305b51e311ca10ad1c1462361f6e04a95e5
https://github.com/ManojmoreS/mores_marvel/blob/b14b1305b51e311ca10ad1c1462361f6e04a95e5/lib/mores_marvel/resource.rb#L12-L14
train
void-main/tily.rb
lib/tily.rb
Tily.Tily.processing_hint_str
def processing_hint_str number, level total = (@ts.tile_size(level) ** 2).to_s now = (number + 1).to_s.rjust(total.length, " ") "#{now}/#{total}" end
ruby
def processing_hint_str number, level total = (@ts.tile_size(level) ** 2).to_s now = (number + 1).to_s.rjust(total.length, " ") "#{now}/#{total}" end
[ "def", "processing_hint_str", "number", ",", "level", "total", "=", "(", "@ts", ".", "tile_size", "(", "level", ")", "**", "2", ")", ".", "to_s", "now", "=", "(", "number", "+", "1", ")", ".", "to_s", ".", "rjust", "(", "total", ".", "length", ",", "\" \"", ")", "\"#{now}/#{total}\"", "end" ]
Format a beautiful hint string
[ "Format", "a", "beautiful", "hint", "string" ]
5ff21e172ef0d62eaea59573aa429522080ae326
https://github.com/void-main/tily.rb/blob/5ff21e172ef0d62eaea59573aa429522080ae326/lib/tily.rb#L64-L68
train
ad2games/soapy_cake
lib/soapy_cake/campaigns.rb
SoapyCake.Campaigns.patch
def patch(campaign_id, opts = {}) campaign = get(campaign_id: campaign_id).first opts = NO_CHANGE_VALUES .merge( affiliate_id: campaign.fetch(:affiliate).fetch(:affiliate_id), media_type_id: campaign.fetch(:media_type).fetch(:media_type_id), offer_contract_id: campaign.fetch(:offer_contract).fetch(:offer_contract_id), offer_id: campaign.fetch(:offer).fetch(:offer_id), payout: campaign.fetch(:payout).fetch(:amount), payout_update_option: 'do_not_change', pixel_html: campaign.dig(:pixel_info, :pixel_html) || '', postback_url: campaign.dig(:pixel_info, :postback_url) || '', redirect_domain: campaign.fetch(:redirect_domain, ''), test_link: campaign[:test_link] || '', unique_key_hash: campaign.dig(:pixel_info, :hash_type, :hash_type_id) || 'none', third_party_name: campaign.fetch(:third_party_name, '') ) .merge(opts) update(campaign_id, opts) nil end
ruby
def patch(campaign_id, opts = {}) campaign = get(campaign_id: campaign_id).first opts = NO_CHANGE_VALUES .merge( affiliate_id: campaign.fetch(:affiliate).fetch(:affiliate_id), media_type_id: campaign.fetch(:media_type).fetch(:media_type_id), offer_contract_id: campaign.fetch(:offer_contract).fetch(:offer_contract_id), offer_id: campaign.fetch(:offer).fetch(:offer_id), payout: campaign.fetch(:payout).fetch(:amount), payout_update_option: 'do_not_change', pixel_html: campaign.dig(:pixel_info, :pixel_html) || '', postback_url: campaign.dig(:pixel_info, :postback_url) || '', redirect_domain: campaign.fetch(:redirect_domain, ''), test_link: campaign[:test_link] || '', unique_key_hash: campaign.dig(:pixel_info, :hash_type, :hash_type_id) || 'none', third_party_name: campaign.fetch(:third_party_name, '') ) .merge(opts) update(campaign_id, opts) nil end
[ "def", "patch", "(", "campaign_id", ",", "opts", "=", "{", "}", ")", "campaign", "=", "get", "(", "campaign_id", ":", "campaign_id", ")", ".", "first", "opts", "=", "NO_CHANGE_VALUES", ".", "merge", "(", "affiliate_id", ":", "campaign", ".", "fetch", "(", ":affiliate", ")", ".", "fetch", "(", ":affiliate_id", ")", ",", "media_type_id", ":", "campaign", ".", "fetch", "(", ":media_type", ")", ".", "fetch", "(", ":media_type_id", ")", ",", "offer_contract_id", ":", "campaign", ".", "fetch", "(", ":offer_contract", ")", ".", "fetch", "(", ":offer_contract_id", ")", ",", "offer_id", ":", "campaign", ".", "fetch", "(", ":offer", ")", ".", "fetch", "(", ":offer_id", ")", ",", "payout", ":", "campaign", ".", "fetch", "(", ":payout", ")", ".", "fetch", "(", ":amount", ")", ",", "payout_update_option", ":", "'do_not_change'", ",", "pixel_html", ":", "campaign", ".", "dig", "(", ":pixel_info", ",", ":pixel_html", ")", "||", "''", ",", "postback_url", ":", "campaign", ".", "dig", "(", ":pixel_info", ",", ":postback_url", ")", "||", "''", ",", "redirect_domain", ":", "campaign", ".", "fetch", "(", ":redirect_domain", ",", "''", ")", ",", "test_link", ":", "campaign", "[", ":test_link", "]", "||", "''", ",", "unique_key_hash", ":", "campaign", ".", "dig", "(", ":pixel_info", ",", ":hash_type", ",", ":hash_type_id", ")", "||", "'none'", ",", "third_party_name", ":", "campaign", ".", "fetch", "(", ":third_party_name", ",", "''", ")", ")", ".", "merge", "(", "opts", ")", "update", "(", "campaign_id", ",", "opts", ")", "nil", "end" ]
The default for `display_link_type_id` is "Fallback" in Cake, which doesn't have an ID and, hence, cannot be set via the API. In order to not change it, it has to be absent from the request.
[ "The", "default", "for", "display_link_type_id", "is", "Fallback", "in", "Cake", "which", "doesn", "t", "have", "an", "ID", "and", "hence", "cannot", "be", "set", "via", "the", "API", ".", "In", "order", "to", "not", "change", "it", "it", "has", "to", "be", "absent", "from", "the", "request", "." ]
1120e0f645cfbe8f74ad08038cc7d77d6dcf1d05
https://github.com/ad2games/soapy_cake/blob/1120e0f645cfbe8f74ad08038cc7d77d6dcf1d05/lib/soapy_cake/campaigns.rb#L60-L80
train
ManaManaFramework/manamana
lib/manamana/steps.rb
ManaMana.Steps.call
def call(step_name) vars = nil step = steps.find { |s| vars = s[:pattern].match(step_name) } raise "Undefined step '#{ step_name }'" unless step if vars.length > 1 step[:block].call(*vars[1..-1]) else step[:block].call end end
ruby
def call(step_name) vars = nil step = steps.find { |s| vars = s[:pattern].match(step_name) } raise "Undefined step '#{ step_name }'" unless step if vars.length > 1 step[:block].call(*vars[1..-1]) else step[:block].call end end
[ "def", "call", "(", "step_name", ")", "vars", "=", "nil", "step", "=", "steps", ".", "find", "{", "|", "s", "|", "vars", "=", "s", "[", ":pattern", "]", ".", "match", "(", "step_name", ")", "}", "raise", "\"Undefined step '#{ step_name }'\"", "unless", "step", "if", "vars", ".", "length", ">", "1", "step", "[", ":block", "]", ".", "call", "(", "*", "vars", "[", "1", "..", "-", "1", "]", ")", "else", "step", "[", ":block", "]", ".", "call", "end", "end" ]
The step_name variable below is a string that may or may not match the regex pattern of one of the hashes in the steps array.
[ "The", "step_name", "variable", "below", "is", "a", "string", "that", "may", "or", "may", "not", "match", "the", "regex", "pattern", "of", "one", "of", "the", "hashes", "in", "the", "steps", "array", "." ]
af7c0715c2b28d1220cfaee2a2fec8f008e37e36
https://github.com/ManaManaFramework/manamana/blob/af7c0715c2b28d1220cfaee2a2fec8f008e37e36/lib/manamana/steps.rb#L29-L40
train
martinemde/gitable
lib/gitable/uri.rb
Gitable.URI.equivalent?
def equivalent?(other_uri) other = Gitable::URI.parse_when_valid(other_uri) return false unless other return false unless normalized_host.to_s == other.normalized_host.to_s if github? || bitbucket? # github doesn't care about relative vs absolute paths in scp uris org_project == other.org_project else # if the path is absolute, we can assume it's the same for all users (so the user doesn't have to match). normalized_path.sub(/\/$/,'') == other.normalized_path.sub(/\/$/,'') && (path[0] == '/' || normalized_user == other.normalized_user) end end
ruby
def equivalent?(other_uri) other = Gitable::URI.parse_when_valid(other_uri) return false unless other return false unless normalized_host.to_s == other.normalized_host.to_s if github? || bitbucket? # github doesn't care about relative vs absolute paths in scp uris org_project == other.org_project else # if the path is absolute, we can assume it's the same for all users (so the user doesn't have to match). normalized_path.sub(/\/$/,'') == other.normalized_path.sub(/\/$/,'') && (path[0] == '/' || normalized_user == other.normalized_user) end end
[ "def", "equivalent?", "(", "other_uri", ")", "other", "=", "Gitable", "::", "URI", ".", "parse_when_valid", "(", "other_uri", ")", "return", "false", "unless", "other", "return", "false", "unless", "normalized_host", ".", "to_s", "==", "other", ".", "normalized_host", ".", "to_s", "if", "github?", "||", "bitbucket?", "org_project", "==", "other", ".", "org_project", "else", "normalized_path", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "==", "other", ".", "normalized_path", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "&&", "(", "path", "[", "0", "]", "==", "'/'", "||", "normalized_user", "==", "other", ".", "normalized_user", ")", "end", "end" ]
Detect if two URIs are equivalent versions of the same uri. When both uris are github repositories, uses a more lenient matching system is used that takes github's repository organization into account. For non-github URIs this method requires the two URIs to have the same host, equivalent paths, and either the same user or an absolute path. @return [Boolean] true if the URI probably indicates the same repository.
[ "Detect", "if", "two", "URIs", "are", "equivalent", "versions", "of", "the", "same", "uri", "." ]
5005bf9056b86c96373e92879a14083b667fe7be
https://github.com/martinemde/gitable/blob/5005bf9056b86c96373e92879a14083b667fe7be/lib/gitable/uri.rb#L199-L212
train
barcoo/rworkflow
lib/rworkflow/flow.rb
Rworkflow.Flow.counters!
def counters! the_counters = { processing: 0 } names = @lifecycle.states.keys results = RedisRds::Object.connection.multi do self.class::STATES_TERMINAL.each { |name| get_list(name).size } names.each { |name| get_list(name).size } @processing.getall end (self.class::STATES_TERMINAL + names).each do |name| the_counters[name] = results.shift.to_i end the_counters[:processing] = results.shift.reduce(0) { |sum, pair| sum + pair.last.to_i } return the_counters end
ruby
def counters! the_counters = { processing: 0 } names = @lifecycle.states.keys results = RedisRds::Object.connection.multi do self.class::STATES_TERMINAL.each { |name| get_list(name).size } names.each { |name| get_list(name).size } @processing.getall end (self.class::STATES_TERMINAL + names).each do |name| the_counters[name] = results.shift.to_i end the_counters[:processing] = results.shift.reduce(0) { |sum, pair| sum + pair.last.to_i } return the_counters end
[ "def", "counters!", "the_counters", "=", "{", "processing", ":", "0", "}", "names", "=", "@lifecycle", ".", "states", ".", "keys", "results", "=", "RedisRds", "::", "Object", ".", "connection", ".", "multi", "do", "self", ".", "class", "::", "STATES_TERMINAL", ".", "each", "{", "|", "name", "|", "get_list", "(", "name", ")", ".", "size", "}", "names", ".", "each", "{", "|", "name", "|", "get_list", "(", "name", ")", ".", "size", "}", "@processing", ".", "getall", "end", "(", "self", ".", "class", "::", "STATES_TERMINAL", "+", "names", ")", ".", "each", "do", "|", "name", "|", "the_counters", "[", "name", "]", "=", "results", ".", "shift", ".", "to_i", "end", "the_counters", "[", ":processing", "]", "=", "results", ".", "shift", ".", "reduce", "(", "0", ")", "{", "|", "sum", ",", "pair", "|", "sum", "+", "pair", ".", "last", ".", "to_i", "}", "return", "the_counters", "end" ]
fetches counters atomically
[ "fetches", "counters", "atomically" ]
1dccaabd47144c846e3d87e65c11ee056ae597a1
https://github.com/barcoo/rworkflow/blob/1dccaabd47144c846e3d87e65c11ee056ae597a1/lib/rworkflow/flow.rb#L107-L124
train
cbeer/kaminari_route_prefix
lib/kaminari_route_prefix/actionview/action_view_extension.rb
KaminariRoutePrefix.ActionViewExtension.link_to_previous_page
def link_to_previous_page(scope, name, options = {}, &block) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.prev_page.present?, name, prev_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'prev') do block.call if block end end
ruby
def link_to_previous_page(scope, name, options = {}, &block) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.prev_page.present?, name, prev_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'prev') do block.call if block end end
[ "def", "link_to_previous_page", "(", "scope", ",", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "prev_page", "=", "Kaminari", "::", "Helpers", "::", "PrevPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "link_to_if", "scope", ".", "prev_page", ".", "present?", ",", "name", ",", "prev_page", ".", "url", ",", "options", ".", "except", "(", ":params", ",", ":param_name", ")", ".", "reverse_merge", "(", ":rel", "=>", "'prev'", ")", "do", "block", ".", "call", "if", "block", "end", "end" ]
A simple "Twitter like" pagination link that creates a link to the previous page. ==== Examples Basic usage: <%= link_to_previous_page @items, 'Previous Page' %> Ajax: <%= link_to_previous_page @items, 'Previous Page', :remote => true %> By default, it renders nothing if there are no more results on the previous page. You can customize this output by passing a block. <%= link_to_previous_page @users, 'Previous Page' do %> <span>At the Beginning</span> <% end %>
[ "A", "simple", "Twitter", "like", "pagination", "link", "that", "creates", "a", "link", "to", "the", "previous", "page", "." ]
70f955e56a777272b033c1ee623ed7269e12d03b
https://github.com/cbeer/kaminari_route_prefix/blob/70f955e56a777272b033c1ee623ed7269e12d03b/lib/kaminari_route_prefix/actionview/action_view_extension.rb#L42-L48
train
cbeer/kaminari_route_prefix
lib/kaminari_route_prefix/actionview/action_view_extension.rb
KaminariRoutePrefix.ActionViewExtension.link_to_next_page
def link_to_next_page(scope, name, options = {}, &block) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.next_page.present?, name, next_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'next') do block.call if block end end
ruby
def link_to_next_page(scope, name, options = {}, &block) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.next_page.present?, name, next_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'next') do block.call if block end end
[ "def", "link_to_next_page", "(", "scope", ",", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "next_page", "=", "Kaminari", "::", "Helpers", "::", "NextPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "link_to_if", "scope", ".", "next_page", ".", "present?", ",", "name", ",", "next_page", ".", "url", ",", "options", ".", "except", "(", ":params", ",", ":param_name", ")", ".", "reverse_merge", "(", ":rel", "=>", "'next'", ")", "do", "block", ".", "call", "if", "block", "end", "end" ]
A simple "Twitter like" pagination link that creates a link to the next page. ==== Examples Basic usage: <%= link_to_next_page @items, 'Next Page' %> Ajax: <%= link_to_next_page @items, 'Next Page', :remote => true %> By default, it renders nothing if there are no more results on the next page. You can customize this output by passing a block. <%= link_to_next_page @users, 'Next Page' do %> <span>No More Pages</span> <% end %>
[ "A", "simple", "Twitter", "like", "pagination", "link", "that", "creates", "a", "link", "to", "the", "next", "page", "." ]
70f955e56a777272b033c1ee623ed7269e12d03b
https://github.com/cbeer/kaminari_route_prefix/blob/70f955e56a777272b033c1ee623ed7269e12d03b/lib/kaminari_route_prefix/actionview/action_view_extension.rb#L67-L73
train
cbeer/kaminari_route_prefix
lib/kaminari_route_prefix/actionview/action_view_extension.rb
KaminariRoutePrefix.ActionViewExtension.rel_next_prev_link_tags
def rel_next_prev_link_tags(scope, options = {}) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) output = String.new output << tag(:link, :rel => "next", :href => next_page.url) if scope.next_page.present? output << tag(:link, :rel => "prev", :href => prev_page.url) if scope.prev_page.present? output.html_safe end
ruby
def rel_next_prev_link_tags(scope, options = {}) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) output = String.new output << tag(:link, :rel => "next", :href => next_page.url) if scope.next_page.present? output << tag(:link, :rel => "prev", :href => prev_page.url) if scope.prev_page.present? output.html_safe end
[ "def", "rel_next_prev_link_tags", "(", "scope", ",", "options", "=", "{", "}", ")", "next_page", "=", "Kaminari", "::", "Helpers", "::", "NextPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "prev_page", "=", "Kaminari", "::", "Helpers", "::", "PrevPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "output", "=", "String", ".", "new", "output", "<<", "tag", "(", ":link", ",", ":rel", "=>", "\"next\"", ",", ":href", "=>", "next_page", ".", "url", ")", "if", "scope", ".", "next_page", ".", "present?", "output", "<<", "tag", "(", ":link", ",", ":rel", "=>", "\"prev\"", ",", ":href", "=>", "prev_page", ".", "url", ")", "if", "scope", ".", "prev_page", ".", "present?", "output", ".", "html_safe", "end" ]
Renders rel="next" and rel="prev" links to be used in the head. ==== Examples Basic usage: In head: <head> <title>My Website</title> <%= yield :head %> </head> Somewhere in body: <% content_for :head do %> <%= rel_next_prev_link_tags @items %> <% end %> #-> <link rel="next" href="/items/page/3" /><link rel="prev" href="/items/page/1" />
[ "Renders", "rel", "=", "next", "and", "rel", "=", "prev", "links", "to", "be", "used", "in", "the", "head", "." ]
70f955e56a777272b033c1ee623ed7269e12d03b
https://github.com/cbeer/kaminari_route_prefix/blob/70f955e56a777272b033c1ee623ed7269e12d03b/lib/kaminari_route_prefix/actionview/action_view_extension.rb#L122-L130
train
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.ratio
def ratio(rgb1, rgb2) raise InvalidColorError, rgb1 unless valid_rgb?(rgb1) raise InvalidColorError, rgb2 unless valid_rgb?(rgb2) srgb1 = rgb_to_srgba(rgb1) srgb2 = rgb_to_srgba(rgb2) l1 = srgb_lightness(srgb1) l2 = srgb_lightness(srgb2) l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05) end
ruby
def ratio(rgb1, rgb2) raise InvalidColorError, rgb1 unless valid_rgb?(rgb1) raise InvalidColorError, rgb2 unless valid_rgb?(rgb2) srgb1 = rgb_to_srgba(rgb1) srgb2 = rgb_to_srgba(rgb2) l1 = srgb_lightness(srgb1) l2 = srgb_lightness(srgb2) l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05) end
[ "def", "ratio", "(", "rgb1", ",", "rgb2", ")", "raise", "InvalidColorError", ",", "rgb1", "unless", "valid_rgb?", "(", "rgb1", ")", "raise", "InvalidColorError", ",", "rgb2", "unless", "valid_rgb?", "(", "rgb2", ")", "srgb1", "=", "rgb_to_srgba", "(", "rgb1", ")", "srgb2", "=", "rgb_to_srgba", "(", "rgb2", ")", "l1", "=", "srgb_lightness", "(", "srgb1", ")", "l2", "=", "srgb_lightness", "(", "srgb2", ")", "l1", ">", "l2", "?", "(", "l1", "+", "0.05", ")", "/", "(", "l2", "+", "0.05", ")", ":", "(", "l2", "+", "0.05", ")", "/", "(", "l1", "+", "0.05", ")", "end" ]
Calculate contast ratio beetween RGB1 and RGB2.
[ "Calculate", "contast", "ratio", "beetween", "RGB1", "and", "RGB2", "." ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L17-L28
train
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.relative_luminance
def relative_luminance(rgb) raise InvalidColorError, rgb unless valid_rgb?(rgb) srgb = rgb_to_srgba(rgb) srgb_lightness(srgb) end
ruby
def relative_luminance(rgb) raise InvalidColorError, rgb unless valid_rgb?(rgb) srgb = rgb_to_srgba(rgb) srgb_lightness(srgb) end
[ "def", "relative_luminance", "(", "rgb", ")", "raise", "InvalidColorError", ",", "rgb", "unless", "valid_rgb?", "(", "rgb", ")", "srgb", "=", "rgb_to_srgba", "(", "rgb", ")", "srgb_lightness", "(", "srgb", ")", "end" ]
Calculate the relative luminance for an rgb color
[ "Calculate", "the", "relative", "luminance", "for", "an", "rgb", "color" ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L31-L36
train
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.rgb_to_srgba
def rgb_to_srgba(rgb) rgb << rgb if rgb.size == 3 [ rgb.slice(0,2).to_i(16) / 255.0, rgb.slice(2,2).to_i(16) / 255.0, rgb.slice(4,2).to_i(16) / 255.0 ] end
ruby
def rgb_to_srgba(rgb) rgb << rgb if rgb.size == 3 [ rgb.slice(0,2).to_i(16) / 255.0, rgb.slice(2,2).to_i(16) / 255.0, rgb.slice(4,2).to_i(16) / 255.0 ] end
[ "def", "rgb_to_srgba", "(", "rgb", ")", "rgb", "<<", "rgb", "if", "rgb", ".", "size", "==", "3", "[", "rgb", ".", "slice", "(", "0", ",", "2", ")", ".", "to_i", "(", "16", ")", "/", "255.0", ",", "rgb", ".", "slice", "(", "2", ",", "2", ")", ".", "to_i", "(", "16", ")", "/", "255.0", ",", "rgb", ".", "slice", "(", "4", ",", "2", ")", ".", "to_i", "(", "16", ")", "/", "255.0", "]", "end" ]
Convert RGB color to sRGB.
[ "Convert", "RGB", "color", "to", "sRGB", "." ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L41-L48
train
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.srgb_lightness
def srgb_lightness(srgb) r, g, b = srgb 0.2126 * (r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4) + 0.7152 * (g <= 0.03928 ? g / 12.92 : ((g + 0.055) / 1.055) ** 2.4) + 0.0722 * (b <= 0.03928 ? b / 12.92 : ((b + 0.055) / 1.055) ** 2.4) end
ruby
def srgb_lightness(srgb) r, g, b = srgb 0.2126 * (r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4) + 0.7152 * (g <= 0.03928 ? g / 12.92 : ((g + 0.055) / 1.055) ** 2.4) + 0.0722 * (b <= 0.03928 ? b / 12.92 : ((b + 0.055) / 1.055) ** 2.4) end
[ "def", "srgb_lightness", "(", "srgb", ")", "r", ",", "g", ",", "b", "=", "srgb", "0.2126", "*", "(", "r", "<=", "0.03928", "?", "r", "/", "12.92", ":", "(", "(", "r", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", ")", "+", "0.7152", "*", "(", "g", "<=", "0.03928", "?", "g", "/", "12.92", ":", "(", "(", "g", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", ")", "+", "0.0722", "*", "(", "b", "<=", "0.03928", "?", "b", "/", "12.92", ":", "(", "(", "b", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", ")", "end" ]
Calculate lightness for sRGB color.
[ "Calculate", "lightness", "for", "sRGB", "color", "." ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L51-L56
train
mpalmer/frankenstein
lib/frankenstein/server.rb
Frankenstein.Server.run
def run @op_mutex.synchronize do return AlreadyRunningError if @server @server_thread = Thread.new do @op_mutex.synchronize do begin wrapped_logger = Frankenstein::Server::WEBrickLogger.new(logger: @logger, progname: "Frankenstein::Server") @server = WEBrick::HTTPServer.new(Logger: wrapped_logger, BindAddress: nil, Port: @port, AccessLog: [[wrapped_logger, WEBrick::AccessLog::COMMON_LOG_FORMAT]]) @server.mount "/", Rack::Handler::WEBrick, app rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: ensure @op_cv.signal end end begin @server.start if @server rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: end end end @op_mutex.synchronize { @op_cv.wait(@op_mutex) until @server } end
ruby
def run @op_mutex.synchronize do return AlreadyRunningError if @server @server_thread = Thread.new do @op_mutex.synchronize do begin wrapped_logger = Frankenstein::Server::WEBrickLogger.new(logger: @logger, progname: "Frankenstein::Server") @server = WEBrick::HTTPServer.new(Logger: wrapped_logger, BindAddress: nil, Port: @port, AccessLog: [[wrapped_logger, WEBrick::AccessLog::COMMON_LOG_FORMAT]]) @server.mount "/", Rack::Handler::WEBrick, app rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: ensure @op_cv.signal end end begin @server.start if @server rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: end end end @op_mutex.synchronize { @op_cv.wait(@op_mutex) until @server } end
[ "def", "run", "@op_mutex", ".", "synchronize", "do", "return", "AlreadyRunningError", "if", "@server", "@server_thread", "=", "Thread", ".", "new", "do", "@op_mutex", ".", "synchronize", "do", "begin", "wrapped_logger", "=", "Frankenstein", "::", "Server", "::", "WEBrickLogger", ".", "new", "(", "logger", ":", "@logger", ",", "progname", ":", "\"Frankenstein::Server\"", ")", "@server", "=", "WEBrick", "::", "HTTPServer", ".", "new", "(", "Logger", ":", "wrapped_logger", ",", "BindAddress", ":", "nil", ",", "Port", ":", "@port", ",", "AccessLog", ":", "[", "[", "wrapped_logger", ",", "WEBrick", "::", "AccessLog", "::", "COMMON_LOG_FORMAT", "]", "]", ")", "@server", ".", "mount", "\"/\"", ",", "Rack", "::", "Handler", "::", "WEBrick", ",", "app", "rescue", "=>", "ex", "@logger", ".", "fatal", "(", "\"Frankenstein::Server#run\"", ")", "{", "(", "[", "\"Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})\"", "]", "+", "ex", ".", "backtrace", ")", ".", "join", "(", "\"\\n \"", ")", "}", "ensure", "@op_cv", ".", "signal", "end", "end", "begin", "@server", ".", "start", "if", "@server", "rescue", "=>", "ex", "@logger", ".", "fatal", "(", "\"Frankenstein::Server#run\"", ")", "{", "(", "[", "\"Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})\"", "]", "+", "ex", ".", "backtrace", ")", ".", "join", "(", "\"\\n \"", ")", "}", "end", "end", "end", "@op_mutex", ".", "synchronize", "{", "@op_cv", ".", "wait", "(", "@op_mutex", ")", "until", "@server", "}", "end" ]
Create a new server instance. @param port [Integer] the TCP to listen on. @param logger [Logger] send log messages from WEBrick to this logger. If not specified, all log messages will be silently eaten. @param metrics_prefix [#to_s] The prefix to apply to the metrics exposed instrumenting the metrics server itself. @param registry [Prometheus::Client::Registry] if you want to use an existing metrics registry for this server, pass it in here. Otherwise, a new one will be created for you, and be made available via #registry. Start the server instance running in a separate thread. This method returns once the server is just about ready to start serving requests.
[ "Create", "a", "new", "server", "instance", "." ]
1bbd9835233d0672af020da405ea1b29d55d105e
https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/server.rb#L74-L104
train
localmed/outbox
lib/outbox/message_types.rb
Outbox.MessageTypes.assign_message_type_values
def assign_message_type_values(values) values.each do |key, value| public_send(key, value) if respond_to?(key) end end
ruby
def assign_message_type_values(values) values.each do |key, value| public_send(key, value) if respond_to?(key) end end
[ "def", "assign_message_type_values", "(", "values", ")", "values", ".", "each", "do", "|", "key", ",", "value", "|", "public_send", "(", "key", ",", "value", ")", "if", "respond_to?", "(", "key", ")", "end", "end" ]
Assign the given hash where each key is a message type and the value is a hash of options for that message type.
[ "Assign", "the", "given", "hash", "where", "each", "key", "is", "a", "message", "type", "and", "the", "value", "is", "a", "hash", "of", "options", "for", "that", "message", "type", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_types.rb#L101-L105
train
mbj/esearch
lib/esearch/request.rb
Esearch.Request.run
def run(connection) connection.public_send(verb, path) do |request| request.params = params request.headers[:content_type] = Command::JSON_CONTENT_TYPE request.body = MultiJson.dump(body) end end
ruby
def run(connection) connection.public_send(verb, path) do |request| request.params = params request.headers[:content_type] = Command::JSON_CONTENT_TYPE request.body = MultiJson.dump(body) end end
[ "def", "run", "(", "connection", ")", "connection", ".", "public_send", "(", "verb", ",", "path", ")", "do", "|", "request", "|", "request", ".", "params", "=", "params", "request", ".", "headers", "[", ":content_type", "]", "=", "Command", "::", "JSON_CONTENT_TYPE", "request", ".", "body", "=", "MultiJson", ".", "dump", "(", "body", ")", "end", "end" ]
Run request on connection @param [Faraday::Connection] @return [Faraday::Response] @api private
[ "Run", "request", "on", "connection" ]
45a1dcb495d650e450085c2240a280fc8082cc34
https://github.com/mbj/esearch/blob/45a1dcb495d650e450085c2240a280fc8082cc34/lib/esearch/request.rb#L77-L83
train
G5/modelish
lib/modelish/validations.rb
Modelish.Validations.validate
def validate errors = {} call_validators do |name, message| errors[name] ||= [] errors[name] << to_error(message) end errors end
ruby
def validate errors = {} call_validators do |name, message| errors[name] ||= [] errors[name] << to_error(message) end errors end
[ "def", "validate", "errors", "=", "{", "}", "call_validators", "do", "|", "name", ",", "message", "|", "errors", "[", "name", "]", "||=", "[", "]", "errors", "[", "name", "]", "<<", "to_error", "(", "message", ")", "end", "errors", "end" ]
Validates all properties based on configured validators. @return [Hash<Symbol,Array>] map of errors where key is the property name and value is the list of errors @see ClassMethods#add_validator
[ "Validates", "all", "properties", "based", "on", "configured", "validators", "." ]
42cb6e07dafd794e0180b858a36fb7b5a8e424b6
https://github.com/G5/modelish/blob/42cb6e07dafd794e0180b858a36fb7b5a8e424b6/lib/modelish/validations.rb#L17-L26
train
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.load_capabilities
def load_capabilities(caps) device = @server.device_data unless device.nil? caps[:caps][:udid] = device.fetch('udid', nil) caps[:caps][:platformVersion] = device.fetch('os', caps[:caps][:platformVersion]) caps[:caps][:deviceName] = device.fetch('name', caps[:caps][:deviceName]) caps[:caps][:wdaLocalPort] = device.fetch('wdaPort', nil) caps[:caps][:avd] = device.fetch('avd', nil) end caps[:appium_lib][:server_url] = ENV['SERVER_URL'] caps end
ruby
def load_capabilities(caps) device = @server.device_data unless device.nil? caps[:caps][:udid] = device.fetch('udid', nil) caps[:caps][:platformVersion] = device.fetch('os', caps[:caps][:platformVersion]) caps[:caps][:deviceName] = device.fetch('name', caps[:caps][:deviceName]) caps[:caps][:wdaLocalPort] = device.fetch('wdaPort', nil) caps[:caps][:avd] = device.fetch('avd', nil) end caps[:appium_lib][:server_url] = ENV['SERVER_URL'] caps end
[ "def", "load_capabilities", "(", "caps", ")", "device", "=", "@server", ".", "device_data", "unless", "device", ".", "nil?", "caps", "[", ":caps", "]", "[", ":udid", "]", "=", "device", ".", "fetch", "(", "'udid'", ",", "nil", ")", "caps", "[", ":caps", "]", "[", ":platformVersion", "]", "=", "device", ".", "fetch", "(", "'os'", ",", "caps", "[", ":caps", "]", "[", ":platformVersion", "]", ")", "caps", "[", ":caps", "]", "[", ":deviceName", "]", "=", "device", ".", "fetch", "(", "'name'", ",", "caps", "[", ":caps", "]", "[", ":deviceName", "]", ")", "caps", "[", ":caps", "]", "[", ":wdaLocalPort", "]", "=", "device", ".", "fetch", "(", "'wdaPort'", ",", "nil", ")", "caps", "[", ":caps", "]", "[", ":avd", "]", "=", "device", ".", "fetch", "(", "'avd'", ",", "nil", ")", "end", "caps", "[", ":appium_lib", "]", "[", ":server_url", "]", "=", "ENV", "[", "'SERVER_URL'", "]", "caps", "end" ]
Load capabilities based on current device data
[ "Load", "capabilities", "based", "on", "current", "device", "data" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L26-L38
train
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.initialize_appium
def initialize_appium(**args) platform = args[:platform] caps = args[:caps] platform = ENV['platform'] if platform.nil? if platform.nil? puts 'Platform not found in environment variable' exit end caps = Appium.load_appium_txt file: File.new("#{Dir.pwd}/appium-#{platform}.txt") if caps.nil? if caps.nil? puts 'No capabilities specified' exit end puts 'Preparing to load capabilities' capabilities = load_capabilities(caps) puts 'Loaded capabilities' @driver = Appium::Driver.new(capabilities, true) puts 'Created driver' Appium.promote_appium_methods Object Appium.promote_appium_methods RSpec::Core::ExampleGroup @driver end
ruby
def initialize_appium(**args) platform = args[:platform] caps = args[:caps] platform = ENV['platform'] if platform.nil? if platform.nil? puts 'Platform not found in environment variable' exit end caps = Appium.load_appium_txt file: File.new("#{Dir.pwd}/appium-#{platform}.txt") if caps.nil? if caps.nil? puts 'No capabilities specified' exit end puts 'Preparing to load capabilities' capabilities = load_capabilities(caps) puts 'Loaded capabilities' @driver = Appium::Driver.new(capabilities, true) puts 'Created driver' Appium.promote_appium_methods Object Appium.promote_appium_methods RSpec::Core::ExampleGroup @driver end
[ "def", "initialize_appium", "(", "**", "args", ")", "platform", "=", "args", "[", ":platform", "]", "caps", "=", "args", "[", ":caps", "]", "platform", "=", "ENV", "[", "'platform'", "]", "if", "platform", ".", "nil?", "if", "platform", ".", "nil?", "puts", "'Platform not found in environment variable'", "exit", "end", "caps", "=", "Appium", ".", "load_appium_txt", "file", ":", "File", ".", "new", "(", "\"#{Dir.pwd}/appium-#{platform}.txt\"", ")", "if", "caps", ".", "nil?", "if", "caps", ".", "nil?", "puts", "'No capabilities specified'", "exit", "end", "puts", "'Preparing to load capabilities'", "capabilities", "=", "load_capabilities", "(", "caps", ")", "puts", "'Loaded capabilities'", "@driver", "=", "Appium", "::", "Driver", ".", "new", "(", "capabilities", ",", "true", ")", "puts", "'Created driver'", "Appium", ".", "promote_appium_methods", "Object", "Appium", ".", "promote_appium_methods", "RSpec", "::", "Core", "::", "ExampleGroup", "@driver", "end" ]
Load appium text file if available and attempt to start the driver platform is either android or ios, otherwise read from ENV caps is mapping of appium capabilities
[ "Load", "appium", "text", "file", "if", "available", "and", "attempt", "to", "start", "the", "driver", "platform", "is", "either", "android", "or", "ios", "otherwise", "read", "from", "ENV", "caps", "is", "mapping", "of", "appium", "capabilities" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L43-L68
train
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.setup_signal_handler
def setup_signal_handler(ios_pid = nil, android_pid = nil) Signal.trap('INT') do Process.kill('INT', ios_pid) unless ios_pid.nil? Process.kill('INT', android_pid) unless android_pid.nil? # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' # Terminate ourself exit 1 end end
ruby
def setup_signal_handler(ios_pid = nil, android_pid = nil) Signal.trap('INT') do Process.kill('INT', ios_pid) unless ios_pid.nil? Process.kill('INT', android_pid) unless android_pid.nil? # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' # Terminate ourself exit 1 end end
[ "def", "setup_signal_handler", "(", "ios_pid", "=", "nil", ",", "android_pid", "=", "nil", ")", "Signal", ".", "trap", "(", "'INT'", ")", "do", "Process", ".", "kill", "(", "'INT'", ",", "ios_pid", ")", "unless", "ios_pid", ".", "nil?", "Process", ".", "kill", "(", "'INT'", ",", "android_pid", ")", "unless", "android_pid", ".", "nil?", "kill_process", "'appium'", "kill_process", "'selenium'", "exit", "1", "end", "end" ]
Define a signal handler for SIGINT
[ "Define", "a", "signal", "handler", "for", "SIGINT" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L71-L83
train
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.execute_specs
def execute_specs(platform, threads, spec_path, parallel = false) command = if parallel "platform=#{platform} parallel_rspec -n #{threads} #{spec_path}" else "platform=#{platform} rspec #{spec_path} --tag #{platform}" end puts "Executing #{command}" exec command end
ruby
def execute_specs(platform, threads, spec_path, parallel = false) command = if parallel "platform=#{platform} parallel_rspec -n #{threads} #{spec_path}" else "platform=#{platform} rspec #{spec_path} --tag #{platform}" end puts "Executing #{command}" exec command end
[ "def", "execute_specs", "(", "platform", ",", "threads", ",", "spec_path", ",", "parallel", "=", "false", ")", "command", "=", "if", "parallel", "\"platform=#{platform} parallel_rspec -n #{threads} #{spec_path}\"", "else", "\"platform=#{platform} rspec #{spec_path} --tag #{platform}\"", "end", "puts", "\"Executing #{command}\"", "exec", "command", "end" ]
Decide whether to execute specs in parallel or not @param [String] platform @param [int] threads @param [String] spec_path @param [boolean] parallel
[ "Decide", "whether", "to", "execute", "specs", "in", "parallel", "or", "not" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L90-L99
train
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.setup
def setup(platform, file_path, threads, parallel) spec_path = 'spec/' spec_path = file_path.to_s unless file_path.nil? puts "SPEC PATH:#{spec_path}" unless %w[ios android].include? platform puts "Invalid platform #{platform}" exit end execute_specs platform, threads, spec_path, parallel end
ruby
def setup(platform, file_path, threads, parallel) spec_path = 'spec/' spec_path = file_path.to_s unless file_path.nil? puts "SPEC PATH:#{spec_path}" unless %w[ios android].include? platform puts "Invalid platform #{platform}" exit end execute_specs platform, threads, spec_path, parallel end
[ "def", "setup", "(", "platform", ",", "file_path", ",", "threads", ",", "parallel", ")", "spec_path", "=", "'spec/'", "spec_path", "=", "file_path", ".", "to_s", "unless", "file_path", ".", "nil?", "puts", "\"SPEC PATH:#{spec_path}\"", "unless", "%w[", "ios", "android", "]", ".", "include?", "platform", "puts", "\"Invalid platform #{platform}\"", "exit", "end", "execute_specs", "platform", ",", "threads", ",", "spec_path", ",", "parallel", "end" ]
Define Spec path, validate platform and execute specs
[ "Define", "Spec", "path", "validate", "platform", "and", "execute", "specs" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L102-L113
train
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.start
def start(**args) platform = args[:platform] file_path = args[:file_path] # Validate environment variable if ENV['platform'].nil? if platform.nil? puts 'No platform detected in environment and none passed to start...' exit end ENV['platform'] = platform end sleep 3 # Appium ports ios_port = 4725 android_port = 4727 default_port = 4725 platform = ENV['platform'] # Platform is required check_platform platform platform = platform.downcase ENV['BASE_DIR'] = Dir.pwd # Check if multithreaded for distributing tests across devices threads = ENV['THREADS'].nil? ? 1 : ENV['THREADS'].to_i parallel = threads != 1 if platform != 'all' pid = fork do if !parallel ENV['SERVER_URL'] = "http://0.0.0.0:#{default_port}/wd/hub" @server.start_single_appium platform, default_port else ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' @server.launch_hub_and_nodes platform end setup(platform, file_path, threads, parallel) end puts "PID: #{pid}" setup_signal_handler(pid) Process.waitpid(pid) else # Spin off 2 sub-processes, one for Android connections and another for iOS, # each with redefining environment variables for the server url, number of threads and platform ios_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start iOS' @server.launch_hub_and_nodes 'ios' else ENV['SERVER_URL'] = "http://0.0.0.0:#{ios_port}/wd/hub" puts 'Start iOS' @server.start_single_appium 'ios', ios_port end setup('ios', file_path, threads, parallel) end android_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start Android' @server.launch_hub_and_nodes 'android' else ENV['SERVER_URL'] = "http://0.0.0.0:#{android_port}/wd/hub" puts 'Start Android' @server.start_single_appium 'android', android_port end setup('android', file_path, threads, parallel) end puts "iOS PID: #{ios_pid}\nAndroid PID: #{android_pid}" setup_signal_handler(ios_pid, android_pid) [ios_pid, android_pid].each { |process_pid| Process.waitpid(process_pid) } end # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' end
ruby
def start(**args) platform = args[:platform] file_path = args[:file_path] # Validate environment variable if ENV['platform'].nil? if platform.nil? puts 'No platform detected in environment and none passed to start...' exit end ENV['platform'] = platform end sleep 3 # Appium ports ios_port = 4725 android_port = 4727 default_port = 4725 platform = ENV['platform'] # Platform is required check_platform platform platform = platform.downcase ENV['BASE_DIR'] = Dir.pwd # Check if multithreaded for distributing tests across devices threads = ENV['THREADS'].nil? ? 1 : ENV['THREADS'].to_i parallel = threads != 1 if platform != 'all' pid = fork do if !parallel ENV['SERVER_URL'] = "http://0.0.0.0:#{default_port}/wd/hub" @server.start_single_appium platform, default_port else ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' @server.launch_hub_and_nodes platform end setup(platform, file_path, threads, parallel) end puts "PID: #{pid}" setup_signal_handler(pid) Process.waitpid(pid) else # Spin off 2 sub-processes, one for Android connections and another for iOS, # each with redefining environment variables for the server url, number of threads and platform ios_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start iOS' @server.launch_hub_and_nodes 'ios' else ENV['SERVER_URL'] = "http://0.0.0.0:#{ios_port}/wd/hub" puts 'Start iOS' @server.start_single_appium 'ios', ios_port end setup('ios', file_path, threads, parallel) end android_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start Android' @server.launch_hub_and_nodes 'android' else ENV['SERVER_URL'] = "http://0.0.0.0:#{android_port}/wd/hub" puts 'Start Android' @server.start_single_appium 'android', android_port end setup('android', file_path, threads, parallel) end puts "iOS PID: #{ios_pid}\nAndroid PID: #{android_pid}" setup_signal_handler(ios_pid, android_pid) [ios_pid, android_pid].each { |process_pid| Process.waitpid(process_pid) } end # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' end
[ "def", "start", "(", "**", "args", ")", "platform", "=", "args", "[", ":platform", "]", "file_path", "=", "args", "[", ":file_path", "]", "if", "ENV", "[", "'platform'", "]", ".", "nil?", "if", "platform", ".", "nil?", "puts", "'No platform detected in environment and none passed to start...'", "exit", "end", "ENV", "[", "'platform'", "]", "=", "platform", "end", "sleep", "3", "ios_port", "=", "4725", "android_port", "=", "4727", "default_port", "=", "4725", "platform", "=", "ENV", "[", "'platform'", "]", "check_platform", "platform", "platform", "=", "platform", ".", "downcase", "ENV", "[", "'BASE_DIR'", "]", "=", "Dir", ".", "pwd", "threads", "=", "ENV", "[", "'THREADS'", "]", ".", "nil?", "?", "1", ":", "ENV", "[", "'THREADS'", "]", ".", "to_i", "parallel", "=", "threads", "!=", "1", "if", "platform", "!=", "'all'", "pid", "=", "fork", "do", "if", "!", "parallel", "ENV", "[", "'SERVER_URL'", "]", "=", "\"http://0.0.0.0:#{default_port}/wd/hub\"", "@server", ".", "start_single_appium", "platform", ",", "default_port", "else", "ENV", "[", "'SERVER_URL'", "]", "=", "'http://localhost:4444/wd/hub'", "@server", ".", "launch_hub_and_nodes", "platform", "end", "setup", "(", "platform", ",", "file_path", ",", "threads", ",", "parallel", ")", "end", "puts", "\"PID: #{pid}\"", "setup_signal_handler", "(", "pid", ")", "Process", ".", "waitpid", "(", "pid", ")", "else", "ios_pid", "=", "fork", "do", "ENV", "[", "'THREADS'", "]", "=", "threads", ".", "to_s", "if", "parallel", "ENV", "[", "'SERVER_URL'", "]", "=", "'http://localhost:4444/wd/hub'", "puts", "'Start iOS'", "@server", ".", "launch_hub_and_nodes", "'ios'", "else", "ENV", "[", "'SERVER_URL'", "]", "=", "\"http://0.0.0.0:#{ios_port}/wd/hub\"", "puts", "'Start iOS'", "@server", ".", "start_single_appium", "'ios'", ",", "ios_port", "end", "setup", "(", "'ios'", ",", "file_path", ",", "threads", ",", "parallel", ")", "end", "android_pid", "=", "fork", "do", "ENV", "[", "'THREADS'", "]", "=", "threads", ".", "to_s", "if", "parallel", "ENV", "[", "'SERVER_URL'", "]", "=", "'http://localhost:4444/wd/hub'", "puts", "'Start Android'", "@server", ".", "launch_hub_and_nodes", "'android'", "else", "ENV", "[", "'SERVER_URL'", "]", "=", "\"http://0.0.0.0:#{android_port}/wd/hub\"", "puts", "'Start Android'", "@server", ".", "start_single_appium", "'android'", ",", "android_port", "end", "setup", "(", "'android'", ",", "file_path", ",", "threads", ",", "parallel", ")", "end", "puts", "\"iOS PID: #{ios_pid}\\nAndroid PID: #{android_pid}\"", "setup_signal_handler", "(", "ios_pid", ",", "android_pid", ")", "[", "ios_pid", ",", "android_pid", "]", ".", "each", "{", "|", "process_pid", "|", "Process", ".", "waitpid", "(", "process_pid", ")", "}", "end", "kill_process", "'appium'", "kill_process", "'selenium'", "end" ]
Fire necessary appium server instances and Selenium grid server if needed.
[ "Fire", "necessary", "appium", "server", "instances", "and", "Selenium", "grid", "server", "if", "needed", "." ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L128-L214
train
weenhanceit/gaapi
lib/gaapi/query.rb
GAAPI.Query.execute
def execute uri = URI.parse("https://analyticsreporting.googleapis.com/v4/reports:batchGet") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true # https.set_debug_output($stdout) request = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{access_token}") request.body = query.to_json Response.new(https.request(request)) end
ruby
def execute uri = URI.parse("https://analyticsreporting.googleapis.com/v4/reports:batchGet") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true # https.set_debug_output($stdout) request = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{access_token}") request.body = query.to_json Response.new(https.request(request)) end
[ "def", "execute", "uri", "=", "URI", ".", "parse", "(", "\"https://analyticsreporting.googleapis.com/v4/reports:batchGet\"", ")", "https", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "https", ".", "use_ssl", "=", "true", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ",", "\"Content-Type\"", "=>", "\"application/json\"", ",", "\"Authorization\"", "=>", "\"Bearer #{access_token}\"", ")", "request", ".", "body", "=", "query", ".", "to_json", "Response", ".", "new", "(", "https", ".", "request", "(", "request", ")", ")", "end" ]
Create a Query object. @param access_token [String] A valid access token with which to make a request to the specified View ID. @param end_date [Date, String] The end date for the report. @param query_string [String, Hash, JSON] The query in JSON format. @param start_date [Date, String] The start date for the report. @param view_id [String] The view ID of the property for which to submit the query. Send the requested query to Google Analytics and return the response. @return [GAAPI::Response] The response from the request.
[ "Create", "a", "Query", "object", "." ]
20d25bd06b2e0cccc86ca1ea1baaac6be045355a
https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/query.rb#L34-L44
train
weenhanceit/gaapi
lib/gaapi/query.rb
GAAPI.Query.stringify_keys
def stringify_keys(object) case object when Hash object.each_with_object({}) do |(key, value), result| result[key.to_s] = stringify_keys(value) end when Array object.map { |e| stringify_keys(e) } else object end end
ruby
def stringify_keys(object) case object when Hash object.each_with_object({}) do |(key, value), result| result[key.to_s] = stringify_keys(value) end when Array object.map { |e| stringify_keys(e) } else object end end
[ "def", "stringify_keys", "(", "object", ")", "case", "object", "when", "Hash", "object", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "result", "|", "result", "[", "key", ".", "to_s", "]", "=", "stringify_keys", "(", "value", ")", "end", "when", "Array", "object", ".", "map", "{", "|", "e", "|", "stringify_keys", "(", "e", ")", "}", "else", "object", "end", "end" ]
The keys have to be strings to get converted to a GA query. Adapted from Rails.
[ "The", "keys", "have", "to", "be", "strings", "to", "get", "converted", "to", "a", "GA", "query", ".", "Adapted", "from", "Rails", "." ]
20d25bd06b2e0cccc86ca1ea1baaac6be045355a
https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/query.rb#L52-L63
train
mbj/esearch
lib/esearch/command.rb
Esearch.Command.raise_status_error
def raise_status_error message = format( 'expected response stati: %s but got: %s, remote message: %s', expected_response_stati, response.status, remote_message.inspect ) fail ProtocolError, message end
ruby
def raise_status_error message = format( 'expected response stati: %s but got: %s, remote message: %s', expected_response_stati, response.status, remote_message.inspect ) fail ProtocolError, message end
[ "def", "raise_status_error", "message", "=", "format", "(", "'expected response stati: %s but got: %s, remote message: %s'", ",", "expected_response_stati", ",", "response", ".", "status", ",", "remote_message", ".", "inspect", ")", "fail", "ProtocolError", ",", "message", "end" ]
Raise remote status error @return [undefined] @api private
[ "Raise", "remote", "status", "error" ]
45a1dcb495d650e450085c2240a280fc8082cc34
https://github.com/mbj/esearch/blob/45a1dcb495d650e450085c2240a280fc8082cc34/lib/esearch/command.rb#L116-L124
train
henkm/shake-the-counter
lib/shake_the_counter/performance.rb
ShakeTheCounter.Performance.sections
def sections return @sections if @sections @sections = [] path = "event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}" result = event.client.call(path, http_method: :get) for section in result @sections << ShakeTheCounter::Section.new(section, performance: self) end return @sections end
ruby
def sections return @sections if @sections @sections = [] path = "event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}" result = event.client.call(path, http_method: :get) for section in result @sections << ShakeTheCounter::Section.new(section, performance: self) end return @sections end
[ "def", "sections", "return", "@sections", "if", "@sections", "@sections", "=", "[", "]", "path", "=", "\"event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}\"", "result", "=", "event", ".", "client", ".", "call", "(", "path", ",", "http_method", ":", ":get", ")", "for", "section", "in", "result", "@sections", "<<", "ShakeTheCounter", "::", "Section", ".", "new", "(", "section", ",", "performance", ":", "self", ")", "end", "return", "@sections", "end" ]
Sets up a new event GET /api/v1/event/{eventKey}/performance/{performanceKey}/sections/{languageCode} Get available sections, pricetypes and prices of the selected performance @return Array of sections
[ "Sets", "up", "a", "new", "event" ]
094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e
https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/performance.rb#L29-L38
train
rtjoseph11/modernizer
lib/modernizer/version_parser.rb
Modernize.VersionParsingContext.method_missing
def method_missing(method, *args, &block) raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1 raise NoMethodError.new("Undefined translation method #{method}") unless MapMethods.respond_to?(method) @maps << {name: method, field: args[0], block: block} end
ruby
def method_missing(method, *args, &block) raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1 raise NoMethodError.new("Undefined translation method #{method}") unless MapMethods.respond_to?(method) @maps << {name: method, field: args[0], block: block} end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "raise", "ArgumentError", ".", "new", "(", "\"wrong number of arguments (#{args.size} for 1)\"", ")", "if", "args", ".", "size", "!=", "1", "raise", "NoMethodError", ".", "new", "(", "\"Undefined translation method #{method}\"", ")", "unless", "MapMethods", ".", "respond_to?", "(", "method", ")", "@maps", "<<", "{", "name", ":", "method", ",", "field", ":", "args", "[", "0", "]", ",", "block", ":", "block", "}", "end" ]
Figures out which translations are done for each version.
[ "Figures", "out", "which", "translations", "are", "done", "for", "each", "version", "." ]
5700b61815731f41146248d7e3fe8eca0e647ef3
https://github.com/rtjoseph11/modernizer/blob/5700b61815731f41146248d7e3fe8eca0e647ef3/lib/modernizer/version_parser.rb#L21-L25
train
fiatinsight/fiat_publication
app/models/fiat_publication/comment.rb
FiatPublication.Comment.mention_users
def mention_users mentions ||= begin regex = /@([\w]+)/ self.body.scan(regex).flatten end mentioned_users ||= User.where(username: mentions) if mentioned_users.any? mentioned_users.each do |i| FiatNotifications::Notification::CreateNotificationJob.set(wait: 5.seconds).perform_later( self, self.authorable, i, action: "mentioned", notified_type: "User", notified_ids: [i.id], email_template_id: FiatNotifications.email_template_id, email_subject: "You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}", email_body: "#{self.body}", reply_to_address: FiatNotifications.reply_to_email_address ) end end end
ruby
def mention_users mentions ||= begin regex = /@([\w]+)/ self.body.scan(regex).flatten end mentioned_users ||= User.where(username: mentions) if mentioned_users.any? mentioned_users.each do |i| FiatNotifications::Notification::CreateNotificationJob.set(wait: 5.seconds).perform_later( self, self.authorable, i, action: "mentioned", notified_type: "User", notified_ids: [i.id], email_template_id: FiatNotifications.email_template_id, email_subject: "You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}", email_body: "#{self.body}", reply_to_address: FiatNotifications.reply_to_email_address ) end end end
[ "def", "mention_users", "mentions", "||=", "begin", "regex", "=", "/", "\\w", "/", "self", ".", "body", ".", "scan", "(", "regex", ")", ".", "flatten", "end", "mentioned_users", "||=", "User", ".", "where", "(", "username", ":", "mentions", ")", "if", "mentioned_users", ".", "any?", "mentioned_users", ".", "each", "do", "|", "i", "|", "FiatNotifications", "::", "Notification", "::", "CreateNotificationJob", ".", "set", "(", "wait", ":", "5", ".", "seconds", ")", ".", "perform_later", "(", "self", ",", "self", ".", "authorable", ",", "i", ",", "action", ":", "\"mentioned\"", ",", "notified_type", ":", "\"User\"", ",", "notified_ids", ":", "[", "i", ".", "id", "]", ",", "email_template_id", ":", "FiatNotifications", ".", "email_template_id", ",", "email_subject", ":", "\"You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}\"", ",", "email_body", ":", "\"#{self.body}\"", ",", "reply_to_address", ":", "FiatNotifications", ".", "reply_to_email_address", ")", "end", "end", "end" ]
Ideally, this would be polymorphic-enabled
[ "Ideally", "this", "would", "be", "polymorphic", "-", "enabled" ]
f4c7209cd7c5e7a51bb70b90171d6e769792c6cf
https://github.com/fiatinsight/fiat_publication/blob/f4c7209cd7c5e7a51bb70b90171d6e769792c6cf/app/models/fiat_publication/comment.rb#L28-L51
train
code0100fun/assignment
lib/assignment/attributes.rb
Assignment.Attributes.assign_attributes
def assign_attributes(new_attributes) if !new_attributes.respond_to?(:stringify_keys) raise ArgumentError, "When assigning attributes, you must pass a hash as an argument." end return if new_attributes.nil? || new_attributes.empty? attributes = new_attributes.stringify_keys _assign_attributes(attributes) end
ruby
def assign_attributes(new_attributes) if !new_attributes.respond_to?(:stringify_keys) raise ArgumentError, "When assigning attributes, you must pass a hash as an argument." end return if new_attributes.nil? || new_attributes.empty? attributes = new_attributes.stringify_keys _assign_attributes(attributes) end
[ "def", "assign_attributes", "(", "new_attributes", ")", "if", "!", "new_attributes", ".", "respond_to?", "(", ":stringify_keys", ")", "raise", "ArgumentError", ",", "\"When assigning attributes, you must pass a hash as an argument.\"", "end", "return", "if", "new_attributes", ".", "nil?", "||", "new_attributes", ".", "empty?", "attributes", "=", "new_attributes", ".", "stringify_keys", "_assign_attributes", "(", "attributes", ")", "end" ]
Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names. class Cat include Assignment::Attributes attr_accessor :name, :status end cat = Cat.new cat.assign_attributes(name: "Gorby", status: "yawning") cat.name # => 'Gorby' cat.status => 'yawning' cat.assign_attributes(status: "sleeping") cat.name # => 'Gorby' cat.status => 'sleeping'
[ "Allows", "you", "to", "set", "all", "the", "attributes", "by", "passing", "in", "a", "hash", "of", "attributes", "with", "keys", "matching", "the", "attribute", "names", "." ]
40134e362dbbe60c6217cf147675ef7df136114d
https://github.com/code0100fun/assignment/blob/40134e362dbbe60c6217cf147675ef7df136114d/lib/assignment/attributes.rb#L21-L29
train