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
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.expand_definition
def expand_definition(definition) return definition if definition.is_a? Hash definition.each_with_object({}) do |key, result| if key.is_a? String result[key] = :default elsif key.is_a? Hash result.merge!(expand_sub_definitions(key)) end end end
ruby
def expand_definition(definition) return definition if definition.is_a? Hash definition.each_with_object({}) do |key, result| if key.is_a? String result[key] = :default elsif key.is_a? Hash result.merge!(expand_sub_definitions(key)) end end end
[ "def", "expand_definition", "(", "definition", ")", "return", "definition", "if", "definition", ".", "is_a?", "Hash", "definition", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key", ",", "result", "|", "if", "key", ".", "is_a?", "String", "result", "[", "key", "]", "=", ":default", "elsif", "key", ".", "is_a?", "Hash", "result", ".", "merge!", "(", "expand_sub_definitions", "(", "key", ")", ")", "end", "end", "end" ]
expands simple arrays into full hash definitions @api private @param definition [Array<String,Hash>] @return [Hash]
[ "expands", "simple", "arrays", "into", "full", "hash", "definitions" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L63-L72
train
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.expand_sub_definitions
def expand_sub_definitions(sub_definitions) sub_definitions.each_with_object({}) do |(subkey, value), result| result[subkey] = value next if value.respond_to? :call result[subkey][:attributes] = expand_definition(value[:attributes]) end end
ruby
def expand_sub_definitions(sub_definitions) sub_definitions.each_with_object({}) do |(subkey, value), result| result[subkey] = value next if value.respond_to? :call result[subkey][:attributes] = expand_definition(value[:attributes]) end end
[ "def", "expand_sub_definitions", "(", "sub_definitions", ")", "sub_definitions", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "subkey", ",", "value", ")", ",", "result", "|", "result", "[", "subkey", "]", "=", "value", "next", "if", "value", ".", "respond_to?", ":call", "result", "[", "subkey", "]", "[", ":attributes", "]", "=", "expand_definition", "(", "value", "[", ":attributes", "]", ")", "end", "end" ]
expands nested simple definition into a full hash @api private @param definition [Hash] @return [Hash]
[ "expands", "nested", "simple", "definition", "into", "a", "full", "hash" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L78-L84
train
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.check_definition
def check_definition(definition, current_expected, current_key = nil) definition.each do |error_key, match_def| if match_def.is_a? Hash key = [current_key, error_key].compact.join('.') check_each(key, match_def, current_expected) else check_values(current_key, error_key, match_def, current_expected) end end end
ruby
def check_definition(definition, current_expected, current_key = nil) definition.each do |error_key, match_def| if match_def.is_a? Hash key = [current_key, error_key].compact.join('.') check_each(key, match_def, current_expected) else check_values(current_key, error_key, match_def, current_expected) end end end
[ "def", "check_definition", "(", "definition", ",", "current_expected", ",", "current_key", "=", "nil", ")", "definition", ".", "each", "do", "|", "error_key", ",", "match_def", "|", "if", "match_def", ".", "is_a?", "Hash", "key", "=", "[", "current_key", ",", "error_key", "]", ".", "compact", ".", "join", "(", "'.'", ")", "check_each", "(", "key", ",", "match_def", ",", "current_expected", ")", "else", "check_values", "(", "current_key", ",", "error_key", ",", "match_def", ",", "current_expected", ")", "end", "end", "end" ]
Walks through the match definition, collecting errors for each field @api private @param definition [Hash] defines how to lookup value in json and on object @param current_expected [Object] the serialized object being checked @current_key [String,nil] optional parent key passed while checking nested definitions @return [nil] returns nothing, adds to error list as side effect
[ "Walks", "through", "the", "match", "definition", "collecting", "errors", "for", "each", "field" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L92-L101
train
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.check_each
def check_each(error_key, each_definition, current_expected) enumerable = each_definition[:each].call(current_expected) enumerable.each_with_index do |each_instance, idx| full_key = [error_key, idx].join('.') check_definition(each_definition[:attributes], each_instance, full_key) end end
ruby
def check_each(error_key, each_definition, current_expected) enumerable = each_definition[:each].call(current_expected) enumerable.each_with_index do |each_instance, idx| full_key = [error_key, idx].join('.') check_definition(each_definition[:attributes], each_instance, full_key) end end
[ "def", "check_each", "(", "error_key", ",", "each_definition", ",", "current_expected", ")", "enumerable", "=", "each_definition", "[", ":each", "]", ".", "call", "(", "current_expected", ")", "enumerable", ".", "each_with_index", "do", "|", "each_instance", ",", "idx", "|", "full_key", "=", "[", "error_key", ",", "idx", "]", ".", "join", "(", "'.'", ")", "check_definition", "(", "each_definition", "[", ":attributes", "]", ",", "each_instance", ",", "full_key", ")", "end", "end" ]
Iterates through a list of objects while checking fields @api private @param error_key [String] the first name of the field reported in the error each errors are reported #{error_key}[#{idx}].#{each_key} @param each_definition [Hash] :each is a function that returns the list of items :attributes is a hash with the same structure as the top-level match_def hash @return [nil] returns nothing, adds to error list as side effect
[ "Iterates", "through", "a", "list", "of", "objects", "while", "checking", "fields" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L112-L118
train
DogParkLabs/json_rspec_match_maker
lib/json_rspec_match_maker/base.rb
JsonRspecMatchMaker.Base.check_values
def check_values(key_prefix, error_key, match_function, expected_instance = expected) expected_value = ExpectedValue.new(match_function, expected_instance, error_key, @prefix) target_value = TargetValue.new([key_prefix, error_key].compact.join('.'), target) add_error(expected_value, target_value) unless expected_value == target_value end
ruby
def check_values(key_prefix, error_key, match_function, expected_instance = expected) expected_value = ExpectedValue.new(match_function, expected_instance, error_key, @prefix) target_value = TargetValue.new([key_prefix, error_key].compact.join('.'), target) add_error(expected_value, target_value) unless expected_value == target_value end
[ "def", "check_values", "(", "key_prefix", ",", "error_key", ",", "match_function", ",", "expected_instance", "=", "expected", ")", "expected_value", "=", "ExpectedValue", ".", "new", "(", "match_function", ",", "expected_instance", ",", "error_key", ",", "@prefix", ")", "target_value", "=", "TargetValue", ".", "new", "(", "[", "key_prefix", ",", "error_key", "]", ".", "compact", ".", "join", "(", "'.'", ")", ",", "target", ")", "add_error", "(", "expected_value", ",", "target_value", ")", "unless", "expected_value", "==", "target_value", "end" ]
Checks fields on a single instance @api private @param key_prefix [String] optional parent key if iterating through nested association @param error_key [String] the name of the field reported in the error @param match_function [Hash] a function returning the value for the key for the object being serialized @param expected_instance [Object] the top level instance, or an each instance from #check_each the index if iterating through a list, otherwise nil @return [nil] returns nothing, adds to error list as side effect
[ "Checks", "fields", "on", "a", "single", "instance" ]
7d9f299a0097c4eca3a4d22cecd28852bde8e8bc
https://github.com/DogParkLabs/json_rspec_match_maker/blob/7d9f299a0097c4eca3a4d22cecd28852bde8e8bc/lib/json_rspec_match_maker/base.rb#L130-L134
train
albertosaurus/us_bank_holidays
lib/us_bank_holidays.rb
UsBankHolidays.DateMethods.add_banking_days
def add_banking_days(days) day = self if days > 0 days.times { day = day.next_banking_day } elsif days < 0 (-days).times { day = day.previous_banking_day } end day end
ruby
def add_banking_days(days) day = self if days > 0 days.times { day = day.next_banking_day } elsif days < 0 (-days).times { day = day.previous_banking_day } end day end
[ "def", "add_banking_days", "(", "days", ")", "day", "=", "self", "if", "days", ">", "0", "days", ".", "times", "{", "day", "=", "day", ".", "next_banking_day", "}", "elsif", "days", "<", "0", "(", "-", "days", ")", ".", "times", "{", "day", "=", "day", ".", "previous_banking_day", "}", "end", "day", "end" ]
Adds the given number of banking days, i.e. bank holidays don't count. If days is negative, subtracts the given number of banking days. If days is zero, returns self.
[ "Adds", "the", "given", "number", "of", "banking", "days", "i", ".", "e", ".", "bank", "holidays", "don", "t", "count", ".", "If", "days", "is", "negative", "subtracts", "the", "given", "number", "of", "banking", "days", ".", "If", "days", "is", "zero", "returns", "self", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays.rb#L85-L93
train
bblack16/bblib-ruby
lib/bblib/classes/fuzzy_matcher.rb
BBLib.FuzzyMatcher.similarity
def similarity(string_a, string_b) string_a, string_b = prep_strings(string_a, string_b) return 100.0 if string_a == string_b score = 0 total_weight = algorithms.values.inject { |sum, weight| sum + weight } algorithms.each do |algorithm, weight| next unless weight.positive? score+= string_a.send("#{algorithm}_similarity", string_b) * weight end score / total_weight end
ruby
def similarity(string_a, string_b) string_a, string_b = prep_strings(string_a, string_b) return 100.0 if string_a == string_b score = 0 total_weight = algorithms.values.inject { |sum, weight| sum + weight } algorithms.each do |algorithm, weight| next unless weight.positive? score+= string_a.send("#{algorithm}_similarity", string_b) * weight end score / total_weight end
[ "def", "similarity", "(", "string_a", ",", "string_b", ")", "string_a", ",", "string_b", "=", "prep_strings", "(", "string_a", ",", "string_b", ")", "return", "100.0", "if", "string_a", "==", "string_b", "score", "=", "0", "total_weight", "=", "algorithms", ".", "values", ".", "inject", "{", "|", "sum", ",", "weight", "|", "sum", "+", "weight", "}", "algorithms", ".", "each", "do", "|", "algorithm", ",", "weight", "|", "next", "unless", "weight", ".", "positive?", "score", "+=", "string_a", ".", "send", "(", "\"#{algorithm}_similarity\"", ",", "string_b", ")", "*", "weight", "end", "score", "/", "total_weight", "end" ]
Calculates a percentage match between string a and string b.
[ "Calculates", "a", "percentage", "match", "between", "string", "a", "and", "string", "b", "." ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/classes/fuzzy_matcher.rb#L12-L22
train
bblack16/bblib-ruby
lib/bblib/classes/fuzzy_matcher.rb
BBLib.FuzzyMatcher.best_match
def best_match(string_a, *string_b) similarities(string_a, *string_b).max_by { |_k, v| v }[0] end
ruby
def best_match(string_a, *string_b) similarities(string_a, *string_b).max_by { |_k, v| v }[0] end
[ "def", "best_match", "(", "string_a", ",", "*", "string_b", ")", "similarities", "(", "string_a", ",", "*", "string_b", ")", ".", "max_by", "{", "|", "_k", ",", "v", "|", "v", "}", "[", "0", "]", "end" ]
Returns the best match from array b to string a based on percent.
[ "Returns", "the", "best", "match", "from", "array", "b", "to", "string", "a", "based", "on", "percent", "." ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/classes/fuzzy_matcher.rb#L30-L32
train
bblack16/bblib-ruby
lib/bblib/classes/fuzzy_matcher.rb
BBLib.FuzzyMatcher.similarities
def similarities(string_a, *string_b) [*string_b].map { |word| [word, matches[word] = similarity(string_a, word)] } end
ruby
def similarities(string_a, *string_b) [*string_b].map { |word| [word, matches[word] = similarity(string_a, word)] } end
[ "def", "similarities", "(", "string_a", ",", "*", "string_b", ")", "[", "*", "string_b", "]", ".", "map", "{", "|", "word", "|", "[", "word", ",", "matches", "[", "word", "]", "=", "similarity", "(", "string_a", ",", "word", ")", "]", "}", "end" ]
Returns a hash of array 'b' with the percentage match to a. If sort is true, the hash is sorted desc by match percent.
[ "Returns", "a", "hash", "of", "array", "b", "with", "the", "percentage", "match", "to", "a", ".", "If", "sort", "is", "true", "the", "hash", "is", "sorted", "desc", "by", "match", "percent", "." ]
274eedeb583cc56243884fd041645488d5bd08a9
https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/classes/fuzzy_matcher.rb#L36-L38
train
OHSU-FM/reindeer-etl
lib/reindeer-etl/transforms/simple_transforms.rb
ReindeerETL::Transforms.SimpleTransforms.st_only_cols
def st_only_cols dict (dict.keys.to_set - @only_cols).each{|col|dict.delete(col)} dict end
ruby
def st_only_cols dict (dict.keys.to_set - @only_cols).each{|col|dict.delete(col)} dict end
[ "def", "st_only_cols", "dict", "(", "dict", ".", "keys", ".", "to_set", "-", "@only_cols", ")", ".", "each", "{", "|", "col", "|", "dict", ".", "delete", "(", "col", ")", "}", "dict", "end" ]
Filter out everything except these columns
[ "Filter", "out", "everything", "except", "these", "columns" ]
bff48c999b17850681346d500f2a05900252e21f
https://github.com/OHSU-FM/reindeer-etl/blob/bff48c999b17850681346d500f2a05900252e21f/lib/reindeer-etl/transforms/simple_transforms.rb#L18-L21
train
OHSU-FM/reindeer-etl
lib/reindeer-etl/transforms/simple_transforms.rb
ReindeerETL::Transforms.SimpleTransforms.st_require_cols
def st_require_cols dict dcols = dict.keys.to_set unless @require_cols.subset? dict.keys.to_set missing_cols = (@require_cols - dcols).to_a raise ReindeerETL::Errors::RecordInvalid.new("Missing required columns: #{missing_cols}") end end
ruby
def st_require_cols dict dcols = dict.keys.to_set unless @require_cols.subset? dict.keys.to_set missing_cols = (@require_cols - dcols).to_a raise ReindeerETL::Errors::RecordInvalid.new("Missing required columns: #{missing_cols}") end end
[ "def", "st_require_cols", "dict", "dcols", "=", "dict", ".", "keys", ".", "to_set", "unless", "@require_cols", ".", "subset?", "dict", ".", "keys", ".", "to_set", "missing_cols", "=", "(", "@require_cols", "-", "dcols", ")", ".", "to_a", "raise", "ReindeerETL", "::", "Errors", "::", "RecordInvalid", ".", "new", "(", "\"Missing required columns: #{missing_cols}\"", ")", "end", "end" ]
require these columns
[ "require", "these", "columns" ]
bff48c999b17850681346d500f2a05900252e21f
https://github.com/OHSU-FM/reindeer-etl/blob/bff48c999b17850681346d500f2a05900252e21f/lib/reindeer-etl/transforms/simple_transforms.rb#L25-L31
train
salesking/sk_sdk
lib/sk_sdk/ar_patches/ar3/validations.rb
ActiveResource.Errors.from_array
def from_array(messages, save_cache=false) clear unless save_cache messages.each do |msg| add msg[0], msg[1] end end
ruby
def from_array(messages, save_cache=false) clear unless save_cache messages.each do |msg| add msg[0], msg[1] end end
[ "def", "from_array", "(", "messages", ",", "save_cache", "=", "false", ")", "clear", "unless", "save_cache", "messages", ".", "each", "do", "|", "msg", "|", "add", "msg", "[", "0", "]", ",", "msg", "[", "1", "]", "end", "end" ]
Patched cause we dont need no attribute name magic .. and its just simpler orig version is looking up the humanized name of the attribute in the error message, which we dont supply => only field name is used in returned error msg
[ "Patched", "cause", "we", "dont", "need", "no", "attribute", "name", "magic", "..", "and", "its", "just", "simpler", "orig", "version", "is", "looking", "up", "the", "humanized", "name", "of", "the", "attribute", "in", "the", "error", "message", "which", "we", "dont", "supply", "=", ">", "only", "field", "name", "is", "used", "in", "returned", "error", "msg" ]
03170b2807cc4e1f1ba44c704c308370c6563dbc
https://github.com/salesking/sk_sdk/blob/03170b2807cc4e1f1ba44c704c308370c6563dbc/lib/sk_sdk/ar_patches/ar3/validations.rb#L6-L11
train
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.parse_modes
def parse_modes(modes) mode_changes = [] modes.scan(/[-+]\w+/).each do |modegroup| set, modegroup = modegroup.split '', 2 set = set == '+' ? true : false modegroup.split('').each do |mode| mode_changes << { set: set, mode: mode } end end return mode_changes end
ruby
def parse_modes(modes) mode_changes = [] modes.scan(/[-+]\w+/).each do |modegroup| set, modegroup = modegroup.split '', 2 set = set == '+' ? true : false modegroup.split('').each do |mode| mode_changes << { set: set, mode: mode } end end return mode_changes end
[ "def", "parse_modes", "(", "modes", ")", "mode_changes", "=", "[", "]", "modes", ".", "scan", "(", "/", "\\w", "/", ")", ".", "each", "do", "|", "modegroup", "|", "set", ",", "modegroup", "=", "modegroup", ".", "split", "''", ",", "2", "set", "=", "set", "==", "'+'", "?", "true", ":", "false", "modegroup", ".", "split", "(", "''", ")", ".", "each", "do", "|", "mode", "|", "mode_changes", "<<", "{", "set", ":", "set", ",", "mode", ":", "mode", "}", "end", "end", "return", "mode_changes", "end" ]
Parse mode changes. @param [Array] modes The modes you want to parse. A string of mode changes (e.g. `'-i+k+l'`) followed by any arguments (e.g. `'secret', 25`). @return [Array] Each element will be a hash with two keys: `:set`, a boolean indicating whether the mode is being set (instead of unset); and `:mode`, the mode character.
[ "Parse", "mode", "changes", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L11-L21
train
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.parse_channel_modes
def parse_channel_modes(modes, opts = {}) chanmodes = opts[:chanmodes] || { 'A' => %w{b e I}.to_set, 'B' => %w{k}.to_set, 'C' => %w{l}.to_set, 'D' => %w{i m n p s t a q r}.to_set, } statmodes = opts[:statmodes] || %w{o h v}.to_set mode_changes = [] modelist, *args = modes parse_modes(modelist).each do |mode_change| set, mode = mode_change[:set], mode_change[:mode] case when chanmodes["A"].include?(mode) || chanmodes["B"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift } when chanmodes["C"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift.to_i } when chanmodes["D"].include?(mode) mode_changes << { mode: mode, set: set, } else raise ArgumentError, "Unknown mode: #{mode}" end end return mode_changes end
ruby
def parse_channel_modes(modes, opts = {}) chanmodes = opts[:chanmodes] || { 'A' => %w{b e I}.to_set, 'B' => %w{k}.to_set, 'C' => %w{l}.to_set, 'D' => %w{i m n p s t a q r}.to_set, } statmodes = opts[:statmodes] || %w{o h v}.to_set mode_changes = [] modelist, *args = modes parse_modes(modelist).each do |mode_change| set, mode = mode_change[:set], mode_change[:mode] case when chanmodes["A"].include?(mode) || chanmodes["B"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift } when chanmodes["C"].include?(mode) mode_changes << { mode: mode, set: set, argument: args.shift.to_i } when chanmodes["D"].include?(mode) mode_changes << { mode: mode, set: set, } else raise ArgumentError, "Unknown mode: #{mode}" end end return mode_changes end
[ "def", "parse_channel_modes", "(", "modes", ",", "opts", "=", "{", "}", ")", "chanmodes", "=", "opts", "[", ":chanmodes", "]", "||", "{", "'A'", "=>", "%w{", "b", "e", "I", "}", ".", "to_set", ",", "'B'", "=>", "%w{", "k", "}", ".", "to_set", ",", "'C'", "=>", "%w{", "l", "}", ".", "to_set", ",", "'D'", "=>", "%w{", "i", "m", "n", "p", "s", "t", "a", "q", "r", "}", ".", "to_set", ",", "}", "statmodes", "=", "opts", "[", ":statmodes", "]", "||", "%w{", "o", "h", "v", "}", ".", "to_set", "mode_changes", "=", "[", "]", "modelist", ",", "*", "args", "=", "modes", "parse_modes", "(", "modelist", ")", ".", "each", "do", "|", "mode_change", "|", "set", ",", "mode", "=", "mode_change", "[", ":set", "]", ",", "mode_change", "[", ":mode", "]", "case", "when", "chanmodes", "[", "\"A\"", "]", ".", "include?", "(", "mode", ")", "||", "chanmodes", "[", "\"B\"", "]", ".", "include?", "(", "mode", ")", "mode_changes", "<<", "{", "mode", ":", "mode", ",", "set", ":", "set", ",", "argument", ":", "args", ".", "shift", "}", "when", "chanmodes", "[", "\"C\"", "]", ".", "include?", "(", "mode", ")", "mode_changes", "<<", "{", "mode", ":", "mode", ",", "set", ":", "set", ",", "argument", ":", "args", ".", "shift", ".", "to_i", "}", "when", "chanmodes", "[", "\"D\"", "]", ".", "include?", "(", "mode", ")", "mode_changes", "<<", "{", "mode", ":", "mode", ",", "set", ":", "set", ",", "}", "else", "raise", "ArgumentError", ",", "\"Unknown mode: #{mode}\"", "end", "end", "return", "mode_changes", "end" ]
Parse channel mode changes. @param [Array] modes The modes you want to parse. @option opts [Hash] :chanmodes The channel modes which are allowed. This is the same as the "CHANMODES" isupport option. @option opts [Hash] :statmodes The channel modes which are allowed. This is the same as the keys of the "PREFIX" isupport option. @return [Array] Each element will be a hash with three keys: `:set`, a boolean indicating whether the mode is being set (instead of unset); `:mode`, the mode character; and `:argument`, the argument to the mode, if any.
[ "Parse", "channel", "mode", "changes", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L33-L70
train
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.condense_modes
def condense_modes(modes) action = nil result = '' modes.split(//).each do |mode| if mode =~ /[+-]/ and (!action or mode != action) result += mode action = mode next end result += mode if mode =~ /[^+-]/ end result.sub!(/[+-]\z/, '') return result end
ruby
def condense_modes(modes) action = nil result = '' modes.split(//).each do |mode| if mode =~ /[+-]/ and (!action or mode != action) result += mode action = mode next end result += mode if mode =~ /[^+-]/ end result.sub!(/[+-]\z/, '') return result end
[ "def", "condense_modes", "(", "modes", ")", "action", "=", "nil", "result", "=", "''", "modes", ".", "split", "(", "/", "/", ")", ".", "each", "do", "|", "mode", "|", "if", "mode", "=~", "/", "/", "and", "(", "!", "action", "or", "mode", "!=", "action", ")", "result", "+=", "mode", "action", "=", "mode", "next", "end", "result", "+=", "mode", "if", "mode", "=~", "/", "/", "end", "result", ".", "sub!", "(", "/", "\\z", "/", ",", "''", ")", "return", "result", "end" ]
Condense mode string by removing duplicates. @param [String] modes A string of modes you want condensed. @return [Strings] A condensed mode string.
[ "Condense", "mode", "string", "by", "removing", "duplicates", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L75-L88
train
hinrik/ircsupport
lib/ircsupport/modes.rb
IRCSupport.Modes.diff_modes
def diff_modes(before, after) before_modes = before.split(//) after_modes = after.split(//) removed = before_modes - after_modes added = after_modes - before_modes result = removed.map { |m| '-' + m }.join result << added.map { |m| '+' + m }.join return condense_modes(result) end
ruby
def diff_modes(before, after) before_modes = before.split(//) after_modes = after.split(//) removed = before_modes - after_modes added = after_modes - before_modes result = removed.map { |m| '-' + m }.join result << added.map { |m| '+' + m }.join return condense_modes(result) end
[ "def", "diff_modes", "(", "before", ",", "after", ")", "before_modes", "=", "before", ".", "split", "(", "/", "/", ")", "after_modes", "=", "after", ".", "split", "(", "/", "/", ")", "removed", "=", "before_modes", "-", "after_modes", "added", "=", "after_modes", "-", "before_modes", "result", "=", "removed", ".", "map", "{", "|", "m", "|", "'-'", "+", "m", "}", ".", "join", "result", "<<", "added", ".", "map", "{", "|", "m", "|", "'+'", "+", "m", "}", ".", "join", "return", "condense_modes", "(", "result", ")", "end" ]
Calculate the difference between two mode strings. @param [String] before The "before" mode string. @param [String] after The "after" mode string. @return [String] A modestring representing the difference between the two mode strings.
[ "Calculate", "the", "difference", "between", "two", "mode", "strings", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/modes.rb#L95-L103
train
jinx/core
lib/jinx/metadata/java_property.rb
Jinx.JavaProperty.infer_collection_type_from_name
def infer_collection_type_from_name # the property name pname = @property_descriptor.name # The potential class name is the capitalized property name without a 'Collection' suffix. cname = pname.capitalize_first.sub(/Collection$/, '') jname = [@declarer.parent_module, cname].join('::') klass = eval jname rescue nil if klass then logger.debug { "Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name." } end klass end
ruby
def infer_collection_type_from_name # the property name pname = @property_descriptor.name # The potential class name is the capitalized property name without a 'Collection' suffix. cname = pname.capitalize_first.sub(/Collection$/, '') jname = [@declarer.parent_module, cname].join('::') klass = eval jname rescue nil if klass then logger.debug { "Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name." } end klass end
[ "def", "infer_collection_type_from_name", "pname", "=", "@property_descriptor", ".", "name", "cname", "=", "pname", ".", "capitalize_first", ".", "sub", "(", "/", "/", ",", "''", ")", "jname", "=", "[", "@declarer", ".", "parent_module", ",", "cname", "]", ".", "join", "(", "'::'", ")", "klass", "=", "eval", "jname", "rescue", "nil", "if", "klass", "then", "logger", ".", "debug", "{", "\"Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name.\"", "}", "end", "klass", "end" ]
Returns the domain type for this property's collection Java property descriptor name. By convention, Jinx domain collection propertys often begin with a domain type name and end in 'Collection'. This method strips the Collection suffix and checks whether the prefix is a domain class. For example, the type of the property named +distributionProtocolCollection+ is inferred as +DistributionProtocol+ by stripping the +Collection+ suffix, capitalizing the prefix and looking for a class of that name in this classifier's domain_module. @return [Class] the collection item type
[ "Returns", "the", "domain", "type", "for", "this", "property", "s", "collection", "Java", "property", "descriptor", "name", ".", "By", "convention", "Jinx", "domain", "collection", "propertys", "often", "begin", "with", "a", "domain", "type", "name", "and", "end", "in", "Collection", ".", "This", "method", "strips", "the", "Collection", "suffix", "and", "checks", "whether", "the", "prefix", "is", "a", "domain", "class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/java_property.rb#L147-L156
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.define_plugin_types
def define_plugin_types(namespace, type_info) if type_info.is_a?(Hash) type_info.each do |plugin_type, default_provider| define_plugin_type(namespace, plugin_type, default_provider) end end self end
ruby
def define_plugin_types(namespace, type_info) if type_info.is_a?(Hash) type_info.each do |plugin_type, default_provider| define_plugin_type(namespace, plugin_type, default_provider) end end self end
[ "def", "define_plugin_types", "(", "namespace", ",", "type_info", ")", "if", "type_info", ".", "is_a?", "(", "Hash", ")", "type_info", ".", "each", "do", "|", "plugin_type", ",", "default_provider", "|", "define_plugin_type", "(", "namespace", ",", "plugin_type", ",", "default_provider", ")", "end", "end", "self", "end" ]
Define one or more new plugin types in a specified namespace. * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [Hash<String, Symbol|String, Symbol>] *type_info* Plugin type, default provider pairs * *Returns* - [Nucleon::Environment] Returns reference to self for compound operations * *Errors* See: - #define_plugin_type
[ "Define", "one", "or", "more", "new", "plugin", "types", "in", "a", "specified", "namespace", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L146-L153
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.loaded_plugin
def loaded_plugin(namespace, plugin_type, provider) get([ :load_info, namespace, sanitize_id(plugin_type), sanitize_id(provider) ], nil) end
ruby
def loaded_plugin(namespace, plugin_type, provider) get([ :load_info, namespace, sanitize_id(plugin_type), sanitize_id(provider) ], nil) end
[ "def", "loaded_plugin", "(", "namespace", ",", "plugin_type", ",", "provider", ")", "get", "(", "[", ":load_info", ",", "namespace", ",", "sanitize_id", "(", "plugin_type", ")", ",", "sanitize_id", "(", "provider", ")", "]", ",", "nil", ")", "end" ]
Return the load information for a specified plugin provider if it exists * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [String, Symbol] *plugin_type* Plugin type name of provider - [String, Symbol] *provider* Plugin provider to return load information * *Returns* - [nil, Hash<Symbol|ANY>] Returns provider load information if provider exists, nil otherwise * *Errors* See: - Nucleon::Config#get See also: - #sanitize_id
[ "Return", "the", "load", "information", "for", "a", "specified", "plugin", "provider", "if", "it", "exists" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L265-L267
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.loaded_plugins
def loaded_plugins(namespace = nil, plugin_type = nil, provider = nil, default = {}) load_info = get_hash(:load_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = default if namespace && load_info.has_key?(namespace) if plugin_type && load_info[namespace].has_key?(plugin_type) if provider && load_info[namespace][plugin_type].has_key?(provider) results = load_info[namespace][plugin_type][provider] elsif ! provider results = load_info[namespace][plugin_type] end elsif ! plugin_type results = load_info[namespace] end elsif ! namespace results = load_info end results end
ruby
def loaded_plugins(namespace = nil, plugin_type = nil, provider = nil, default = {}) load_info = get_hash(:load_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = default if namespace && load_info.has_key?(namespace) if plugin_type && load_info[namespace].has_key?(plugin_type) if provider && load_info[namespace][plugin_type].has_key?(provider) results = load_info[namespace][plugin_type][provider] elsif ! provider results = load_info[namespace][plugin_type] end elsif ! plugin_type results = load_info[namespace] end elsif ! namespace results = load_info end results end
[ "def", "loaded_plugins", "(", "namespace", "=", "nil", ",", "plugin_type", "=", "nil", ",", "provider", "=", "nil", ",", "default", "=", "{", "}", ")", "load_info", "=", "get_hash", "(", ":load_info", ")", "namespace", "=", "namespace", ".", "to_sym", "if", "namespace", "plugin_type", "=", "sanitize_id", "(", "plugin_type", ")", "if", "plugin_type", "provider", "=", "sanitize_id", "(", "provider", ")", "if", "provider", "results", "=", "default", "if", "namespace", "&&", "load_info", ".", "has_key?", "(", "namespace", ")", "if", "plugin_type", "&&", "load_info", "[", "namespace", "]", ".", "has_key?", "(", "plugin_type", ")", "if", "provider", "&&", "load_info", "[", "namespace", "]", "[", "plugin_type", "]", ".", "has_key?", "(", "provider", ")", "results", "=", "load_info", "[", "namespace", "]", "[", "plugin_type", "]", "[", "provider", "]", "elsif", "!", "provider", "results", "=", "load_info", "[", "namespace", "]", "[", "plugin_type", "]", "end", "elsif", "!", "plugin_type", "results", "=", "load_info", "[", "namespace", "]", "end", "elsif", "!", "namespace", "results", "=", "load_info", "end", "results", "end" ]
Return the load information for namespaces, plugin types, providers if it exists * *Parameters* - [nil, String, Symbol] *namespace* Namespace to return load information - [nil, String, Symbol] *plugin_type* Plugin type name to return load information - [nil, String, Symbol] *provider* Plugin provider to return load information - [ANY] *default* Default results if nothing found (empty hash by default) * *Returns* - [nil, Hash<Symbol|Symbol|Symbol|Symbol|ANY>] Returns all load information if no parameters given - [nil, Hash<Symbol|Symbol|Symbol|ANY>] Returns namespace load information if only namespace given - [nil, Hash<Symbol|Symbol|ANY>] Returns plugin type load information if namespace and plugin type given - [nil, Hash<Symbol|ANY>] Returns provider load information if namespace, plugin type, and provider given * *Errors* See: - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Return", "the", "load", "information", "for", "namespaces", "plugin", "types", "providers", "if", "it", "exists" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L291-L313
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.plugin_has_provider?
def plugin_has_provider?(namespace, plugin_type, provider) get_hash([ :load_info, namespace, sanitize_id(plugin_type) ]).has_key?(sanitize_id(provider)) end
ruby
def plugin_has_provider?(namespace, plugin_type, provider) get_hash([ :load_info, namespace, sanitize_id(plugin_type) ]).has_key?(sanitize_id(provider)) end
[ "def", "plugin_has_provider?", "(", "namespace", ",", "plugin_type", ",", "provider", ")", "get_hash", "(", "[", ":load_info", ",", "namespace", ",", "sanitize_id", "(", "plugin_type", ")", "]", ")", ".", "has_key?", "(", "sanitize_id", "(", "provider", ")", ")", "end" ]
Check if a specified plugin provider has been loaded * *Parameters* - [String, Symbol] *namespace* Namespace that contains plugin types - [String, Symbol] *plugin_type* Plugin type name to check - [String, Symbol] *provider* Plugin provider name to check * *Returns* - [Boolean] Returns true if plugin provider has been loaded, false otherwise * *Errors* See: - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Check", "if", "a", "specified", "plugin", "provider", "has", "been", "loaded" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L354-L356
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.get_plugin
def get_plugin(namespace, plugin_type, plugin_name) namespace = namespace.to_sym plugin_type = sanitize_id(plugin_type) instances = get_hash([ :active_info, namespace, plugin_type ]) instance_ids = array(@instance_map.get([ namespace, plugin_type, plugin_name.to_s.to_sym ])) if instance_ids.size return instances[instance_ids[0]] end nil end
ruby
def get_plugin(namespace, plugin_type, plugin_name) namespace = namespace.to_sym plugin_type = sanitize_id(plugin_type) instances = get_hash([ :active_info, namespace, plugin_type ]) instance_ids = array(@instance_map.get([ namespace, plugin_type, plugin_name.to_s.to_sym ])) if instance_ids.size return instances[instance_ids[0]] end nil end
[ "def", "get_plugin", "(", "namespace", ",", "plugin_type", ",", "plugin_name", ")", "namespace", "=", "namespace", ".", "to_sym", "plugin_type", "=", "sanitize_id", "(", "plugin_type", ")", "instances", "=", "get_hash", "(", "[", ":active_info", ",", "namespace", ",", "plugin_type", "]", ")", "instance_ids", "=", "array", "(", "@instance_map", ".", "get", "(", "[", "namespace", ",", "plugin_type", ",", "plugin_name", ".", "to_s", ".", "to_sym", "]", ")", ")", "if", "instance_ids", ".", "size", "return", "instances", "[", "instance_ids", "[", "0", "]", "]", "end", "nil", "end" ]
Return a plugin instance by name if it exists * *Parameters* - [String, Symbol] *namespace* Namespace that contains the plugin - [String, Symbol] *plugin_type* Plugin type name - [String, Symbol] *plugin_name* Plugin name to return * *Returns* - [nil, Nucleon::Plugin::Base] Returns a plugin instance of name specified if it exists * *Errors* See: - Nucleon::Plugin::Base - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Return", "a", "plugin", "instance", "by", "name", "if", "it", "exists" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L488-L499
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.remove_plugin
def remove_plugin(namespace, plugin_type, instance_name, &code) # :yields: plugin plugin = delete([ :active_info, namespace, sanitize_id(plugin_type), instance_name ]) code.call(plugin) if code && plugin plugin end
ruby
def remove_plugin(namespace, plugin_type, instance_name, &code) # :yields: plugin plugin = delete([ :active_info, namespace, sanitize_id(plugin_type), instance_name ]) code.call(plugin) if code && plugin plugin end
[ "def", "remove_plugin", "(", "namespace", ",", "plugin_type", ",", "instance_name", ",", "&", "code", ")", "plugin", "=", "delete", "(", "[", ":active_info", ",", "namespace", ",", "sanitize_id", "(", "plugin_type", ")", ",", "instance_name", "]", ")", "code", ".", "call", "(", "plugin", ")", "if", "code", "&&", "plugin", "plugin", "end" ]
Remove a plugin instance from the environment * *Parameters* - [String, Symbol] *namespace* Namespace that contains the plugin - [String, Symbol] *plugin_type* Plugin type name - [String, Symbol] *instance_name* Plugin instance name to tremove * *Returns* - [nil, Nucleon::Plugin::Base] Returns the plugin instance that was removed from environment * *Errors* * *Yields* - [Nucleon::Plugin::Base] *plugin* Plugin object being removed (cleanup) See: - Nucleon::Plugin::Base - Nucleon::Config#delete See also: - #sanitize_id
[ "Remove", "a", "plugin", "instance", "from", "the", "environment" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L523-L527
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.active_plugins
def active_plugins(namespace = nil, plugin_type = nil, provider = nil) active_info = get_hash(:active_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = {} if namespace && active_info.has_key?(namespace) if plugin_type && active_info[namespace].has_key?(plugin_type) if provider && ! active_info[namespace][plugin_type].keys.empty? active_info[namespace][plugin_type].each do |instance_name, plugin| plugin = active_info[namespace][plugin_type][instance_name] results[instance_name] = plugin if plugin.plugin_provider == provider end elsif ! provider results = active_info[namespace][plugin_type] end elsif ! plugin_type results = active_info[namespace] end elsif ! namespace results = active_info end results end
ruby
def active_plugins(namespace = nil, plugin_type = nil, provider = nil) active_info = get_hash(:active_info) namespace = namespace.to_sym if namespace plugin_type = sanitize_id(plugin_type) if plugin_type provider = sanitize_id(provider) if provider results = {} if namespace && active_info.has_key?(namespace) if plugin_type && active_info[namespace].has_key?(plugin_type) if provider && ! active_info[namespace][plugin_type].keys.empty? active_info[namespace][plugin_type].each do |instance_name, plugin| plugin = active_info[namespace][plugin_type][instance_name] results[instance_name] = plugin if plugin.plugin_provider == provider end elsif ! provider results = active_info[namespace][plugin_type] end elsif ! plugin_type results = active_info[namespace] end elsif ! namespace results = active_info end results end
[ "def", "active_plugins", "(", "namespace", "=", "nil", ",", "plugin_type", "=", "nil", ",", "provider", "=", "nil", ")", "active_info", "=", "get_hash", "(", ":active_info", ")", "namespace", "=", "namespace", ".", "to_sym", "if", "namespace", "plugin_type", "=", "sanitize_id", "(", "plugin_type", ")", "if", "plugin_type", "provider", "=", "sanitize_id", "(", "provider", ")", "if", "provider", "results", "=", "{", "}", "if", "namespace", "&&", "active_info", ".", "has_key?", "(", "namespace", ")", "if", "plugin_type", "&&", "active_info", "[", "namespace", "]", ".", "has_key?", "(", "plugin_type", ")", "if", "provider", "&&", "!", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", ".", "keys", ".", "empty?", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", ".", "each", "do", "|", "instance_name", ",", "plugin", "|", "plugin", "=", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", "[", "instance_name", "]", "results", "[", "instance_name", "]", "=", "plugin", "if", "plugin", ".", "plugin_provider", "==", "provider", "end", "elsif", "!", "provider", "results", "=", "active_info", "[", "namespace", "]", "[", "plugin_type", "]", "end", "elsif", "!", "plugin_type", "results", "=", "active_info", "[", "namespace", "]", "end", "elsif", "!", "namespace", "results", "=", "active_info", "end", "results", "end" ]
Return active plugins for namespaces, plugin types, providers if specified * *Parameters* - [nil, String, Symbol] *namespace* Namespace to return plugin instance - [nil, String, Symbol] *plugin_type* Plugin type name to return plugin instance - [nil, String, Symbol] *provider* Plugin provider to return plugin instance * *Returns* - [nil, Hash<Symbol|Symbol|Symbol|Symbol|Nucleon::Plugin::Base>] Returns all plugin instances if no parameters given - [nil, Hash<Symbol|Symbol|Symbol|Nucleon::Plugin::Base>] Returns namespace plugin instances if only namespace given - [nil, Hash<Symbol|Symbol|Nucleon::Plugin::Base>] Returns plugin type instances if namespace and plugin type given - [nil, Hash<Symbol|Nucleon::Plugin::Base>] Returns provider instances if namespace, plugin type, and provider given * *Errors* See: - Nucleon::Config#get_hash See also: - #sanitize_id
[ "Return", "active", "plugins", "for", "namespaces", "plugin", "types", "providers", "if", "specified" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L550-L575
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.class_const
def class_const(name, separator = '::') components = class_name(name, separator, TRUE) constant = Object components.each do |component| constant = constant.const_defined?(component) ? constant.const_get(component) : constant.const_missing(component) end constant end
ruby
def class_const(name, separator = '::') components = class_name(name, separator, TRUE) constant = Object components.each do |component| constant = constant.const_defined?(component) ? constant.const_get(component) : constant.const_missing(component) end constant end
[ "def", "class_const", "(", "name", ",", "separator", "=", "'::'", ")", "components", "=", "class_name", "(", "name", ",", "separator", ",", "TRUE", ")", "constant", "=", "Object", "components", ".", "each", "do", "|", "component", "|", "constant", "=", "constant", ".", "const_defined?", "(", "component", ")", "?", "constant", ".", "const_get", "(", "component", ")", ":", "constant", ".", "const_missing", "(", "component", ")", "end", "constant", "end" ]
Return a fully formed class name as a machine usable constant * *Parameters* - [String, Symbol, Array] *name* Class name components - [String, Symbol] *separator* Class component separator (default '::') * *Returns* - [Class Constant] Returns class constant for fully formed class name of given components * *Errors* See also: - #class_name
[ "Return", "a", "fully", "formed", "class", "name", "as", "a", "machine", "usable", "constant" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L629-L639
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.sanitize_class
def sanitize_class(class_component) class_component.to_s.split('_').collect {|elem| elem.slice(0,1).capitalize + elem.slice(1..-1) }.join('') end
ruby
def sanitize_class(class_component) class_component.to_s.split('_').collect {|elem| elem.slice(0,1).capitalize + elem.slice(1..-1) }.join('') end
[ "def", "sanitize_class", "(", "class_component", ")", "class_component", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "collect", "{", "|", "elem", "|", "elem", ".", "slice", "(", "0", ",", "1", ")", ".", "capitalize", "+", "elem", ".", "slice", "(", "1", "..", "-", "1", ")", "}", ".", "join", "(", "''", ")", "end" ]
Sanitize a class identifier for internal use. * *Parameters* - [String, Symbol] *class_component* Class identifier to sanitize * *Returns* - [String] Returns a sanitized string representing the given class component * *Errors*
[ "Sanitize", "a", "class", "identifier", "for", "internal", "use", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L666-L668
train
coralnexus/nucleon
lib/core/environment.rb
Nucleon.Environment.provider_class
def provider_class(namespace, plugin_type, provider) class_const([ sanitize_class(namespace), sanitize_class(plugin_type), provider ]) end
ruby
def provider_class(namespace, plugin_type, provider) class_const([ sanitize_class(namespace), sanitize_class(plugin_type), provider ]) end
[ "def", "provider_class", "(", "namespace", ",", "plugin_type", ",", "provider", ")", "class_const", "(", "[", "sanitize_class", "(", "namespace", ")", ",", "sanitize_class", "(", "plugin_type", ")", ",", "provider", "]", ")", "end" ]
Return a class constant representing a plugin provider class generated from namespace, plugin_type, and provider name. The provider name can be entered as an array if it is included in sub modules. * *Parameters* - [String, Symbol] *namespace* Plugin namespace to constantize - [String, Symbol] *plugin_type* Plugin type to constantize - [String, Symbol, Array] *provider* Plugin provider name to constantize * *Returns* - [String] Returns a class constant representing the plugin provider * *Errors* See also: - #class_const - #sanitize_class
[ "Return", "a", "class", "constant", "representing", "a", "plugin", "provider", "class", "generated", "from", "namespace", "plugin_type", "and", "provider", "name", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/environment.rb#L709-L711
train
codescrum/bebox
lib/bebox/wizards/role_wizard.rb
Bebox.RoleWizard.create_new_role
def create_new_role(project_root, role_name) # Check if the role name is valid return error _('wizard.role.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} unless valid_puppet_class_name?(role_name) # Check if the role exist return error(_('wizard.role.name_exist')%{role: role_name}) if role_exists?(project_root, role_name) # Role creation role = Bebox::Role.new(role_name, project_root) output = role.create ok _('wizard.role.creation_success') return output end
ruby
def create_new_role(project_root, role_name) # Check if the role name is valid return error _('wizard.role.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} unless valid_puppet_class_name?(role_name) # Check if the role exist return error(_('wizard.role.name_exist')%{role: role_name}) if role_exists?(project_root, role_name) # Role creation role = Bebox::Role.new(role_name, project_root) output = role.create ok _('wizard.role.creation_success') return output end
[ "def", "create_new_role", "(", "project_root", ",", "role_name", ")", "return", "error", "_", "(", "'wizard.role.invalid_name'", ")", "%", "{", "words", ":", "Bebox", "::", "RESERVED_WORDS", ".", "join", "(", "', '", ")", "}", "unless", "valid_puppet_class_name?", "(", "role_name", ")", "return", "error", "(", "_", "(", "'wizard.role.name_exist'", ")", "%", "{", "role", ":", "role_name", "}", ")", "if", "role_exists?", "(", "project_root", ",", "role_name", ")", "role", "=", "Bebox", "::", "Role", ".", "new", "(", "role_name", ",", "project_root", ")", "output", "=", "role", ".", "create", "ok", "_", "(", "'wizard.role.creation_success'", ")", "return", "output", "end" ]
Create a new role
[ "Create", "a", "new", "role" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/role_wizard.rb#L8-L18
train
codescrum/bebox
lib/bebox/wizards/role_wizard.rb
Bebox.RoleWizard.remove_role
def remove_role(project_root) # Choose a role from the availables roles = Bebox::Role.list(project_root) # Get a role if exist. if roles.count > 0 role_name = choose_option(roles, _('wizard.role.choose_deletion_role')) else return error _('wizard.role.no_deletion_roles') end # Ask for deletion confirmation return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.role.confirm_deletion')) # Role deletion role = Bebox::Role.new(role_name, project_root) output = role.remove ok _('wizard.role.deletion_success') return output end
ruby
def remove_role(project_root) # Choose a role from the availables roles = Bebox::Role.list(project_root) # Get a role if exist. if roles.count > 0 role_name = choose_option(roles, _('wizard.role.choose_deletion_role')) else return error _('wizard.role.no_deletion_roles') end # Ask for deletion confirmation return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.role.confirm_deletion')) # Role deletion role = Bebox::Role.new(role_name, project_root) output = role.remove ok _('wizard.role.deletion_success') return output end
[ "def", "remove_role", "(", "project_root", ")", "roles", "=", "Bebox", "::", "Role", ".", "list", "(", "project_root", ")", "if", "roles", ".", "count", ">", "0", "role_name", "=", "choose_option", "(", "roles", ",", "_", "(", "'wizard.role.choose_deletion_role'", ")", ")", "else", "return", "error", "_", "(", "'wizard.role.no_deletion_roles'", ")", "end", "return", "warn", "(", "_", "(", "'wizard.no_changes'", ")", ")", "unless", "confirm_action?", "(", "_", "(", "'wizard.role.confirm_deletion'", ")", ")", "role", "=", "Bebox", "::", "Role", ".", "new", "(", "role_name", ",", "project_root", ")", "output", "=", "role", ".", "remove", "ok", "_", "(", "'wizard.role.deletion_success'", ")", "return", "output", "end" ]
Removes an existing role
[ "Removes", "an", "existing", "role" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/role_wizard.rb#L21-L37
train
codescrum/bebox
lib/bebox/wizards/role_wizard.rb
Bebox.RoleWizard.add_profile
def add_profile(project_root) roles = Bebox::Role.list(project_root) profiles = Bebox::Profile.list(project_root) role = choose_option(roles, _('wizard.choose_role')) profile = choose_option(profiles, _('wizard.role.choose_add_profile')) if Bebox::Role.profile_in_role?(project_root, role, profile) warn _('wizard.role.profile_exist')%{profile: profile, role: role} output = false else output = Bebox::Role.add_profile(project_root, role, profile) ok _('wizard.role.add_profile_success')%{profile: profile, role: role} end return output end
ruby
def add_profile(project_root) roles = Bebox::Role.list(project_root) profiles = Bebox::Profile.list(project_root) role = choose_option(roles, _('wizard.choose_role')) profile = choose_option(profiles, _('wizard.role.choose_add_profile')) if Bebox::Role.profile_in_role?(project_root, role, profile) warn _('wizard.role.profile_exist')%{profile: profile, role: role} output = false else output = Bebox::Role.add_profile(project_root, role, profile) ok _('wizard.role.add_profile_success')%{profile: profile, role: role} end return output end
[ "def", "add_profile", "(", "project_root", ")", "roles", "=", "Bebox", "::", "Role", ".", "list", "(", "project_root", ")", "profiles", "=", "Bebox", "::", "Profile", ".", "list", "(", "project_root", ")", "role", "=", "choose_option", "(", "roles", ",", "_", "(", "'wizard.choose_role'", ")", ")", "profile", "=", "choose_option", "(", "profiles", ",", "_", "(", "'wizard.role.choose_add_profile'", ")", ")", "if", "Bebox", "::", "Role", ".", "profile_in_role?", "(", "project_root", ",", "role", ",", "profile", ")", "warn", "_", "(", "'wizard.role.profile_exist'", ")", "%", "{", "profile", ":", "profile", ",", "role", ":", "role", "}", "output", "=", "false", "else", "output", "=", "Bebox", "::", "Role", ".", "add_profile", "(", "project_root", ",", "role", ",", "profile", ")", "ok", "_", "(", "'wizard.role.add_profile_success'", ")", "%", "{", "profile", ":", "profile", ",", "role", ":", "role", "}", "end", "return", "output", "end" ]
Add a profile to a role
[ "Add", "a", "profile", "to", "a", "role" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/role_wizard.rb#L40-L53
train
kindlinglabs/bullring
lib/bullring/util/drubied_process.rb
Bullring.DrubiedProcess.connect_to_process!
def connect_to_process! Bullring.logger.debug{"#{caller_name}: Connecting to process..."} if !process_port_active? Bullring.logger.debug {"#{caller_name}: Spawning process..."} # Spawn the process in its own process group so it stays alive even if this process dies pid = Process.spawn([@options[:process][:command], @options[:process][:args]].flatten.join(" "), {:pgroup => true}) Process.detach(pid) time_sleeping = 0 while (!process_port_active?) sleep(0.2) if (time_sleeping += 0.2) > @options[:process][:max_bringup_time] Bullring.logger.error {"#{caller_name}: Timed out waiting to bring up the process"} raise StandardError, "#{caller_name}: Timed out waiting to bring up the process", caller end end end if !@local_service.nil? @local_service.stop_service Bullring.logger.debug {"#{caller_name}: Stopped local service on #{@local_service.uri}"} end @local_service = DRb.start_service "druby://127.0.0.1:0" Bullring.logger.debug {"#{caller_name}: Started local service on #{@local_service.uri}"} @process = DRbObject.new nil, "druby://#{host}:#{port}" @after_connect_block.call(@process) if !@after_connect_block.nil? end
ruby
def connect_to_process! Bullring.logger.debug{"#{caller_name}: Connecting to process..."} if !process_port_active? Bullring.logger.debug {"#{caller_name}: Spawning process..."} # Spawn the process in its own process group so it stays alive even if this process dies pid = Process.spawn([@options[:process][:command], @options[:process][:args]].flatten.join(" "), {:pgroup => true}) Process.detach(pid) time_sleeping = 0 while (!process_port_active?) sleep(0.2) if (time_sleeping += 0.2) > @options[:process][:max_bringup_time] Bullring.logger.error {"#{caller_name}: Timed out waiting to bring up the process"} raise StandardError, "#{caller_name}: Timed out waiting to bring up the process", caller end end end if !@local_service.nil? @local_service.stop_service Bullring.logger.debug {"#{caller_name}: Stopped local service on #{@local_service.uri}"} end @local_service = DRb.start_service "druby://127.0.0.1:0" Bullring.logger.debug {"#{caller_name}: Started local service on #{@local_service.uri}"} @process = DRbObject.new nil, "druby://#{host}:#{port}" @after_connect_block.call(@process) if !@after_connect_block.nil? end
[ "def", "connect_to_process!", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Connecting to process...\"", "}", "if", "!", "process_port_active?", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Spawning process...\"", "}", "pid", "=", "Process", ".", "spawn", "(", "[", "@options", "[", ":process", "]", "[", ":command", "]", ",", "@options", "[", ":process", "]", "[", ":args", "]", "]", ".", "flatten", ".", "join", "(", "\" \"", ")", ",", "{", ":pgroup", "=>", "true", "}", ")", "Process", ".", "detach", "(", "pid", ")", "time_sleeping", "=", "0", "while", "(", "!", "process_port_active?", ")", "sleep", "(", "0.2", ")", "if", "(", "time_sleeping", "+=", "0.2", ")", ">", "@options", "[", ":process", "]", "[", ":max_bringup_time", "]", "Bullring", ".", "logger", ".", "error", "{", "\"#{caller_name}: Timed out waiting to bring up the process\"", "}", "raise", "StandardError", ",", "\"#{caller_name}: Timed out waiting to bring up the process\"", ",", "caller", "end", "end", "end", "if", "!", "@local_service", ".", "nil?", "@local_service", ".", "stop_service", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Stopped local service on #{@local_service.uri}\"", "}", "end", "@local_service", "=", "DRb", ".", "start_service", "\"druby://127.0.0.1:0\"", "Bullring", ".", "logger", ".", "debug", "{", "\"#{caller_name}: Started local service on #{@local_service.uri}\"", "}", "@process", "=", "DRbObject", ".", "new", "nil", ",", "\"druby://#{host}:#{port}\"", "@after_connect_block", ".", "call", "(", "@process", ")", "if", "!", "@after_connect_block", ".", "nil?", "end" ]
Creates a druby connection to the process, starting it up if necessary
[ "Creates", "a", "druby", "connection", "to", "the", "process", "starting", "it", "up", "if", "necessary" ]
30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44
https://github.com/kindlinglabs/bullring/blob/30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44/lib/bullring/util/drubied_process.rb#L69-L100
train
pilaf/recaptcha-mailhide
lib/recaptcha_mailhide/helpers/action_view_helper.rb
RecaptchaMailhide.ActionViewHelper.recaptcha_mailhide
def recaptcha_mailhide(*args, &block) options = args.extract_options! raise ArgumentError, "at least one argument is required (not counting options)" if args.empty? if block_given? url = RecaptchaMailhide.url_for(args.first) link_to(url, recaptcha_mailhide_options(url, options), &block) else if args.length == 1 content = truncate_email(args.first, options) url = RecaptchaMailhide.url_for(args.first) else content = args.first url = RecaptchaMailhide.url_for(args.second) end link_to(content, url, recaptcha_mailhide_options(url, options)) end end
ruby
def recaptcha_mailhide(*args, &block) options = args.extract_options! raise ArgumentError, "at least one argument is required (not counting options)" if args.empty? if block_given? url = RecaptchaMailhide.url_for(args.first) link_to(url, recaptcha_mailhide_options(url, options), &block) else if args.length == 1 content = truncate_email(args.first, options) url = RecaptchaMailhide.url_for(args.first) else content = args.first url = RecaptchaMailhide.url_for(args.second) end link_to(content, url, recaptcha_mailhide_options(url, options)) end end
[ "def", "recaptcha_mailhide", "(", "*", "args", ",", "&", "block", ")", "options", "=", "args", ".", "extract_options!", "raise", "ArgumentError", ",", "\"at least one argument is required (not counting options)\"", "if", "args", ".", "empty?", "if", "block_given?", "url", "=", "RecaptchaMailhide", ".", "url_for", "(", "args", ".", "first", ")", "link_to", "(", "url", ",", "recaptcha_mailhide_options", "(", "url", ",", "options", ")", ",", "&", "block", ")", "else", "if", "args", ".", "length", "==", "1", "content", "=", "truncate_email", "(", "args", ".", "first", ",", "options", ")", "url", "=", "RecaptchaMailhide", ".", "url_for", "(", "args", ".", "first", ")", "else", "content", "=", "args", ".", "first", "url", "=", "RecaptchaMailhide", ".", "url_for", "(", "args", ".", "second", ")", "end", "link_to", "(", "content", ",", "url", ",", "recaptcha_mailhide_options", "(", "url", ",", "options", ")", ")", "end", "end" ]
Generates a link tag to a ReCAPTCHA Mailhide URL for the given email address. If a block is given it will use it to generate the content, and takes these attributes: * +email+ - The email address to hide * +options+ - See options below When no block is given it accepts two forms: # Just email recaptcha_mailhide(email, options = {}) # Email and content recaptcha_mailhide(content, email, options = {}) In the first instance it will process the email with <code>truncate_email</code> and use it as the link content. ==== Options Accepts every option supported by <code>link_to</code>, plus: [:popup] Set it to <code>true</code> to have the link open a popup window (through JavaScript and the <code>onclick</code> event). Can also be a hash of sub-options, which can be <code>:width</code> and <code>:height</code>, setting the size of the popup window. In case of not supplying your own content you can also pass options for <code>truncate_email</code>, e.g.: recaptcha_mailhide('[email protected]', omission: '-', truncate_domain: true)
[ "Generates", "a", "link", "tag", "to", "a", "ReCAPTCHA", "Mailhide", "URL", "for", "the", "given", "email", "address", "." ]
f3dbee2141a2849de52addec7959dbb270adaa4c
https://github.com/pilaf/recaptcha-mailhide/blob/f3dbee2141a2849de52addec7959dbb270adaa4c/lib/recaptcha_mailhide/helpers/action_view_helper.rb#L40-L57
train
raid5/agilezen
lib/agilezen/projects.rb
AgileZen.Projects.projects
def projects(options={}) response = connection.get do |req| req.url "/api/v1/projects", options end response.body end
ruby
def projects(options={}) response = connection.get do |req| req.url "/api/v1/projects", options end response.body end
[ "def", "projects", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"/api/v1/projects\"", ",", "options", "end", "response", ".", "body", "end" ]
Retrieve information for all projects.
[ "Retrieve", "information", "for", "all", "projects", "." ]
36fcef642c82b35c8c8664ee6a2ff22ce52054c0
https://github.com/raid5/agilezen/blob/36fcef642c82b35c8c8664ee6a2ff22ce52054c0/lib/agilezen/projects.rb#L6-L11
train
saclark/lite_page
lib/lite_page/element_factory.rb
LitePage.ElementFactory.def_elements
def def_elements(root_elem_var_name, element_definitions = {}) element_definitions.each do |name, definition| define_method(name) do |other_selectors = {}| definition[1].merge!(other_selectors) instance_variable_get(root_elem_var_name.to_sym).send(*definition) end end end
ruby
def def_elements(root_elem_var_name, element_definitions = {}) element_definitions.each do |name, definition| define_method(name) do |other_selectors = {}| definition[1].merge!(other_selectors) instance_variable_get(root_elem_var_name.to_sym).send(*definition) end end end
[ "def", "def_elements", "(", "root_elem_var_name", ",", "element_definitions", "=", "{", "}", ")", "element_definitions", ".", "each", "do", "|", "name", ",", "definition", "|", "define_method", "(", "name", ")", "do", "|", "other_selectors", "=", "{", "}", "|", "definition", "[", "1", "]", ".", "merge!", "(", "other_selectors", ")", "instance_variable_get", "(", "root_elem_var_name", ".", "to_sym", ")", ".", "send", "(", "*", "definition", ")", "end", "end", "end" ]
Provides convenient method for concisely defining element getters @param root_elem_var_name [Symbol] the name of the instance variable containing the element on which methods should be caleld (typically the browser instance). @param element_definitions [Hash] the hash used to define element getters on the class instance where each key represents the name of the method to be defined and whose value is an array containing first, the element tag name and second, the selectors with which to locate it.
[ "Provides", "convenient", "method", "for", "concisely", "defining", "element", "getters" ]
efa3ae28a49428ee60c6ee95b51c5d79f603acec
https://github.com/saclark/lite_page/blob/efa3ae28a49428ee60c6ee95b51c5d79f603acec/lib/lite_page/element_factory.rb#L12-L19
train
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.price_scale
def price_scale(definition, order) return definition['scale'][price_paid][0] * order.price, definition['scale'][price_paid][1] * order.price end
ruby
def price_scale(definition, order) return definition['scale'][price_paid][0] * order.price, definition['scale'][price_paid][1] * order.price end
[ "def", "price_scale", "(", "definition", ",", "order", ")", "return", "definition", "[", "'scale'", "]", "[", "price_paid", "]", "[", "0", "]", "*", "order", ".", "price", ",", "definition", "[", "'scale'", "]", "[", "price_paid", "]", "[", "1", "]", "*", "order", ".", "price", "end" ]
Calculates the prices according to the `scale` definition.
[ "Calculates", "the", "prices", "according", "to", "the", "scale", "definition", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L47-L49
train
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.price_set
def price_set(definition, order) if order.price != definition['set'][price_paid] log_order(order) log_error 'order matched but price differs; ignoring this order.' p order p definition return 0, 0 else return definition['set']['half'], definition['set']['full'] end end
ruby
def price_set(definition, order) if order.price != definition['set'][price_paid] log_order(order) log_error 'order matched but price differs; ignoring this order.' p order p definition return 0, 0 else return definition['set']['half'], definition['set']['full'] end end
[ "def", "price_set", "(", "definition", ",", "order", ")", "if", "order", ".", "price", "!=", "definition", "[", "'set'", "]", "[", "price_paid", "]", "log_order", "(", "order", ")", "log_error", "'order matched but price differs; ignoring this order.'", "p", "order", "p", "definition", "return", "0", ",", "0", "else", "return", "definition", "[", "'set'", "]", "[", "'half'", "]", ",", "definition", "[", "'set'", "]", "[", "'full'", "]", "end", "end" ]
Calculates the prices according to the `set` definition.
[ "Calculates", "the", "prices", "according", "to", "the", "set", "definition", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L52-L62
train
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.price_choices
def price_choices(definition, order) # auto select definition['choices'].each { |name,prices| return prices['half'], prices['full'] if prices[price_paid] == order.price } return price_guess_get(order) if @force_guess_fallback choose do |menu| menu.prompt = "\nSelect the choice that applies to your travels? " log_info "\n" definition['choices'].each do |name,prices| menu.choice "#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})" do end end menu.choice "…or enter manually" do ask_for_price(order) end end end
ruby
def price_choices(definition, order) # auto select definition['choices'].each { |name,prices| return prices['half'], prices['full'] if prices[price_paid] == order.price } return price_guess_get(order) if @force_guess_fallback choose do |menu| menu.prompt = "\nSelect the choice that applies to your travels? " log_info "\n" definition['choices'].each do |name,prices| menu.choice "#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})" do end end menu.choice "…or enter manually" do ask_for_price(order) end end end
[ "def", "price_choices", "(", "definition", ",", "order", ")", "definition", "[", "'choices'", "]", ".", "each", "{", "|", "name", ",", "prices", "|", "return", "prices", "[", "'half'", "]", ",", "prices", "[", "'full'", "]", "if", "prices", "[", "price_paid", "]", "==", "order", ".", "price", "}", "return", "price_guess_get", "(", "order", ")", "if", "@force_guess_fallback", "choose", "do", "|", "menu", "|", "menu", ".", "prompt", "=", "\"\\nSelect the choice that applies to your travels? \"", "log_info", "\"\\n\"", "definition", "[", "'choices'", "]", ".", "each", "do", "|", "name", ",", "prices", "|", "menu", ".", "choice", "\"#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})\"", "do", "end", "end", "menu", ".", "choice", "\"…or enter manually\" d", " a", "k_for_price(o", "r", "der) ", "e", "d", "end", "end" ]
Calculates the prices according to the `choices` definition.
[ "Calculates", "the", "prices", "according", "to", "the", "choices", "definition", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L65-L81
train
rndstr/halffare
lib/halffare/price_sbb.rb
Halffare.PriceSbb.ask_for_price
def ask_for_price(order) guesshalf, guessfull = price_guess_get(order) if !Halffare.debug # was already logged log_order(order) end if @halffare other = ask("What would have been the full price? ", Float) { |q| q.default = guessfull } return order.price, other else other = ask("What would have been the half-fare price? ", Float) { |q| q.default = guesshalf } return other, order.price end end
ruby
def ask_for_price(order) guesshalf, guessfull = price_guess_get(order) if !Halffare.debug # was already logged log_order(order) end if @halffare other = ask("What would have been the full price? ", Float) { |q| q.default = guessfull } return order.price, other else other = ask("What would have been the half-fare price? ", Float) { |q| q.default = guesshalf } return other, order.price end end
[ "def", "ask_for_price", "(", "order", ")", "guesshalf", ",", "guessfull", "=", "price_guess_get", "(", "order", ")", "if", "!", "Halffare", ".", "debug", "log_order", "(", "order", ")", "end", "if", "@halffare", "other", "=", "ask", "(", "\"What would have been the full price? \"", ",", "Float", ")", "{", "|", "q", "|", "q", ".", "default", "=", "guessfull", "}", "return", "order", ".", "price", ",", "other", "else", "other", "=", "ask", "(", "\"What would have been the half-fare price? \"", ",", "Float", ")", "{", "|", "q", "|", "q", ".", "default", "=", "guesshalf", "}", "return", "other", ",", "order", ".", "price", "end", "end" ]
Ask the user for the price.
[ "Ask", "the", "user", "for", "the", "price", "." ]
2c4c7563a9e0834e5d2d93c15bd052bb67f8996a
https://github.com/rndstr/halffare/blob/2c4c7563a9e0834e5d2d93c15bd052bb67f8996a/lib/halffare/price_sbb.rb#L84-L99
train
jns/Aims
lib/aims/volume.rb
Aims.Volume.bounding_box
def bounding_box unless @bbox p = @points[0] minX = p[0] maxX = p[0] minY = p[1] maxY = p[1] minZ = p[2] maxZ = p[2] @points.each{|p| minX = p[0] if p[0] < minX maxX = p[0] if p[0] > maxX minY = p[1] if p[1] < minY maxY = p[1] if p[1] > maxY minZ = p[2] if p[2] < minZ maxZ = p[2] if p[2] > maxZ } @max = Vector[maxX, maxY,maxZ] @min = Vector[minX, minY, minZ] @bbox = Volume.new([Plane.new(-1,0,0, minX, minY, minZ), Plane.new(0,-1,0, minX, minY, minZ), Plane.new(0,0,-1, minX, minY, minZ), Plane.new(1,0,0, maxX, maxY, maxZ), Plane.new(0,1,0, maxX, maxY, maxZ), Plane.new(0,0,1, maxX, maxY, maxZ)]) end @bbox end
ruby
def bounding_box unless @bbox p = @points[0] minX = p[0] maxX = p[0] minY = p[1] maxY = p[1] minZ = p[2] maxZ = p[2] @points.each{|p| minX = p[0] if p[0] < minX maxX = p[0] if p[0] > maxX minY = p[1] if p[1] < minY maxY = p[1] if p[1] > maxY minZ = p[2] if p[2] < minZ maxZ = p[2] if p[2] > maxZ } @max = Vector[maxX, maxY,maxZ] @min = Vector[minX, minY, minZ] @bbox = Volume.new([Plane.new(-1,0,0, minX, minY, minZ), Plane.new(0,-1,0, minX, minY, minZ), Plane.new(0,0,-1, minX, minY, minZ), Plane.new(1,0,0, maxX, maxY, maxZ), Plane.new(0,1,0, maxX, maxY, maxZ), Plane.new(0,0,1, maxX, maxY, maxZ)]) end @bbox end
[ "def", "bounding_box", "unless", "@bbox", "p", "=", "@points", "[", "0", "]", "minX", "=", "p", "[", "0", "]", "maxX", "=", "p", "[", "0", "]", "minY", "=", "p", "[", "1", "]", "maxY", "=", "p", "[", "1", "]", "minZ", "=", "p", "[", "2", "]", "maxZ", "=", "p", "[", "2", "]", "@points", ".", "each", "{", "|", "p", "|", "minX", "=", "p", "[", "0", "]", "if", "p", "[", "0", "]", "<", "minX", "maxX", "=", "p", "[", "0", "]", "if", "p", "[", "0", "]", ">", "maxX", "minY", "=", "p", "[", "1", "]", "if", "p", "[", "1", "]", "<", "minY", "maxY", "=", "p", "[", "1", "]", "if", "p", "[", "1", "]", ">", "maxY", "minZ", "=", "p", "[", "2", "]", "if", "p", "[", "2", "]", "<", "minZ", "maxZ", "=", "p", "[", "2", "]", "if", "p", "[", "2", "]", ">", "maxZ", "}", "@max", "=", "Vector", "[", "maxX", ",", "maxY", ",", "maxZ", "]", "@min", "=", "Vector", "[", "minX", ",", "minY", ",", "minZ", "]", "@bbox", "=", "Volume", ".", "new", "(", "[", "Plane", ".", "new", "(", "-", "1", ",", "0", ",", "0", ",", "minX", ",", "minY", ",", "minZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "-", "1", ",", "0", ",", "minX", ",", "minY", ",", "minZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "0", ",", "-", "1", ",", "minX", ",", "minY", ",", "minZ", ")", ",", "Plane", ".", "new", "(", "1", ",", "0", ",", "0", ",", "maxX", ",", "maxY", ",", "maxZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "1", ",", "0", ",", "maxX", ",", "maxY", ",", "maxZ", ")", ",", "Plane", ".", "new", "(", "0", ",", "0", ",", "1", ",", "maxX", ",", "maxY", ",", "maxZ", ")", "]", ")", "end", "@bbox", "end" ]
Return the bounding box for this volume
[ "Return", "the", "bounding", "box", "for", "this", "volume" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/volume.rb#L83-L110
train
jns/Aims
lib/aims/volume.rb
Aims.Volume.contains_point
def contains_point(x,y,z) behind = true @planes.each{|p| behind = (0 >= p.distance_to_point(x,y,z)) break if not behind } return behind end
ruby
def contains_point(x,y,z) behind = true @planes.each{|p| behind = (0 >= p.distance_to_point(x,y,z)) break if not behind } return behind end
[ "def", "contains_point", "(", "x", ",", "y", ",", "z", ")", "behind", "=", "true", "@planes", ".", "each", "{", "|", "p", "|", "behind", "=", "(", "0", ">=", "p", ".", "distance_to_point", "(", "x", ",", "y", ",", "z", ")", ")", "break", "if", "not", "behind", "}", "return", "behind", "end" ]
A volume contains a point if it lies behind all the planes
[ "A", "volume", "contains", "a", "point", "if", "it", "lies", "behind", "all", "the", "planes" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/volume.rb#L131-L138
train
NU-CBITS/bit_core
app/models/bit_core/content_module.rb
BitCore.ContentModule.provider
def provider(position) content_providers.find_by(position: position) || ContentProviders::Null.new(self, position) end
ruby
def provider(position) content_providers.find_by(position: position) || ContentProviders::Null.new(self, position) end
[ "def", "provider", "(", "position", ")", "content_providers", ".", "find_by", "(", "position", ":", "position", ")", "||", "ContentProviders", "::", "Null", ".", "new", "(", "self", ",", "position", ")", "end" ]
Returns the `ContentProvider` at the given position, or a `Null` `ContentProvider` if none exists.
[ "Returns", "the", "ContentProvider", "at", "the", "given", "position", "or", "a", "Null", "ContentProvider", "if", "none", "exists", "." ]
25954c9f9ba0867e7bcd987d9626632b8607cf12
https://github.com/NU-CBITS/bit_core/blob/25954c9f9ba0867e7bcd987d9626632b8607cf12/app/models/bit_core/content_module.rb#L21-L24
train
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/jobs_api.rb
TriglavClient.JobsApi.create_or_update_job
def create_or_update_job(job, opts = {}) data, _status_code, _headers = create_or_update_job_with_http_info(job, opts) return data end
ruby
def create_or_update_job(job, opts = {}) data, _status_code, _headers = create_or_update_job_with_http_info(job, opts) return data end
[ "def", "create_or_update_job", "(", "job", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_or_update_job_with_http_info", "(", "job", ",", "opts", ")", "return", "data", "end" ]
Creates or Updates a single job @param job Job parameters @param [Hash] opts the optional parameters @return [JobResponse]
[ "Creates", "or", "Updates", "a", "single", "job" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/jobs_api.rb#L39-L42
train
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/jobs_api.rb
TriglavClient.JobsApi.get_job
def get_job(id_or_uri, opts = {}) data, _status_code, _headers = get_job_with_http_info(id_or_uri, opts) return data end
ruby
def get_job(id_or_uri, opts = {}) data, _status_code, _headers = get_job_with_http_info(id_or_uri, opts) return data end
[ "def", "get_job", "(", "id_or_uri", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_job_with_http_info", "(", "id_or_uri", ",", "opts", ")", "return", "data", "end" ]
Returns a single job @param id_or_uri ID or URI of job to fetch @param [Hash] opts the optional parameters @return [JobResponse]
[ "Returns", "a", "single", "job" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/jobs_api.rb#L152-L155
train
jochenseeber/rubble
lib/rubble/environment.rb
Rubble.Environment.server
def server(*names, &block) names.each do |name| server = @tool.provide_server(name) scope = Scope.new(self, server) if not block.nil? then Docile.dsl_eval(scope, &block) end end end
ruby
def server(*names, &block) names.each do |name| server = @tool.provide_server(name) scope = Scope.new(self, server) if not block.nil? then Docile.dsl_eval(scope, &block) end end end
[ "def", "server", "(", "*", "names", ",", "&", "block", ")", "names", ".", "each", "do", "|", "name", "|", "server", "=", "@tool", ".", "provide_server", "(", "name", ")", "scope", "=", "Scope", ".", "new", "(", "self", ",", "server", ")", "if", "not", "block", ".", "nil?", "then", "Docile", ".", "dsl_eval", "(", "scope", ",", "&", "block", ")", "end", "end", "end" ]
Action statt plan
[ "Action", "statt", "plan" ]
62f9b45bc1322a1bc4261f162768f6f3008c50ab
https://github.com/jochenseeber/rubble/blob/62f9b45bc1322a1bc4261f162768f6f3008c50ab/lib/rubble/environment.rb#L18-L26
train
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.confirm_action?
def confirm_action?(message) require 'highline/import' quest message response = ask(highline_quest('(y/n)')) do |q| q.default = "n" end return response == 'y' ? true : false end
ruby
def confirm_action?(message) require 'highline/import' quest message response = ask(highline_quest('(y/n)')) do |q| q.default = "n" end return response == 'y' ? true : false end
[ "def", "confirm_action?", "(", "message", ")", "require", "'highline/import'", "quest", "message", "response", "=", "ask", "(", "highline_quest", "(", "'(y/n)'", ")", ")", "do", "|", "q", "|", "q", ".", "default", "=", "\"n\"", "end", "return", "response", "==", "'y'", "?", "true", ":", "false", "end" ]
Ask for confirmation of any action
[ "Ask", "for", "confirmation", "of", "any", "action" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L5-L12
train
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.write_input
def write_input(message, default=nil, validator=nil, not_valid_message=nil) require 'highline/import' response = ask(highline_quest(message)) do |q| q.default = default if default q.validate = /\.(.*)/ if validator q.responses[:not_valid] = highline_warn(not_valid_message) if not_valid_message end return response end
ruby
def write_input(message, default=nil, validator=nil, not_valid_message=nil) require 'highline/import' response = ask(highline_quest(message)) do |q| q.default = default if default q.validate = /\.(.*)/ if validator q.responses[:not_valid] = highline_warn(not_valid_message) if not_valid_message end return response end
[ "def", "write_input", "(", "message", ",", "default", "=", "nil", ",", "validator", "=", "nil", ",", "not_valid_message", "=", "nil", ")", "require", "'highline/import'", "response", "=", "ask", "(", "highline_quest", "(", "message", ")", ")", "do", "|", "q", "|", "q", ".", "default", "=", "default", "if", "default", "q", ".", "validate", "=", "/", "\\.", "/", "if", "validator", "q", ".", "responses", "[", ":not_valid", "]", "=", "highline_warn", "(", "not_valid_message", ")", "if", "not_valid_message", "end", "return", "response", "end" ]
Ask to write some input with validation
[ "Ask", "to", "write", "some", "input", "with", "validation" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L15-L23
train
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.choose_option
def choose_option(options, question) require 'highline/import' choose do |menu| menu.header = title(question) options.each do |option| menu.choice(option) end end end
ruby
def choose_option(options, question) require 'highline/import' choose do |menu| menu.header = title(question) options.each do |option| menu.choice(option) end end end
[ "def", "choose_option", "(", "options", ",", "question", ")", "require", "'highline/import'", "choose", "do", "|", "menu", "|", "menu", ".", "header", "=", "title", "(", "question", ")", "options", ".", "each", "do", "|", "option", "|", "menu", ".", "choice", "(", "option", ")", "end", "end", "end" ]
Asks to choose an option
[ "Asks", "to", "choose", "an", "option" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L26-L34
train
codescrum/bebox
lib/bebox/wizards/wizards_helper.rb
Bebox.WizardsHelper.valid_puppet_class_name?
def valid_puppet_class_name?(name) valid_name = (name =~ /\A[a-z][a-z0-9_]*\Z/).nil? ? false : true valid_name && !Bebox::RESERVED_WORDS.include?(name) end
ruby
def valid_puppet_class_name?(name) valid_name = (name =~ /\A[a-z][a-z0-9_]*\Z/).nil? ? false : true valid_name && !Bebox::RESERVED_WORDS.include?(name) end
[ "def", "valid_puppet_class_name?", "(", "name", ")", "valid_name", "=", "(", "name", "=~", "/", "\\A", "\\Z", "/", ")", ".", "nil?", "?", "false", ":", "true", "valid_name", "&&", "!", "Bebox", "::", "RESERVED_WORDS", ".", "include?", "(", "name", ")", "end" ]
Check if the puppet resource has a valid name
[ "Check", "if", "the", "puppet", "resource", "has", "a", "valid", "name" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/wizards_helper.rb#L37-L40
train
treeder/quicky
lib/quicky/timer.rb
Quicky.Timer.loop_for
def loop_for(name, seconds, options={}, &blk) end_at = Time.now + seconds if options[:warmup] options[:warmup].times do |i| #puts "Warming up... #{i}" yield i end end i = 0 while Time.now < end_at time_i(i, name, options, &blk) i += 1 end end
ruby
def loop_for(name, seconds, options={}, &blk) end_at = Time.now + seconds if options[:warmup] options[:warmup].times do |i| #puts "Warming up... #{i}" yield i end end i = 0 while Time.now < end_at time_i(i, name, options, &blk) i += 1 end end
[ "def", "loop_for", "(", "name", ",", "seconds", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "end_at", "=", "Time", ".", "now", "+", "seconds", "if", "options", "[", ":warmup", "]", "options", "[", ":warmup", "]", ".", "times", "do", "|", "i", "|", "yield", "i", "end", "end", "i", "=", "0", "while", "Time", ".", "now", "<", "end_at", "time_i", "(", "i", ",", "name", ",", "options", ",", "&", "blk", ")", "i", "+=", "1", "end", "end" ]
will loop for number of seconds
[ "will", "loop", "for", "number", "of", "seconds" ]
4ac89408c28ca04745280a4cef2db4f97ed5b6d2
https://github.com/treeder/quicky/blob/4ac89408c28ca04745280a4cef2db4f97ed5b6d2/lib/quicky/timer.rb#L24-L37
train
Bastes/CellularMap
lib/cellular_map/zone.rb
CellularMap.Zone.relative
def relative(x, y) if x.respond_to?(:to_i) && y.respond_to?(:to_i) [@x.min + x.to_i, @y.min + y.to_i] else x, y = rangeize(x, y) [ (@x.min + x.min)..(@x.min + x.max), (@y.min + y.min)..(@y.min + y.max) ] end end
ruby
def relative(x, y) if x.respond_to?(:to_i) && y.respond_to?(:to_i) [@x.min + x.to_i, @y.min + y.to_i] else x, y = rangeize(x, y) [ (@x.min + x.min)..(@x.min + x.max), (@y.min + y.min)..(@y.min + y.max) ] end end
[ "def", "relative", "(", "x", ",", "y", ")", "if", "x", ".", "respond_to?", "(", ":to_i", ")", "&&", "y", ".", "respond_to?", "(", ":to_i", ")", "[", "@x", ".", "min", "+", "x", ".", "to_i", ",", "@y", ".", "min", "+", "y", ".", "to_i", "]", "else", "x", ",", "y", "=", "rangeize", "(", "x", ",", "y", ")", "[", "(", "@x", ".", "min", "+", "x", ".", "min", ")", "..", "(", "@x", ".", "min", "+", "x", ".", "max", ")", ",", "(", "@y", ".", "min", "+", "y", ".", "min", ")", "..", "(", "@y", ".", "min", "+", "y", ".", "max", ")", "]", "end", "end" ]
Converts coordinates to coordinates relative to inside the map.
[ "Converts", "coordinates", "to", "coordinates", "relative", "to", "inside", "the", "map", "." ]
e9cfa44ce820b16cdc5ca5b59291e80e53363d1f
https://github.com/Bastes/CellularMap/blob/e9cfa44ce820b16cdc5ca5b59291e80e53363d1f/lib/cellular_map/zone.rb#L68-L76
train
Bastes/CellularMap
lib/cellular_map/zone.rb
CellularMap.Zone.rangeize
def rangeize(x, y) [x, y].collect { |i| i.respond_to?(:to_i) ? (i.to_i..i.to_i) : i } end
ruby
def rangeize(x, y) [x, y].collect { |i| i.respond_to?(:to_i) ? (i.to_i..i.to_i) : i } end
[ "def", "rangeize", "(", "x", ",", "y", ")", "[", "x", ",", "y", "]", ".", "collect", "{", "|", "i", "|", "i", ".", "respond_to?", "(", ":to_i", ")", "?", "(", "i", ".", "to_i", "..", "i", ".", "to_i", ")", ":", "i", "}", "end" ]
Converts given coordinates to ranges if necessary.
[ "Converts", "given", "coordinates", "to", "ranges", "if", "necessary", "." ]
e9cfa44ce820b16cdc5ca5b59291e80e53363d1f
https://github.com/Bastes/CellularMap/blob/e9cfa44ce820b16cdc5ca5b59291e80e53363d1f/lib/cellular_map/zone.rb#L79-L81
train
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.set_attribute_inverse
def set_attribute_inverse(attribute, inverse) prop = property(attribute) # the standard attribute pa = prop.attribute # return if inverse is already set return if prop.inverse == inverse # the default inverse inverse ||= prop.type.detect_inverse_attribute(self) # If the attribute is not declared by this class, then make a new attribute # metadata specialized for this class. unless prop.declarer == self then prop = restrict_attribute_inverse(prop, inverse) end logger.debug { "Setting #{qp}.#{pa} inverse to #{inverse}..." } # the inverse attribute meta-data inv_prop = prop.type.property(inverse) # If the attribute is the many side of a 1:M relation, then delegate to the one side. if prop.collection? and not inv_prop.collection? then return prop.type.set_attribute_inverse(inverse, pa) end # This class must be the same as or a subclass of the inverse attribute type. unless self <= inv_prop.type then raise TypeError.new("Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}") end # Set the inverse in the attribute metadata. prop.inverse = inverse # If attribute is the one side of a 1:M or non-reflexive 1:1 relation, then add the inverse updater. unless prop.collection? then # Inject adding to the inverse collection into the attribute writer method. add_inverse_updater(pa) unless prop.type == inv_prop.type or inv_prop.collection? then prop.type.delegate_writer_to_inverse(inverse, pa) end end logger.debug { "Set #{qp}.#{pa} inverse to #{inverse}." } end
ruby
def set_attribute_inverse(attribute, inverse) prop = property(attribute) # the standard attribute pa = prop.attribute # return if inverse is already set return if prop.inverse == inverse # the default inverse inverse ||= prop.type.detect_inverse_attribute(self) # If the attribute is not declared by this class, then make a new attribute # metadata specialized for this class. unless prop.declarer == self then prop = restrict_attribute_inverse(prop, inverse) end logger.debug { "Setting #{qp}.#{pa} inverse to #{inverse}..." } # the inverse attribute meta-data inv_prop = prop.type.property(inverse) # If the attribute is the many side of a 1:M relation, then delegate to the one side. if prop.collection? and not inv_prop.collection? then return prop.type.set_attribute_inverse(inverse, pa) end # This class must be the same as or a subclass of the inverse attribute type. unless self <= inv_prop.type then raise TypeError.new("Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}") end # Set the inverse in the attribute metadata. prop.inverse = inverse # If attribute is the one side of a 1:M or non-reflexive 1:1 relation, then add the inverse updater. unless prop.collection? then # Inject adding to the inverse collection into the attribute writer method. add_inverse_updater(pa) unless prop.type == inv_prop.type or inv_prop.collection? then prop.type.delegate_writer_to_inverse(inverse, pa) end end logger.debug { "Set #{qp}.#{pa} inverse to #{inverse}." } end
[ "def", "set_attribute_inverse", "(", "attribute", ",", "inverse", ")", "prop", "=", "property", "(", "attribute", ")", "pa", "=", "prop", ".", "attribute", "return", "if", "prop", ".", "inverse", "==", "inverse", "inverse", "||=", "prop", ".", "type", ".", "detect_inverse_attribute", "(", "self", ")", "unless", "prop", ".", "declarer", "==", "self", "then", "prop", "=", "restrict_attribute_inverse", "(", "prop", ",", "inverse", ")", "end", "logger", ".", "debug", "{", "\"Setting #{qp}.#{pa} inverse to #{inverse}...\"", "}", "inv_prop", "=", "prop", ".", "type", ".", "property", "(", "inverse", ")", "if", "prop", ".", "collection?", "and", "not", "inv_prop", ".", "collection?", "then", "return", "prop", ".", "type", ".", "set_attribute_inverse", "(", "inverse", ",", "pa", ")", "end", "unless", "self", "<=", "inv_prop", ".", "type", "then", "raise", "TypeError", ".", "new", "(", "\"Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}\"", ")", "end", "prop", ".", "inverse", "=", "inverse", "unless", "prop", ".", "collection?", "then", "add_inverse_updater", "(", "pa", ")", "unless", "prop", ".", "type", "==", "inv_prop", ".", "type", "or", "inv_prop", ".", "collection?", "then", "prop", ".", "type", ".", "delegate_writer_to_inverse", "(", "inverse", ",", "pa", ")", "end", "end", "logger", ".", "debug", "{", "\"Set #{qp}.#{pa} inverse to #{inverse}.\"", "}", "end" ]
Sets the given bi-directional association attribute's inverse. @param [Symbol] attribute the subject attribute @param [Symbol] the attribute inverse @raise [TypeError] if the inverse type is incompatible with this Resource
[ "Sets", "the", "given", "bi", "-", "directional", "association", "attribute", "s", "inverse", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L40-L75
train
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.clear_inverse
def clear_inverse(property) # the inverse property ip = property.inverse_property || return # If the property is a collection and the inverse is not, then delegate to # the inverse. if property.collection? then return ip.declarer.clear_inverse(ip) unless ip.collection? else # Restore the property reader and writer to the Java reader and writer, resp. alias_property_accessors(property) end # Unset the inverse. property.inverse = nil end
ruby
def clear_inverse(property) # the inverse property ip = property.inverse_property || return # If the property is a collection and the inverse is not, then delegate to # the inverse. if property.collection? then return ip.declarer.clear_inverse(ip) unless ip.collection? else # Restore the property reader and writer to the Java reader and writer, resp. alias_property_accessors(property) end # Unset the inverse. property.inverse = nil end
[ "def", "clear_inverse", "(", "property", ")", "ip", "=", "property", ".", "inverse_property", "||", "return", "if", "property", ".", "collection?", "then", "return", "ip", ".", "declarer", ".", "clear_inverse", "(", "ip", ")", "unless", "ip", ".", "collection?", "else", "alias_property_accessors", "(", "property", ")", "end", "property", ".", "inverse", "=", "nil", "end" ]
Clears the property inverse, if there is one.
[ "Clears", "the", "property", "inverse", "if", "there", "is", "one", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L78-L91
train
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.detect_inverse_attribute
def detect_inverse_attribute(klass) # The candidate attributes return the referencing type and don't already have an inverse. candidates = domain_attributes.compose { |prop| klass <= prop.type and prop.inverse.nil? } pa = detect_inverse_attribute_from_candidates(klass, candidates) if pa then logger.debug { "#{qp} #{klass.qp} inverse attribute is #{pa}." } else logger.debug { "#{qp} #{klass.qp} inverse attribute was not detected." } end pa end
ruby
def detect_inverse_attribute(klass) # The candidate attributes return the referencing type and don't already have an inverse. candidates = domain_attributes.compose { |prop| klass <= prop.type and prop.inverse.nil? } pa = detect_inverse_attribute_from_candidates(klass, candidates) if pa then logger.debug { "#{qp} #{klass.qp} inverse attribute is #{pa}." } else logger.debug { "#{qp} #{klass.qp} inverse attribute was not detected." } end pa end
[ "def", "detect_inverse_attribute", "(", "klass", ")", "candidates", "=", "domain_attributes", ".", "compose", "{", "|", "prop", "|", "klass", "<=", "prop", ".", "type", "and", "prop", ".", "inverse", ".", "nil?", "}", "pa", "=", "detect_inverse_attribute_from_candidates", "(", "klass", ",", "candidates", ")", "if", "pa", "then", "logger", ".", "debug", "{", "\"#{qp} #{klass.qp} inverse attribute is #{pa}.\"", "}", "else", "logger", ".", "debug", "{", "\"#{qp} #{klass.qp} inverse attribute was not detected.\"", "}", "end", "pa", "end" ]
Detects an unambiguous attribute which refers to the given referencing class. If there is exactly one attribute with the given return type, then that attribute is chosen. Otherwise, the attribute whose name matches the underscored referencing class name is chosen, if any. @param [Class] klass the referencing class @return [Symbol, nil] the inverse attribute for the given referencing class and inverse, or nil if no owner attribute was detected
[ "Detects", "an", "unambiguous", "attribute", "which", "refers", "to", "the", "given", "referencing", "class", ".", "If", "there", "is", "exactly", "one", "attribute", "with", "the", "given", "return", "type", "then", "that", "attribute", "is", "chosen", ".", "Otherwise", "the", "attribute", "whose", "name", "matches", "the", "underscored", "referencing", "class", "name", "is", "chosen", "if", "any", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L101-L111
train
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.delegate_writer_to_inverse
def delegate_writer_to_inverse(attribute, inverse) prop = property(attribute) # nothing to do if no inverse inv_prop = prop.inverse_property || return logger.debug { "Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}..." } # redefine the write to set the dependent inverse redefine_method(prop.writer) do |old_writer| # delegate to the Jinx::Resource set_inverse method lambda { |dep| set_inverse(dep, old_writer, inv_prop.writer) } end end
ruby
def delegate_writer_to_inverse(attribute, inverse) prop = property(attribute) # nothing to do if no inverse inv_prop = prop.inverse_property || return logger.debug { "Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}..." } # redefine the write to set the dependent inverse redefine_method(prop.writer) do |old_writer| # delegate to the Jinx::Resource set_inverse method lambda { |dep| set_inverse(dep, old_writer, inv_prop.writer) } end end
[ "def", "delegate_writer_to_inverse", "(", "attribute", ",", "inverse", ")", "prop", "=", "property", "(", "attribute", ")", "inv_prop", "=", "prop", ".", "inverse_property", "||", "return", "logger", ".", "debug", "{", "\"Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}...\"", "}", "redefine_method", "(", "prop", ".", "writer", ")", "do", "|", "old_writer", "|", "lambda", "{", "|", "dep", "|", "set_inverse", "(", "dep", ",", "old_writer", ",", "inv_prop", ".", "writer", ")", "}", "end", "end" ]
Redefines the attribute writer method to delegate to its inverse writer. This is done to enforce inverse integrity. For a +Person+ attribute +account+ with inverse +holder+, this is equivalent to the following: class Person alias :set_account :account= def account=(acct) acct.holder = self if acct set_account(acct) end end
[ "Redefines", "the", "attribute", "writer", "method", "to", "delegate", "to", "its", "inverse", "writer", ".", "This", "is", "done", "to", "enforce", "inverse", "integrity", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L124-L134
train
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.restrict_attribute_inverse
def restrict_attribute_inverse(prop, inverse) logger.debug { "Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}..." } rst_prop = prop.restrict(self, :inverse => inverse) logger.debug { "Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}." } rst_prop end
ruby
def restrict_attribute_inverse(prop, inverse) logger.debug { "Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}..." } rst_prop = prop.restrict(self, :inverse => inverse) logger.debug { "Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}." } rst_prop end
[ "def", "restrict_attribute_inverse", "(", "prop", ",", "inverse", ")", "logger", ".", "debug", "{", "\"Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}...\"", "}", "rst_prop", "=", "prop", ".", "restrict", "(", "self", ",", ":inverse", "=>", "inverse", ")", "logger", ".", "debug", "{", "\"Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}.\"", "}", "rst_prop", "end" ]
Copies the given attribute metadata from its declarer to this class. The new attribute metadata has the same attribute access methods, but the declarer is this class and the inverse is the given inverse attribute. @param [Property] prop the attribute to copy @param [Symbol] the attribute inverse @return [Property] the copied attribute metadata
[ "Copies", "the", "given", "attribute", "metadata", "from", "its", "declarer", "to", "this", "class", ".", "The", "new", "attribute", "metadata", "has", "the", "same", "attribute", "access", "methods", "but", "the", "declarer", "is", "this", "class", "and", "the", "inverse", "is", "the", "given", "inverse", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L145-L150
train
jinx/core
lib/jinx/metadata/inverse.rb
Jinx.Inverse.add_inverse_updater
def add_inverse_updater(attribute) prop = property(attribute) # the reader and writer methods rdr, wtr = prop.accessors # the inverse attribute metadata inv_prop = prop.inverse_property # the inverse attribute reader and writer inv_rdr, inv_wtr = inv_accessors = inv_prop.accessors # Redefine the writer method to update the inverse by delegating to the inverse. redefine_method(wtr) do |old_wtr| # the attribute reader and (superseded) writer accessors = [rdr, old_wtr] if inv_prop.collection? then lambda { |other| add_to_inverse_collection(other, accessors, inv_rdr) } else lambda { |other| set_inversible_noncollection_attribute(other, accessors, inv_wtr) } end end logger.debug { "Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}." } end
ruby
def add_inverse_updater(attribute) prop = property(attribute) # the reader and writer methods rdr, wtr = prop.accessors # the inverse attribute metadata inv_prop = prop.inverse_property # the inverse attribute reader and writer inv_rdr, inv_wtr = inv_accessors = inv_prop.accessors # Redefine the writer method to update the inverse by delegating to the inverse. redefine_method(wtr) do |old_wtr| # the attribute reader and (superseded) writer accessors = [rdr, old_wtr] if inv_prop.collection? then lambda { |other| add_to_inverse_collection(other, accessors, inv_rdr) } else lambda { |other| set_inversible_noncollection_attribute(other, accessors, inv_wtr) } end end logger.debug { "Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}." } end
[ "def", "add_inverse_updater", "(", "attribute", ")", "prop", "=", "property", "(", "attribute", ")", "rdr", ",", "wtr", "=", "prop", ".", "accessors", "inv_prop", "=", "prop", ".", "inverse_property", "inv_rdr", ",", "inv_wtr", "=", "inv_accessors", "=", "inv_prop", ".", "accessors", "redefine_method", "(", "wtr", ")", "do", "|", "old_wtr", "|", "accessors", "=", "[", "rdr", ",", "old_wtr", "]", "if", "inv_prop", ".", "collection?", "then", "lambda", "{", "|", "other", "|", "add_to_inverse_collection", "(", "other", ",", "accessors", ",", "inv_rdr", ")", "}", "else", "lambda", "{", "|", "other", "|", "set_inversible_noncollection_attribute", "(", "other", ",", "accessors", ",", "inv_wtr", ")", "}", "end", "end", "logger", ".", "debug", "{", "\"Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}.\"", "}", "end" ]
Modifies the given attribute writer method to update the given inverse. @param (see #set_attribute_inverse)
[ "Modifies", "the", "given", "attribute", "writer", "method", "to", "update", "the", "given", "inverse", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/inverse.rb#L168-L187
train
jpsilvashy/epicmix
lib/epicmix.rb
Epicmix.Client.login
def login url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx' options = { :query => { :loginID => username, :password => password }} response = HTTParty.post(url, options) token_from(response) # if response.instance_of? Net::HTTPOK end
ruby
def login url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx' options = { :query => { :loginID => username, :password => password }} response = HTTParty.post(url, options) token_from(response) # if response.instance_of? Net::HTTPOK end
[ "def", "login", "url", "=", "'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx'", "options", "=", "{", ":query", "=>", "{", ":loginID", "=>", "username", ",", ":password", "=>", "password", "}", "}", "response", "=", "HTTParty", ".", "post", "(", "url", ",", "options", ")", "token_from", "(", "response", ")", "end" ]
Initializes and logs in to Epicmix Login to epic mix
[ "Initializes", "and", "logs", "in", "to", "Epicmix", "Login", "to", "epic", "mix" ]
c2d930c78e845f10115171ddd16b58f1db3af009
https://github.com/jpsilvashy/epicmix/blob/c2d930c78e845f10115171ddd16b58f1db3af009/lib/epicmix.rb#L17-L24
train
jpsilvashy/epicmix
lib/epicmix.rb
Epicmix.Client.season_stats
def season_stats url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx' options = { :timetype => 'season', :token => token } response = HTTParty.get(url, :query => options, :headers => headers) JSON.parse(response.body)['seasonStats'] end
ruby
def season_stats url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx' options = { :timetype => 'season', :token => token } response = HTTParty.get(url, :query => options, :headers => headers) JSON.parse(response.body)['seasonStats'] end
[ "def", "season_stats", "url", "=", "'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx'", "options", "=", "{", ":timetype", "=>", "'season'", ",", ":token", "=>", "token", "}", "response", "=", "HTTParty", ".", "get", "(", "url", ",", ":query", "=>", "options", ",", ":headers", "=>", "headers", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "'seasonStats'", "]", "end" ]
Gets all your season stats
[ "Gets", "all", "your", "season", "stats" ]
c2d930c78e845f10115171ddd16b58f1db3af009
https://github.com/jpsilvashy/epicmix/blob/c2d930c78e845f10115171ddd16b58f1db3af009/lib/epicmix.rb#L27-L34
train
BideoWego/mousevc
lib/mousevc/validation.rb
Mousevc.Validation.min_length?
def min_length?(value, length) has_min_length = coerce_bool (value.length >= length) unless has_min_length @error = "Error, expected value to have at least #{length} characters, got: #{value.length}" end has_min_length end
ruby
def min_length?(value, length) has_min_length = coerce_bool (value.length >= length) unless has_min_length @error = "Error, expected value to have at least #{length} characters, got: #{value.length}" end has_min_length end
[ "def", "min_length?", "(", "value", ",", "length", ")", "has_min_length", "=", "coerce_bool", "(", "value", ".", "length", ">=", "length", ")", "unless", "has_min_length", "@error", "=", "\"Error, expected value to have at least #{length} characters, got: #{value.length}\"", "end", "has_min_length", "end" ]
Returns +true+ if the value has at least the specified length @param value [String] the value @param length [Integer] the length @return [Boolean]
[ "Returns", "+", "true", "+", "if", "the", "value", "has", "at", "least", "the", "specified", "length" ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/validation.rb#L71-L77
train
BideoWego/mousevc
lib/mousevc/validation.rb
Mousevc.Validation.max_length?
def max_length?(value, length) has_max_length = coerce_bool (value.length <= length) unless has_max_length @error = "Error, expected value to have at most #{length} characters, got: #{value.length}" end has_max_length end
ruby
def max_length?(value, length) has_max_length = coerce_bool (value.length <= length) unless has_max_length @error = "Error, expected value to have at most #{length} characters, got: #{value.length}" end has_max_length end
[ "def", "max_length?", "(", "value", ",", "length", ")", "has_max_length", "=", "coerce_bool", "(", "value", ".", "length", "<=", "length", ")", "unless", "has_max_length", "@error", "=", "\"Error, expected value to have at most #{length} characters, got: #{value.length}\"", "end", "has_max_length", "end" ]
Returns +true+ if the value has at most the specified length @param value [String] the value @param length [Integer] the length @return [Boolean]
[ "Returns", "+", "true", "+", "if", "the", "value", "has", "at", "most", "the", "specified", "length" ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/validation.rb#L86-L92
train
BideoWego/mousevc
lib/mousevc/validation.rb
Mousevc.Validation.exact_length?
def exact_length?(value, length) has_exact_length = coerce_bool (value.length == length) unless has_exact_length @error = "Error, expected value to have exactly #{length} characters, got: #{value.length}" end has_exact_length end
ruby
def exact_length?(value, length) has_exact_length = coerce_bool (value.length == length) unless has_exact_length @error = "Error, expected value to have exactly #{length} characters, got: #{value.length}" end has_exact_length end
[ "def", "exact_length?", "(", "value", ",", "length", ")", "has_exact_length", "=", "coerce_bool", "(", "value", ".", "length", "==", "length", ")", "unless", "has_exact_length", "@error", "=", "\"Error, expected value to have exactly #{length} characters, got: #{value.length}\"", "end", "has_exact_length", "end" ]
Returns +true+ if the value has exactly the specified length @param value [String] the value @param length [Integer] the length @return [Boolean]
[ "Returns", "+", "true", "+", "if", "the", "value", "has", "exactly", "the", "specified", "length" ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/validation.rb#L101-L107
train
ktkaushik/beta_invite
app/controllers/beta_invite/beta_invites_controller.rb
BetaInvite.BetaInvitesController.create
def create email = params[:beta_invite][:email] beta_invite = BetaInvite.new( email: email, token: SecureRandom.hex(10) ) if beta_invite.save flash[:success] = "#{email} has been registered for beta invite" # send an email if configured if BetaInviteSetup.send_email_to_admins BetaInvite::BetaInviteNotificationMailer.notify_admins( BetaInviteSetup.from_email, BetaInviteSetup.admin_emails, email, BetaInvite.count ).deliver end if BetaInviteSetup.send_thank_you_email BetaInvite::BetaInviteNotificationMailer.thank_user( BetaInviteSetup.from_email, email ).deliver end redirect_to beta_invites_path else flash[:alert] = beta_invite.errors.full_messages redirect_to new_beta_invite_path end end
ruby
def create email = params[:beta_invite][:email] beta_invite = BetaInvite.new( email: email, token: SecureRandom.hex(10) ) if beta_invite.save flash[:success] = "#{email} has been registered for beta invite" # send an email if configured if BetaInviteSetup.send_email_to_admins BetaInvite::BetaInviteNotificationMailer.notify_admins( BetaInviteSetup.from_email, BetaInviteSetup.admin_emails, email, BetaInvite.count ).deliver end if BetaInviteSetup.send_thank_you_email BetaInvite::BetaInviteNotificationMailer.thank_user( BetaInviteSetup.from_email, email ).deliver end redirect_to beta_invites_path else flash[:alert] = beta_invite.errors.full_messages redirect_to new_beta_invite_path end end
[ "def", "create", "email", "=", "params", "[", ":beta_invite", "]", "[", ":email", "]", "beta_invite", "=", "BetaInvite", ".", "new", "(", "email", ":", "email", ",", "token", ":", "SecureRandom", ".", "hex", "(", "10", ")", ")", "if", "beta_invite", ".", "save", "flash", "[", ":success", "]", "=", "\"#{email} has been registered for beta invite\"", "if", "BetaInviteSetup", ".", "send_email_to_admins", "BetaInvite", "::", "BetaInviteNotificationMailer", ".", "notify_admins", "(", "BetaInviteSetup", ".", "from_email", ",", "BetaInviteSetup", ".", "admin_emails", ",", "email", ",", "BetaInvite", ".", "count", ")", ".", "deliver", "end", "if", "BetaInviteSetup", ".", "send_thank_you_email", "BetaInvite", "::", "BetaInviteNotificationMailer", ".", "thank_user", "(", "BetaInviteSetup", ".", "from_email", ",", "email", ")", ".", "deliver", "end", "redirect_to", "beta_invites_path", "else", "flash", "[", ":alert", "]", "=", "beta_invite", ".", "errors", ".", "full_messages", "redirect_to", "new_beta_invite_path", "end", "end" ]
Save the email and a randomly generated token
[ "Save", "the", "email", "and", "a", "randomly", "generated", "token" ]
9819622812516ac78e54f76cc516d616e993599a
https://github.com/ktkaushik/beta_invite/blob/9819622812516ac78e54f76cc516d616e993599a/app/controllers/beta_invite/beta_invites_controller.rb#L11-L31
train
spox/spockets
lib/spockets/watcher.rb
Spockets.Watcher.stop
def stop if(@runner.nil? && @stop) raise NotRunning.new elsif(@runner.nil? || [email protected]?) @stop = true @runner = nil else @stop = true if(@runner) @runner.raise Resync.new if @runner.alive? && @runner.stop? @runner.join(0.05) if @runner @runner.kill if @runner && @runner.alive? end @runner = nil end nil end
ruby
def stop if(@runner.nil? && @stop) raise NotRunning.new elsif(@runner.nil? || [email protected]?) @stop = true @runner = nil else @stop = true if(@runner) @runner.raise Resync.new if @runner.alive? && @runner.stop? @runner.join(0.05) if @runner @runner.kill if @runner && @runner.alive? end @runner = nil end nil end
[ "def", "stop", "if", "(", "@runner", ".", "nil?", "&&", "@stop", ")", "raise", "NotRunning", ".", "new", "elsif", "(", "@runner", ".", "nil?", "||", "!", "@runner", ".", "alive?", ")", "@stop", "=", "true", "@runner", "=", "nil", "else", "@stop", "=", "true", "if", "(", "@runner", ")", "@runner", ".", "raise", "Resync", ".", "new", "if", "@runner", ".", "alive?", "&&", "@runner", ".", "stop?", "@runner", ".", "join", "(", "0.05", ")", "if", "@runner", "@runner", ".", "kill", "if", "@runner", "&&", "@runner", ".", "alive?", "end", "@runner", "=", "nil", "end", "nil", "end" ]
stop the watcher
[ "stop", "the", "watcher" ]
48a314b0ca34a698489055f7a986d294906b74c1
https://github.com/spox/spockets/blob/48a314b0ca34a698489055f7a986d294906b74c1/lib/spockets/watcher.rb#L39-L55
train
spox/spockets
lib/spockets/watcher.rb
Spockets.Watcher.watch
def watch until(@stop) begin resultset = Kernel.select(@sockets.keys, nil, nil, nil) for sock in resultset[0] string = sock.gets if(sock.closed? || string.nil?) if(@sockets[sock][:closed]) @sockets[sock][:closed].each do |pr| pr[1].call(*([sock]+pr[0])) end end @sockets.delete(sock) else string = clean? ? do_clean(string) : string process(string.dup, sock) end end rescue Resync # break select and relisten # end end @runner = nil end
ruby
def watch until(@stop) begin resultset = Kernel.select(@sockets.keys, nil, nil, nil) for sock in resultset[0] string = sock.gets if(sock.closed? || string.nil?) if(@sockets[sock][:closed]) @sockets[sock][:closed].each do |pr| pr[1].call(*([sock]+pr[0])) end end @sockets.delete(sock) else string = clean? ? do_clean(string) : string process(string.dup, sock) end end rescue Resync # break select and relisten # end end @runner = nil end
[ "def", "watch", "until", "(", "@stop", ")", "begin", "resultset", "=", "Kernel", ".", "select", "(", "@sockets", ".", "keys", ",", "nil", ",", "nil", ",", "nil", ")", "for", "sock", "in", "resultset", "[", "0", "]", "string", "=", "sock", ".", "gets", "if", "(", "sock", ".", "closed?", "||", "string", ".", "nil?", ")", "if", "(", "@sockets", "[", "sock", "]", "[", ":closed", "]", ")", "@sockets", "[", "sock", "]", "[", ":closed", "]", ".", "each", "do", "|", "pr", "|", "pr", "[", "1", "]", ".", "call", "(", "*", "(", "[", "sock", "]", "+", "pr", "[", "0", "]", ")", ")", "end", "end", "@sockets", ".", "delete", "(", "sock", ")", "else", "string", "=", "clean?", "?", "do_clean", "(", "string", ")", ":", "string", "process", "(", "string", ".", "dup", ",", "sock", ")", "end", "end", "rescue", "Resync", "end", "end", "@runner", "=", "nil", "end" ]
Watch the sockets and send strings for processing
[ "Watch", "the", "sockets", "and", "send", "strings", "for", "processing" ]
48a314b0ca34a698489055f7a986d294906b74c1
https://github.com/spox/spockets/blob/48a314b0ca34a698489055f7a986d294906b74c1/lib/spockets/watcher.rb#L76-L99
train
riddopic/hoodie
lib/hoodie/utils/file_helper.rb
Hoodie.FileHelper.command_in_path?
def command_in_path?(command) found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p| File.exist?(File.join(p, command)) end found.include?(true) end
ruby
def command_in_path?(command) found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p| File.exist?(File.join(p, command)) end found.include?(true) end
[ "def", "command_in_path?", "(", "command", ")", "found", "=", "ENV", "[", "'PATH'", "]", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ".", "map", "do", "|", "p", "|", "File", ".", "exist?", "(", "File", ".", "join", "(", "p", ",", "command", ")", ")", "end", "found", ".", "include?", "(", "true", ")", "end" ]
Checks in PATH returns true if the command is found. @param [String] command The name of the command to look for. @return [Boolean] True if the command is found in the path.
[ "Checks", "in", "PATH", "returns", "true", "if", "the", "command", "is", "found", "." ]
921601dd4849845d3f5d3765dafcf00178b2aa66
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/file_helper.rb#L35-L40
train
mbj/ducktrap
lib/ducktrap/pretty_dump.rb
Ducktrap.PrettyDump.pretty_inspect
def pretty_inspect io = StringIO.new formatter = Formatter.new(io) pretty_dump(formatter) io.rewind io.read end
ruby
def pretty_inspect io = StringIO.new formatter = Formatter.new(io) pretty_dump(formatter) io.rewind io.read end
[ "def", "pretty_inspect", "io", "=", "StringIO", ".", "new", "formatter", "=", "Formatter", ".", "new", "(", "io", ")", "pretty_dump", "(", "formatter", ")", "io", ".", "rewind", "io", ".", "read", "end" ]
Return pretty inspection @return [String] @api private
[ "Return", "pretty", "inspection" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/pretty_dump.rb#L22-L28
train
PRX/fixer_client
lib/fixer/response.rb
Fixer.Response.method_missing
def method_missing(method_name, *args, &block) if self.has_key?(method_name.to_s) self.[](method_name, &block) elsif self.body.respond_to?(method_name) self.body.send(method_name, *args, &block) elsif self.request[:api].respond_to?(method_name) self.request[:api].send(method_name, *args, &block) else super end end
ruby
def method_missing(method_name, *args, &block) if self.has_key?(method_name.to_s) self.[](method_name, &block) elsif self.body.respond_to?(method_name) self.body.send(method_name, *args, &block) elsif self.request[:api].respond_to?(method_name) self.request[:api].send(method_name, *args, &block) else super end end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "if", "self", ".", "has_key?", "(", "method_name", ".", "to_s", ")", "self", ".", "[]", "(", "method_name", ",", "&", "block", ")", "elsif", "self", ".", "body", ".", "respond_to?", "(", "method_name", ")", "self", ".", "body", ".", "send", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "elsif", "self", ".", "request", "[", ":api", "]", ".", "respond_to?", "(", "method_name", ")", "self", ".", "request", "[", ":api", "]", ".", "send", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "else", "super", "end", "end" ]
Coerce any method calls for body attributes
[ "Coerce", "any", "method", "calls", "for", "body", "attributes" ]
56dab7912496d3bcefe519eb326c99dcdb754ccf
https://github.com/PRX/fixer_client/blob/56dab7912496d3bcefe519eb326c99dcdb754ccf/lib/fixer/response.rb#L48-L58
train
salesking/sk_sdk
lib/sk_sdk/sync.rb
SK::SDK.Sync.update
def update(side, flds=nil) raise ArgumentError, 'The side to update must be :l or :r' unless [:l, :r].include?(side) target, source = (side==:l) ? [:l, :r] : [:r, :l] # use set field/s or update all flds ||= fields target_obj = self.send("#{target}_obj") source_obj = self.send("#{source}_obj") flds.each do |fld| target_name = fld.send("#{target}_name") source_name = fld.send("#{source}_name") # remember for log old_val = target_obj.send(target_name) rescue 'empty' # get new value through transfer method or direct new_val = if fld.transition? cur_trans = fld.send("#{target}_trans") eval "#{cur_trans} source_obj.send( source_name )" else source_obj.send( source_name ) end target_obj.send( "#{target_name}=" , new_val ) log << "#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}" end end
ruby
def update(side, flds=nil) raise ArgumentError, 'The side to update must be :l or :r' unless [:l, :r].include?(side) target, source = (side==:l) ? [:l, :r] : [:r, :l] # use set field/s or update all flds ||= fields target_obj = self.send("#{target}_obj") source_obj = self.send("#{source}_obj") flds.each do |fld| target_name = fld.send("#{target}_name") source_name = fld.send("#{source}_name") # remember for log old_val = target_obj.send(target_name) rescue 'empty' # get new value through transfer method or direct new_val = if fld.transition? cur_trans = fld.send("#{target}_trans") eval "#{cur_trans} source_obj.send( source_name )" else source_obj.send( source_name ) end target_obj.send( "#{target_name}=" , new_val ) log << "#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}" end end
[ "def", "update", "(", "side", ",", "flds", "=", "nil", ")", "raise", "ArgumentError", ",", "'The side to update must be :l or :r'", "unless", "[", ":l", ",", ":r", "]", ".", "include?", "(", "side", ")", "target", ",", "source", "=", "(", "side", "==", ":l", ")", "?", "[", ":l", ",", ":r", "]", ":", "[", ":r", ",", ":l", "]", "flds", "||=", "fields", "target_obj", "=", "self", ".", "send", "(", "\"#{target}_obj\"", ")", "source_obj", "=", "self", ".", "send", "(", "\"#{source}_obj\"", ")", "flds", ".", "each", "do", "|", "fld", "|", "target_name", "=", "fld", ".", "send", "(", "\"#{target}_name\"", ")", "source_name", "=", "fld", ".", "send", "(", "\"#{source}_name\"", ")", "old_val", "=", "target_obj", ".", "send", "(", "target_name", ")", "rescue", "'empty'", "new_val", "=", "if", "fld", ".", "transition?", "cur_trans", "=", "fld", ".", "send", "(", "\"#{target}_trans\"", ")", "eval", "\"#{cur_trans} source_obj.send( source_name )\"", "else", "source_obj", ".", "send", "(", "source_name", ")", "end", "target_obj", ".", "send", "(", "\"#{target_name}=\"", ",", "new_val", ")", "log", "<<", "\"#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}\"", "end", "end" ]
Update a side with the values from the other side. Populates the log with updated fields and values. @param [String|Symbol] side to update l OR r @param [Array<Field>, nil] flds fields to update, default nil update all fields
[ "Update", "a", "side", "with", "the", "values", "from", "the", "other", "side", ".", "Populates", "the", "log", "with", "updated", "fields", "and", "values", "." ]
03170b2807cc4e1f1ba44c704c308370c6563dbc
https://github.com/salesking/sk_sdk/blob/03170b2807cc4e1f1ba44c704c308370c6563dbc/lib/sk_sdk/sync.rb#L111-L134
train
mdub/pith
lib/pith/input.rb
Pith.Input.ignorable?
def ignorable? @ignorable ||= path.each_filename do |path_component| project.config.ignore_patterns.each do |pattern| return true if File.fnmatch(pattern, path_component) end end end
ruby
def ignorable? @ignorable ||= path.each_filename do |path_component| project.config.ignore_patterns.each do |pattern| return true if File.fnmatch(pattern, path_component) end end end
[ "def", "ignorable?", "@ignorable", "||=", "path", ".", "each_filename", "do", "|", "path_component", "|", "project", ".", "config", ".", "ignore_patterns", ".", "each", "do", "|", "pattern", "|", "return", "true", "if", "File", ".", "fnmatch", "(", "pattern", ",", "path_component", ")", "end", "end", "end" ]
Consider whether this input can be ignored. Returns true if it can.
[ "Consider", "whether", "this", "input", "can", "be", "ignored", "." ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/input.rb#L33-L39
train
mdub/pith
lib/pith/input.rb
Pith.Input.render
def render(context, locals = {}, &block) return file.read if !template? ensure_loaded pipeline.inject(@template_text) do |text, processor| template = processor.new(file.to_s, @template_start_line) { text } template.render(context, locals, &block) end end
ruby
def render(context, locals = {}, &block) return file.read if !template? ensure_loaded pipeline.inject(@template_text) do |text, processor| template = processor.new(file.to_s, @template_start_line) { text } template.render(context, locals, &block) end end
[ "def", "render", "(", "context", ",", "locals", "=", "{", "}", ",", "&", "block", ")", "return", "file", ".", "read", "if", "!", "template?", "ensure_loaded", "pipeline", ".", "inject", "(", "@template_text", ")", "do", "|", "text", ",", "processor", "|", "template", "=", "processor", ".", "new", "(", "file", ".", "to_s", ",", "@template_start_line", ")", "{", "text", "}", "template", ".", "render", "(", "context", ",", "locals", ",", "&", "block", ")", "end", "end" ]
Render this input using Tilt
[ "Render", "this", "input", "using", "Tilt" ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/input.rb#L71-L78
train
mdub/pith
lib/pith/input.rb
Pith.Input.load
def load @load_time = Time.now @meta = {} if template? logger.debug "loading #{path}" file.open do |io| read_meta(io) @template_start_line = io.lineno + 1 @template_text = io.read end end end
ruby
def load @load_time = Time.now @meta = {} if template? logger.debug "loading #{path}" file.open do |io| read_meta(io) @template_start_line = io.lineno + 1 @template_text = io.read end end end
[ "def", "load", "@load_time", "=", "Time", ".", "now", "@meta", "=", "{", "}", "if", "template?", "logger", ".", "debug", "\"loading #{path}\"", "file", ".", "open", "do", "|", "io", "|", "read_meta", "(", "io", ")", "@template_start_line", "=", "io", ".", "lineno", "+", "1", "@template_text", "=", "io", ".", "read", "end", "end", "end" ]
Read input file, extracting YAML meta-data header, and template content.
[ "Read", "input", "file", "extracting", "YAML", "meta", "-", "data", "header", "and", "template", "content", "." ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/input.rb#L188-L199
train
4rlm/utf8_sanitizer
lib/utf8_sanitizer/utf.rb
Utf8Sanitizer.UTF.process_hash_row
def process_hash_row(hsh) if @headers.any? keys_or_values = hsh.values @row_id = hsh[:row_id] else keys_or_values = hsh.keys.map(&:to_s) end file_line = keys_or_values.join(',') validated_line = utf_filter(check_utf(file_line)) res = line_parse(validated_line) res end
ruby
def process_hash_row(hsh) if @headers.any? keys_or_values = hsh.values @row_id = hsh[:row_id] else keys_or_values = hsh.keys.map(&:to_s) end file_line = keys_or_values.join(',') validated_line = utf_filter(check_utf(file_line)) res = line_parse(validated_line) res end
[ "def", "process_hash_row", "(", "hsh", ")", "if", "@headers", ".", "any?", "keys_or_values", "=", "hsh", ".", "values", "@row_id", "=", "hsh", "[", ":row_id", "]", "else", "keys_or_values", "=", "hsh", ".", "keys", ".", "map", "(", "&", ":to_s", ")", "end", "file_line", "=", "keys_or_values", ".", "join", "(", "','", ")", "validated_line", "=", "utf_filter", "(", "check_utf", "(", "file_line", ")", ")", "res", "=", "line_parse", "(", "validated_line", ")", "res", "end" ]
process_hash_row - helper VALIDATE HASHES Converts hash keys and vals into parsed line.
[ "process_hash_row", "-", "helper", "VALIDATE", "HASHES", "Converts", "hash", "keys", "and", "vals", "into", "parsed", "line", "." ]
4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05
https://github.com/4rlm/utf8_sanitizer/blob/4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05/lib/utf8_sanitizer/utf.rb#L63-L75
train
4rlm/utf8_sanitizer
lib/utf8_sanitizer/utf.rb
Utf8Sanitizer.UTF.line_parse
def line_parse(validated_line) return unless validated_line row = validated_line.split(',') return unless row.any? if @headers.empty? @headers = row else @data_hash.merge!(row_to_hsh(row)) @valid_rows << @data_hash end end
ruby
def line_parse(validated_line) return unless validated_line row = validated_line.split(',') return unless row.any? if @headers.empty? @headers = row else @data_hash.merge!(row_to_hsh(row)) @valid_rows << @data_hash end end
[ "def", "line_parse", "(", "validated_line", ")", "return", "unless", "validated_line", "row", "=", "validated_line", ".", "split", "(", "','", ")", "return", "unless", "row", ".", "any?", "if", "@headers", ".", "empty?", "@headers", "=", "row", "else", "@data_hash", ".", "merge!", "(", "row_to_hsh", "(", "row", ")", ")", "@valid_rows", "<<", "@data_hash", "end", "end" ]
line_parse - helper VALIDATE HASHES Parses line to row, then updates final results.
[ "line_parse", "-", "helper", "VALIDATE", "HASHES", "Parses", "line", "to", "row", "then", "updates", "final", "results", "." ]
4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05
https://github.com/4rlm/utf8_sanitizer/blob/4e7cb63cda21e5e4f5c4e954e468fbb4f854bb05/lib/utf8_sanitizer/utf.rb#L79-L89
train
barkerest/shells
lib/shells/shell_base/prompt.rb
Shells.ShellBase.wait_for_prompt
def wait_for_prompt(silence_timeout = nil, command_timeout = nil, timeout_error = true) #:doc: raise Shells::NotRunning unless running? silence_timeout ||= options[:silence_timeout] command_timeout ||= options[:command_timeout] # when did we send a NL and how many have we sent while waiting for output? nudged_at = nil nudge_count = 0 silence_timeout = silence_timeout.to_s.to_f unless silence_timeout.is_a?(Numeric) nudge_seconds = if silence_timeout > 0 (silence_timeout / 3.0) # we want to nudge twice before officially timing out. else 0 end # if there is a limit for the command timeout, then set the absolute timeout for the loop. command_timeout = command_timeout.to_s.to_f unless command_timeout.is_a?(Numeric) timeout = if command_timeout > 0 Time.now + command_timeout else nil end # loop until the output matches the prompt regex. # if something gets output async server side, the silence timeout will be handy in getting the shell to reappear. # a match while waiting for output is invalid, so by requiring that flag to be false this should work with # unbuffered input as well. until output =~ prompt_match && !wait_for_output # hint that we need to let another thread run. Thread.pass last_response = last_output # Do we need to nudge the shell? if nudge_seconds > 0 && (Time.now - last_response) > nudge_seconds nudge_count = (nudged_at.nil? || nudged_at < last_response) ? 1 : (nudge_count + 1) # Have we previously nudged the shell? if nudge_count > 2 # we timeout on the third nudge. raise Shells::SilenceTimeout if timeout_error debug ' > silence timeout' return false else nudged_at = Time.now queue_input line_ending # wait a bit longer... self.last_output = nudged_at end end # honor the absolute timeout. if timeout && Time.now > timeout raise Shells::CommandTimeout if timeout_error debug ' > command timeout' return false end end # make sure there is a newline before the prompt, just to keep everything clean. pos = (output =~ prompt_match) if output[pos - 1] != "\n" # no newline before prompt, fix that. self.output = output[0...pos] + "\n" + output[pos..-1] end # make sure there is a newline at the end of STDOUT content buffer. if stdout[-1] != "\n" # no newline at end, fix that. self.stdout += "\n" end true end
ruby
def wait_for_prompt(silence_timeout = nil, command_timeout = nil, timeout_error = true) #:doc: raise Shells::NotRunning unless running? silence_timeout ||= options[:silence_timeout] command_timeout ||= options[:command_timeout] # when did we send a NL and how many have we sent while waiting for output? nudged_at = nil nudge_count = 0 silence_timeout = silence_timeout.to_s.to_f unless silence_timeout.is_a?(Numeric) nudge_seconds = if silence_timeout > 0 (silence_timeout / 3.0) # we want to nudge twice before officially timing out. else 0 end # if there is a limit for the command timeout, then set the absolute timeout for the loop. command_timeout = command_timeout.to_s.to_f unless command_timeout.is_a?(Numeric) timeout = if command_timeout > 0 Time.now + command_timeout else nil end # loop until the output matches the prompt regex. # if something gets output async server side, the silence timeout will be handy in getting the shell to reappear. # a match while waiting for output is invalid, so by requiring that flag to be false this should work with # unbuffered input as well. until output =~ prompt_match && !wait_for_output # hint that we need to let another thread run. Thread.pass last_response = last_output # Do we need to nudge the shell? if nudge_seconds > 0 && (Time.now - last_response) > nudge_seconds nudge_count = (nudged_at.nil? || nudged_at < last_response) ? 1 : (nudge_count + 1) # Have we previously nudged the shell? if nudge_count > 2 # we timeout on the third nudge. raise Shells::SilenceTimeout if timeout_error debug ' > silence timeout' return false else nudged_at = Time.now queue_input line_ending # wait a bit longer... self.last_output = nudged_at end end # honor the absolute timeout. if timeout && Time.now > timeout raise Shells::CommandTimeout if timeout_error debug ' > command timeout' return false end end # make sure there is a newline before the prompt, just to keep everything clean. pos = (output =~ prompt_match) if output[pos - 1] != "\n" # no newline before prompt, fix that. self.output = output[0...pos] + "\n" + output[pos..-1] end # make sure there is a newline at the end of STDOUT content buffer. if stdout[-1] != "\n" # no newline at end, fix that. self.stdout += "\n" end true end
[ "def", "wait_for_prompt", "(", "silence_timeout", "=", "nil", ",", "command_timeout", "=", "nil", ",", "timeout_error", "=", "true", ")", "raise", "Shells", "::", "NotRunning", "unless", "running?", "silence_timeout", "||=", "options", "[", ":silence_timeout", "]", "command_timeout", "||=", "options", "[", ":command_timeout", "]", "nudged_at", "=", "nil", "nudge_count", "=", "0", "silence_timeout", "=", "silence_timeout", ".", "to_s", ".", "to_f", "unless", "silence_timeout", ".", "is_a?", "(", "Numeric", ")", "nudge_seconds", "=", "if", "silence_timeout", ">", "0", "(", "silence_timeout", "/", "3.0", ")", "else", "0", "end", "command_timeout", "=", "command_timeout", ".", "to_s", ".", "to_f", "unless", "command_timeout", ".", "is_a?", "(", "Numeric", ")", "timeout", "=", "if", "command_timeout", ">", "0", "Time", ".", "now", "+", "command_timeout", "else", "nil", "end", "until", "output", "=~", "prompt_match", "&&", "!", "wait_for_output", "Thread", ".", "pass", "last_response", "=", "last_output", "if", "nudge_seconds", ">", "0", "&&", "(", "Time", ".", "now", "-", "last_response", ")", ">", "nudge_seconds", "nudge_count", "=", "(", "nudged_at", ".", "nil?", "||", "nudged_at", "<", "last_response", ")", "?", "1", ":", "(", "nudge_count", "+", "1", ")", "if", "nudge_count", ">", "2", "raise", "Shells", "::", "SilenceTimeout", "if", "timeout_error", "debug", "' > silence timeout'", "return", "false", "else", "nudged_at", "=", "Time", ".", "now", "queue_input", "line_ending", "self", ".", "last_output", "=", "nudged_at", "end", "end", "if", "timeout", "&&", "Time", ".", "now", ">", "timeout", "raise", "Shells", "::", "CommandTimeout", "if", "timeout_error", "debug", "' > command timeout'", "return", "false", "end", "end", "pos", "=", "(", "output", "=~", "prompt_match", ")", "if", "output", "[", "pos", "-", "1", "]", "!=", "\"\\n\"", "self", ".", "output", "=", "output", "[", "0", "...", "pos", "]", "+", "\"\\n\"", "+", "output", "[", "pos", "..", "-", "1", "]", "end", "if", "stdout", "[", "-", "1", "]", "!=", "\"\\n\"", "self", ".", "stdout", "+=", "\"\\n\"", "end", "true", "end" ]
Waits for the prompt to appear at the end of the output. Once the prompt appears, new input can be sent to the shell. This is automatically called in +exec+ so you would only need to call it directly if you were sending data manually to the shell. This method is used internally in the +exec+ method, but there may be legitimate use cases outside of that method as well.
[ "Waits", "for", "the", "prompt", "to", "appear", "at", "the", "end", "of", "the", "output", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/prompt.rb#L46-L124
train
barkerest/shells
lib/shells/shell_base/prompt.rb
Shells.ShellBase.temporary_prompt
def temporary_prompt(prompt) #:doc: raise Shells::NotRunning unless running? old_prompt = prompt_match begin self.prompt_match = prompt yield if block_given? ensure self.prompt_match = old_prompt end end
ruby
def temporary_prompt(prompt) #:doc: raise Shells::NotRunning unless running? old_prompt = prompt_match begin self.prompt_match = prompt yield if block_given? ensure self.prompt_match = old_prompt end end
[ "def", "temporary_prompt", "(", "prompt", ")", "raise", "Shells", "::", "NotRunning", "unless", "running?", "old_prompt", "=", "prompt_match", "begin", "self", ".", "prompt_match", "=", "prompt", "yield", "if", "block_given?", "ensure", "self", ".", "prompt_match", "=", "old_prompt", "end", "end" ]
Sets the prompt to the value temporarily for execution of the code block.
[ "Sets", "the", "prompt", "to", "the", "value", "temporarily", "for", "execution", "of", "the", "code", "block", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/prompt.rb#L128-L137
train
jakewendt/simply_authorized
generators/simply_authorized/simply_authorized_generator.rb
Rails::Generator::Commands.Base.next_migration_string
def next_migration_string(padding = 3) @s = ([email protected]?)? @s.to_i + 1 : if ActiveRecord::Base.timestamped_migrations Time.now.utc.strftime("%Y%m%d%H%M%S") else "%.#{padding}d" % next_migration_number end end
ruby
def next_migration_string(padding = 3) @s = ([email protected]?)? @s.to_i + 1 : if ActiveRecord::Base.timestamped_migrations Time.now.utc.strftime("%Y%m%d%H%M%S") else "%.#{padding}d" % next_migration_number end end
[ "def", "next_migration_string", "(", "padding", "=", "3", ")", "@s", "=", "(", "!", "@s", ".", "nil?", ")", "?", "@s", ".", "to_i", "+", "1", ":", "if", "ActiveRecord", "::", "Base", ".", "timestamped_migrations", "Time", ".", "now", ".", "utc", ".", "strftime", "(", "\"%Y%m%d%H%M%S\"", ")", "else", "\"%.#{padding}d\"", "%", "next_migration_number", "end", "end" ]
the loop through migrations happens so fast that they all have the same timestamp which won't work when you actually try to migrate. All the timestamps MUST be unique.
[ "the", "loop", "through", "migrations", "happens", "so", "fast", "that", "they", "all", "have", "the", "same", "timestamp", "which", "won", "t", "work", "when", "you", "actually", "try", "to", "migrate", ".", "All", "the", "timestamps", "MUST", "be", "unique", "." ]
11a1c8bfdf1561bf14243a516cdbe901aac55e53
https://github.com/jakewendt/simply_authorized/blob/11a1c8bfdf1561bf14243a516cdbe901aac55e53/generators/simply_authorized/simply_authorized_generator.rb#L76-L82
train
Hubro/rozi
lib/rozi/shared.rb
Rozi.Shared.interpret_color
def interpret_color(color) if color.is_a? String # Turns RRGGBB into BBGGRR for hex conversion. color = color[-2..-1] << color[2..3] << color[0..1] color = color.to_i(16) end color end
ruby
def interpret_color(color) if color.is_a? String # Turns RRGGBB into BBGGRR for hex conversion. color = color[-2..-1] << color[2..3] << color[0..1] color = color.to_i(16) end color end
[ "def", "interpret_color", "(", "color", ")", "if", "color", ".", "is_a?", "String", "color", "=", "color", "[", "-", "2", "..", "-", "1", "]", "<<", "color", "[", "2", "..", "3", "]", "<<", "color", "[", "0", "..", "1", "]", "color", "=", "color", ".", "to_i", "(", "16", ")", "end", "color", "end" ]
Converts the input to an RGB color represented by an integer @param [String, Integer] color Can be a RRGGBB hex string or an integer @return [Integer] @example interpret_color(255) # => 255 interpret_color("ABCDEF") # => 15715755
[ "Converts", "the", "input", "to", "an", "RGB", "color", "represented", "by", "an", "integer" ]
05a52dcc947be2e9bd0c7e881b9770239b28290a
https://github.com/Hubro/rozi/blob/05a52dcc947be2e9bd0c7e881b9770239b28290a/lib/rozi/shared.rb#L34-L42
train
BideoWego/mousevc
lib/mousevc/app.rb
Mousevc.App.listen
def listen begin clear_view @router.route unless Input.quit? reset if Input.reset? end until Input.quit? end
ruby
def listen begin clear_view @router.route unless Input.quit? reset if Input.reset? end until Input.quit? end
[ "def", "listen", "begin", "clear_view", "@router", ".", "route", "unless", "Input", ".", "quit?", "reset", "if", "Input", ".", "reset?", "end", "until", "Input", ".", "quit?", "end" ]
Runs the application loop. Clears the system view each iteration. Calls route on the router instance. If the user is trying to reset or quit the application responds accordingly. Clears Input class variables before exit.
[ "Runs", "the", "application", "loop", ".", "Clears", "the", "system", "view", "each", "iteration", ".", "Calls", "route", "on", "the", "router", "instance", "." ]
71bc2240afa3353250e39e50b3cb6a762a452836
https://github.com/BideoWego/mousevc/blob/71bc2240afa3353250e39e50b3cb6a762a452836/lib/mousevc/app.rb#L124-L130
train
jinx/core
lib/jinx/helpers/log.rb
Jinx.MultilineLogger.format_message
def format_message(severity, datetime, progname, msg) if String === msg then msg.inject('') { |s, line| s << super(severity, datetime, progname, line.chomp) } else super end end
ruby
def format_message(severity, datetime, progname, msg) if String === msg then msg.inject('') { |s, line| s << super(severity, datetime, progname, line.chomp) } else super end end
[ "def", "format_message", "(", "severity", ",", "datetime", ",", "progname", ",", "msg", ")", "if", "String", "===", "msg", "then", "msg", ".", "inject", "(", "''", ")", "{", "|", "s", ",", "line", "|", "s", "<<", "super", "(", "severity", ",", "datetime", ",", "progname", ",", "line", ".", "chomp", ")", "}", "else", "super", "end", "end" ]
Writes msg to the log device. Each line in msg is formatted separately. @param (see Logger#format_message) @return (see Logger#format_message)
[ "Writes", "msg", "to", "the", "log", "device", ".", "Each", "line", "in", "msg", "is", "formatted", "separately", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/log.rb#L39-L45
train
stormbrew/user_input
lib/user_input/type_safe_hash.rb
UserInput.TypeSafeHash.each_pair
def each_pair(type, default = nil) real_hash.each_key() { |key| value = fetch(key, type, default) if (!value.nil?) yield(key, value) end } end
ruby
def each_pair(type, default = nil) real_hash.each_key() { |key| value = fetch(key, type, default) if (!value.nil?) yield(key, value) end } end
[ "def", "each_pair", "(", "type", ",", "default", "=", "nil", ")", "real_hash", ".", "each_key", "(", ")", "{", "|", "key", "|", "value", "=", "fetch", "(", "key", ",", "type", ",", "default", ")", "if", "(", "!", "value", ".", "nil?", ")", "yield", "(", "key", ",", "value", ")", "end", "}", "end" ]
Enumerates the key, value pairs in the has.
[ "Enumerates", "the", "key", "value", "pairs", "in", "the", "has", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/type_safe_hash.rb#L60-L67
train
stormbrew/user_input
lib/user_input/type_safe_hash.rb
UserInput.TypeSafeHash.each_match
def each_match(regex, type, default = nil) real_hash.each_key() { |key| if (matchinfo = regex.match(key)) value = fetch(key, type, default) if (!value.nil?) yield(matchinfo, value) end end } end
ruby
def each_match(regex, type, default = nil) real_hash.each_key() { |key| if (matchinfo = regex.match(key)) value = fetch(key, type, default) if (!value.nil?) yield(matchinfo, value) end end } end
[ "def", "each_match", "(", "regex", ",", "type", ",", "default", "=", "nil", ")", "real_hash", ".", "each_key", "(", ")", "{", "|", "key", "|", "if", "(", "matchinfo", "=", "regex", ".", "match", "(", "key", ")", ")", "value", "=", "fetch", "(", "key", ",", "type", ",", "default", ")", "if", "(", "!", "value", ".", "nil?", ")", "yield", "(", "matchinfo", ",", "value", ")", "end", "end", "}", "end" ]
Enumerates keys that match a regex, passing the match object and the value.
[ "Enumerates", "keys", "that", "match", "a", "regex", "passing", "the", "match", "object", "and", "the", "value", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/type_safe_hash.rb#L71-L80
train
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.attributes_hash
def attributes_hash attributes = @scope.attributes.collect do |attr| value = fetch_property(attr) if value.kind_of?(BigDecimal) value = value.to_f end [attr, value] end Hash[attributes] end
ruby
def attributes_hash attributes = @scope.attributes.collect do |attr| value = fetch_property(attr) if value.kind_of?(BigDecimal) value = value.to_f end [attr, value] end Hash[attributes] end
[ "def", "attributes_hash", "attributes", "=", "@scope", ".", "attributes", ".", "collect", "do", "|", "attr", "|", "value", "=", "fetch_property", "(", "attr", ")", "if", "value", ".", "kind_of?", "(", "BigDecimal", ")", "value", "=", "value", ".", "to_f", "end", "[", "attr", ",", "value", "]", "end", "Hash", "[", "attributes", "]", "end" ]
Collects attributes for serialization. Attributes can be overwritten in the serializer. @return [Hash]
[ "Collects", "attributes", "for", "serialization", ".", "Attributes", "can", "be", "overwritten", "in", "the", "serializer", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L96-L108
train
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.associations_hash
def associations_hash hash = {} @scope.associations.each do |association, options| hash.merge!(render_association(association, options)) end hash end
ruby
def associations_hash hash = {} @scope.associations.each do |association, options| hash.merge!(render_association(association, options)) end hash end
[ "def", "associations_hash", "hash", "=", "{", "}", "@scope", ".", "associations", ".", "each", "do", "|", "association", ",", "options", "|", "hash", ".", "merge!", "(", "render_association", "(", "association", ",", "options", ")", ")", "end", "hash", "end" ]
Collects associations for serialization. Associations can be overwritten in the serializer. @return [Hash]
[ "Collects", "associations", "for", "serialization", ".", "Associations", "can", "be", "overwritten", "in", "the", "serializer", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L116-L122
train
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.render_association
def render_association(association_data, options={}) hash = {} if association_data.is_a?(Hash) association_data.each do |association, association_options| data = render_association(association, options.merge(:include => association_options)) hash.merge!(data) if data end elsif association_data.is_a?(Array) association_data.each do |option| data = render_association(option) hash.merge!(data) if data end else if options[:preload] includes = options[:preload] == true ? options[:include] : options[:preload] end if (object = fetch_association(association_data, includes)) data = ScopedSerializer.for(object, options.merge(:associations => options[:include])).as_json hash.merge!(data) if data end end hash end
ruby
def render_association(association_data, options={}) hash = {} if association_data.is_a?(Hash) association_data.each do |association, association_options| data = render_association(association, options.merge(:include => association_options)) hash.merge!(data) if data end elsif association_data.is_a?(Array) association_data.each do |option| data = render_association(option) hash.merge!(data) if data end else if options[:preload] includes = options[:preload] == true ? options[:include] : options[:preload] end if (object = fetch_association(association_data, includes)) data = ScopedSerializer.for(object, options.merge(:associations => options[:include])).as_json hash.merge!(data) if data end end hash end
[ "def", "render_association", "(", "association_data", ",", "options", "=", "{", "}", ")", "hash", "=", "{", "}", "if", "association_data", ".", "is_a?", "(", "Hash", ")", "association_data", ".", "each", "do", "|", "association", ",", "association_options", "|", "data", "=", "render_association", "(", "association", ",", "options", ".", "merge", "(", ":include", "=>", "association_options", ")", ")", "hash", ".", "merge!", "(", "data", ")", "if", "data", "end", "elsif", "association_data", ".", "is_a?", "(", "Array", ")", "association_data", ".", "each", "do", "|", "option", "|", "data", "=", "render_association", "(", "option", ")", "hash", ".", "merge!", "(", "data", ")", "if", "data", "end", "else", "if", "options", "[", ":preload", "]", "includes", "=", "options", "[", ":preload", "]", "==", "true", "?", "options", "[", ":include", "]", ":", "options", "[", ":preload", "]", "end", "if", "(", "object", "=", "fetch_association", "(", "association_data", ",", "includes", ")", ")", "data", "=", "ScopedSerializer", ".", "for", "(", "object", ",", "options", ".", "merge", "(", ":associations", "=>", "options", "[", ":include", "]", ")", ")", ".", "as_json", "hash", ".", "merge!", "(", "data", ")", "if", "data", "end", "end", "hash", "end" ]
Renders a specific association. @return [Hash] @example render_association(:employee) render_association([:employee, :company]) render_association({ :employee => :address })
[ "Renders", "a", "specific", "association", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L134-L159
train
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.fetch_property
def fetch_property(property) return nil unless property unless respond_to?(property) object = @resource.send(property) else object = send(property) end end
ruby
def fetch_property(property) return nil unless property unless respond_to?(property) object = @resource.send(property) else object = send(property) end end
[ "def", "fetch_property", "(", "property", ")", "return", "nil", "unless", "property", "unless", "respond_to?", "(", "property", ")", "object", "=", "@resource", ".", "send", "(", "property", ")", "else", "object", "=", "send", "(", "property", ")", "end", "end" ]
Fetches property from the serializer or resource. This method makes it possible to overwrite defined attributes or associations.
[ "Fetches", "property", "from", "the", "serializer", "or", "resource", ".", "This", "method", "makes", "it", "possible", "to", "overwrite", "defined", "attributes", "or", "associations", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L165-L173
train
booqable/scoped_serializer
lib/scoped_serializer/serializer.rb
ScopedSerializer.Serializer.fetch_association
def fetch_association(name, includes=nil) association = fetch_property(name) if includes.present? && ! @resource.association(name).loaded? association.includes(includes) else association end end
ruby
def fetch_association(name, includes=nil) association = fetch_property(name) if includes.present? && ! @resource.association(name).loaded? association.includes(includes) else association end end
[ "def", "fetch_association", "(", "name", ",", "includes", "=", "nil", ")", "association", "=", "fetch_property", "(", "name", ")", "if", "includes", ".", "present?", "&&", "!", "@resource", ".", "association", "(", "name", ")", ".", "loaded?", "association", ".", "includes", "(", "includes", ")", "else", "association", "end", "end" ]
Fetches association and eager loads data. Doesn't eager load when includes is empty or when the association has already been loaded. @example fetch_association(:comments, :user)
[ "Fetches", "association", "and", "eager", "loads", "data", ".", "Doesn", "t", "eager", "load", "when", "includes", "is", "empty", "or", "when", "the", "association", "has", "already", "been", "loaded", "." ]
fb163bbf61f54a5e8684e4aba3908592bdd986ac
https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/serializer.rb#L182-L190
train
inside-track/remi
lib/remi/job.rb
Remi.Job.execute
def execute(*components) execute_transforms if components.empty? || components.include?(:transforms) execute_sub_jobs if components.empty? || components.include?(:sub_jobs) execute_load_targets if components.empty? || components.include?(:load_targets) self end
ruby
def execute(*components) execute_transforms if components.empty? || components.include?(:transforms) execute_sub_jobs if components.empty? || components.include?(:sub_jobs) execute_load_targets if components.empty? || components.include?(:load_targets) self end
[ "def", "execute", "(", "*", "components", ")", "execute_transforms", "if", "components", ".", "empty?", "||", "components", ".", "include?", "(", ":transforms", ")", "execute_sub_jobs", "if", "components", ".", "empty?", "||", "components", ".", "include?", "(", ":sub_jobs", ")", "execute_load_targets", "if", "components", ".", "empty?", "||", "components", ".", "include?", "(", ":load_targets", ")", "self", "end" ]
Execute the specified components of the job. @param components [Array<symbol>] list of components to execute (e.g., `:transforms`, `:load_targets`) @return [self]
[ "Execute", "the", "specified", "components", "of", "the", "job", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/job.rb#L284-L289
train
tclaus/keytechkit.gem
lib/keytechKit/user.rb
KeytechKit.User.load
def load(username) options = {} options[:basic_auth] = @auth response = self.class.get("/user/#{username}", options) if response.success? self.response = response parse_response self else raise response.response end end
ruby
def load(username) options = {} options[:basic_auth] = @auth response = self.class.get("/user/#{username}", options) if response.success? self.response = response parse_response self else raise response.response end end
[ "def", "load", "(", "username", ")", "options", "=", "{", "}", "options", "[", ":basic_auth", "]", "=", "@auth", "response", "=", "self", ".", "class", ".", "get", "(", "\"/user/#{username}\"", ",", "options", ")", "if", "response", ".", "success?", "self", ".", "response", "=", "response", "parse_response", "self", "else", "raise", "response", ".", "response", "end", "end" ]
Returns a updated user object username = key of user
[ "Returns", "a", "updated", "user", "object", "username", "=", "key", "of", "user" ]
caa7a6bee32b75ec18a4004179ae10cb69d148c2
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/user.rb#L27-L38
train
jinx/core
lib/jinx/metadata/dependency.rb
Jinx.Dependency.add_dependent_property
def add_dependent_property(property, *flags) logger.debug { "Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}..." } flags << :dependent unless flags.include?(:dependent) property.qualify(*flags) inv = property.inverse inv_type = property.type # example: Parent.add_dependent_property(child_prop) with inverse :parent calls the following: # Child.add_owner(Parent, :children, :parent) inv_type.add_owner(self, property.attribute, inv) if inv then logger.debug "Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}." else logger.debug "Marked #{qp}.#{property} as a uni-directional dependent attribute." end end
ruby
def add_dependent_property(property, *flags) logger.debug { "Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}..." } flags << :dependent unless flags.include?(:dependent) property.qualify(*flags) inv = property.inverse inv_type = property.type # example: Parent.add_dependent_property(child_prop) with inverse :parent calls the following: # Child.add_owner(Parent, :children, :parent) inv_type.add_owner(self, property.attribute, inv) if inv then logger.debug "Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}." else logger.debug "Marked #{qp}.#{property} as a uni-directional dependent attribute." end end
[ "def", "add_dependent_property", "(", "property", ",", "*", "flags", ")", "logger", ".", "debug", "{", "\"Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}...\"", "}", "flags", "<<", ":dependent", "unless", "flags", ".", "include?", "(", ":dependent", ")", "property", ".", "qualify", "(", "*", "flags", ")", "inv", "=", "property", ".", "inverse", "inv_type", "=", "property", ".", "type", "inv_type", ".", "add_owner", "(", "self", ",", "property", ".", "attribute", ",", "inv", ")", "if", "inv", "then", "logger", ".", "debug", "\"Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}.\"", "else", "logger", ".", "debug", "\"Marked #{qp}.#{property} as a uni-directional dependent attribute.\"", "end", "end" ]
Adds the given property as a dependent. If the property inverse is not a collection, then the property writer is modified to delegate to the dependent owner writer. This enforces referential integrity by ensuring that the following post-condition holds: * _owner_._attribute_._inverse_ == _owner_ where: * _owner_ is an instance this property's declaring class * _inverse_ is the owner inverse attribute defined in the dependent class @param [Property] property the dependent to add @param [<Symbol>] flags the attribute qualifier flags
[ "Adds", "the", "given", "property", "as", "a", "dependent", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/dependency.rb#L21-L35
train
jinx/core
lib/jinx/metadata/dependency.rb
Jinx.Dependency.add_owner
def add_owner(klass, inverse, attribute=nil) if inverse.nil? then raise ValidationError.new("Owner #{klass.qp} missing dependent attribute for dependent #{qp}") end logger.debug { "Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}..." } if @owner_prop_hash then raise MetadataError.new("Can't add #{qp} owner #{klass.qp} after dependencies have been accessed") end # Detect the owner attribute, if necessary. attribute ||= detect_owner_attribute(klass, inverse) hash = local_owner_property_hash # Guard against a conflicting owner reference attribute. if hash[klass] then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}") end # Add the owner class => attribute entry. # The attribute is nil if the dependency is unidirectional, i.e. there is an owner class which # references this class via a dependency attribute but there is no inverse owner attribute. prop = property(attribute) if attribute hash[klass] = prop # If the dependency is unidirectional, then our job is done. if attribute.nil? then logger.debug { "#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}." } return end # Bi-directional: add the owner property. local_owner_properties << prop # Set the inverse if necessary. unless prop.inverse then set_attribute_inverse(attribute, inverse) end # Set the owner flag if necessary. prop.qualify(:owner) unless prop.owner? # Redefine the writer method to issue a warning if the owner is changed. rdr, wtr = prop.accessors redefine_method(wtr) do |old_wtr| lambda do |ref| prev = send(rdr) send(old_wtr, ref) if prev and prev != ref then if ref.nil? then logger.warn("Unset the #{self} owner #{attribute} #{prev}.") elsif ref.key != prev.key then logger.warn("Reset the #{self} owner #{attribute} from #{prev} to #{ref}.") end end ref end end logger.debug { "Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}." } logger.debug { "#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}." } end
ruby
def add_owner(klass, inverse, attribute=nil) if inverse.nil? then raise ValidationError.new("Owner #{klass.qp} missing dependent attribute for dependent #{qp}") end logger.debug { "Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}..." } if @owner_prop_hash then raise MetadataError.new("Can't add #{qp} owner #{klass.qp} after dependencies have been accessed") end # Detect the owner attribute, if necessary. attribute ||= detect_owner_attribute(klass, inverse) hash = local_owner_property_hash # Guard against a conflicting owner reference attribute. if hash[klass] then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}") end # Add the owner class => attribute entry. # The attribute is nil if the dependency is unidirectional, i.e. there is an owner class which # references this class via a dependency attribute but there is no inverse owner attribute. prop = property(attribute) if attribute hash[klass] = prop # If the dependency is unidirectional, then our job is done. if attribute.nil? then logger.debug { "#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}." } return end # Bi-directional: add the owner property. local_owner_properties << prop # Set the inverse if necessary. unless prop.inverse then set_attribute_inverse(attribute, inverse) end # Set the owner flag if necessary. prop.qualify(:owner) unless prop.owner? # Redefine the writer method to issue a warning if the owner is changed. rdr, wtr = prop.accessors redefine_method(wtr) do |old_wtr| lambda do |ref| prev = send(rdr) send(old_wtr, ref) if prev and prev != ref then if ref.nil? then logger.warn("Unset the #{self} owner #{attribute} #{prev}.") elsif ref.key != prev.key then logger.warn("Reset the #{self} owner #{attribute} from #{prev} to #{ref}.") end end ref end end logger.debug { "Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}." } logger.debug { "#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}." } end
[ "def", "add_owner", "(", "klass", ",", "inverse", ",", "attribute", "=", "nil", ")", "if", "inverse", ".", "nil?", "then", "raise", "ValidationError", ".", "new", "(", "\"Owner #{klass.qp} missing dependent attribute for dependent #{qp}\"", ")", "end", "logger", ".", "debug", "{", "\"Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}...\"", "}", "if", "@owner_prop_hash", "then", "raise", "MetadataError", ".", "new", "(", "\"Can't add #{qp} owner #{klass.qp} after dependencies have been accessed\"", ")", "end", "attribute", "||=", "detect_owner_attribute", "(", "klass", ",", "inverse", ")", "hash", "=", "local_owner_property_hash", "if", "hash", "[", "klass", "]", "then", "raise", "MetadataError", ".", "new", "(", "\"Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}\"", ")", "end", "prop", "=", "property", "(", "attribute", ")", "if", "attribute", "hash", "[", "klass", "]", "=", "prop", "if", "attribute", ".", "nil?", "then", "logger", ".", "debug", "{", "\"#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}.\"", "}", "return", "end", "local_owner_properties", "<<", "prop", "unless", "prop", ".", "inverse", "then", "set_attribute_inverse", "(", "attribute", ",", "inverse", ")", "end", "prop", ".", "qualify", "(", ":owner", ")", "unless", "prop", ".", "owner?", "rdr", ",", "wtr", "=", "prop", ".", "accessors", "redefine_method", "(", "wtr", ")", "do", "|", "old_wtr", "|", "lambda", "do", "|", "ref", "|", "prev", "=", "send", "(", "rdr", ")", "send", "(", "old_wtr", ",", "ref", ")", "if", "prev", "and", "prev", "!=", "ref", "then", "if", "ref", ".", "nil?", "then", "logger", ".", "warn", "(", "\"Unset the #{self} owner #{attribute} #{prev}.\"", ")", "elsif", "ref", ".", "key", "!=", "prev", ".", "key", "then", "logger", ".", "warn", "(", "\"Reset the #{self} owner #{attribute} from #{prev} to #{ref}.\"", ")", "end", "end", "ref", "end", "end", "logger", ".", "debug", "{", "\"Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}.\"", "}", "logger", ".", "debug", "{", "\"#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}.\"", "}", "end" ]
Adds the given owner class to this dependent class. This method must be called before any dependent attribute is accessed. If the attribute is given, then the attribute inverse is set. Otherwise, if there is not already an owner attribute, then a new owner attribute is created. The name of the new attribute is the lower-case demodulized owner class name. @param [Class] the owner class @param [Symbol] inverse the owner -> dependent attribute @param [Symbol, nil] attribute the dependent -> owner attribute, if known @raise [ValidationError] if the inverse is nil
[ "Adds", "the", "given", "owner", "class", "to", "this", "dependent", "class", ".", "This", "method", "must", "be", "called", "before", "any", "dependent", "attribute", "is", "accessed", ".", "If", "the", "attribute", "is", "given", "then", "the", "attribute", "inverse", "is", "set", ".", "Otherwise", "if", "there", "is", "not", "already", "an", "owner", "attribute", "then", "a", "new", "owner", "attribute", "is", "created", ".", "The", "name", "of", "the", "new", "attribute", "is", "the", "lower", "-", "case", "demodulized", "owner", "class", "name", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/dependency.rb#L146-L200
train
jinx/core
lib/jinx/metadata/dependency.rb
Jinx.Dependency.add_owner_attribute
def add_owner_attribute(attribute) prop = property(attribute) otype = prop.type hash = local_owner_property_hash if hash.include?(otype) then oa = hash[otype] unless oa.nil? then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}") end hash[otype] = prop else add_owner(otype, prop.inverse, attribute) end end
ruby
def add_owner_attribute(attribute) prop = property(attribute) otype = prop.type hash = local_owner_property_hash if hash.include?(otype) then oa = hash[otype] unless oa.nil? then raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}") end hash[otype] = prop else add_owner(otype, prop.inverse, attribute) end end
[ "def", "add_owner_attribute", "(", "attribute", ")", "prop", "=", "property", "(", "attribute", ")", "otype", "=", "prop", ".", "type", "hash", "=", "local_owner_property_hash", "if", "hash", ".", "include?", "(", "otype", ")", "then", "oa", "=", "hash", "[", "otype", "]", "unless", "oa", ".", "nil?", "then", "raise", "MetadataError", ".", "new", "(", "\"Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}\"", ")", "end", "hash", "[", "otype", "]", "=", "prop", "else", "add_owner", "(", "otype", ",", "prop", ".", "inverse", ",", "attribute", ")", "end", "end" ]
Adds the given attribute as an owner. This method is called when a new attribute is added that references an existing owner. @param [Symbol] attribute the owner attribute
[ "Adds", "the", "given", "attribute", "as", "an", "owner", ".", "This", "method", "is", "called", "when", "a", "new", "attribute", "is", "added", "that", "references", "an", "existing", "owner", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/dependency.rb#L206-L219
train
nrser/nrser.rb
lib/nrser/errors/abstract_method_error.rb
NRSER.AbstractMethodError.method_instance
def method_instance lazy_var :@method_instance do # Just drop a warning if we can't get the method object logger.catch.warn( "Failed to get method", instance: instance, method_name: method_name, ) do instance.method method_name end end end
ruby
def method_instance lazy_var :@method_instance do # Just drop a warning if we can't get the method object logger.catch.warn( "Failed to get method", instance: instance, method_name: method_name, ) do instance.method method_name end end end
[ "def", "method_instance", "lazy_var", ":@method_instance", "do", "logger", ".", "catch", ".", "warn", "(", "\"Failed to get method\"", ",", "instance", ":", "instance", ",", "method_name", ":", "method_name", ",", ")", "do", "instance", ".", "method", "method_name", "end", "end", "end" ]
Construct a new `AbstractMethodError`. @param [Object] instance Instance that invoked the abstract method. @param [Symbol | String] method_name Name of abstract method. #initialize
[ "Construct", "a", "new", "AbstractMethodError", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/errors/abstract_method_error.rb#L88-L99
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_user_and_check
def get_user_and_check(user) user_full = @octokit.user(user) { username: user_full[:login], avatar: user_full[:avatar_url] } rescue Octokit::NotFound return false end
ruby
def get_user_and_check(user) user_full = @octokit.user(user) { username: user_full[:login], avatar: user_full[:avatar_url] } rescue Octokit::NotFound return false end
[ "def", "get_user_and_check", "(", "user", ")", "user_full", "=", "@octokit", ".", "user", "(", "user", ")", "{", "username", ":", "user_full", "[", ":login", "]", ",", "avatar", ":", "user_full", "[", ":avatar_url", "]", "}", "rescue", "Octokit", "::", "NotFound", "return", "false", "end" ]
Gets the Octokit and colors for the program. @param opts [Hash] The options to use. The ones that are used by this method are: :token, :pass, and :user. @return [Hash] A hash containing objects formatted as { git: Octokit::Client, colors: JSON } Gets the user and checks if it exists in the process. @param user [Any] The user ID or name. @return [Hash] Their username and avatar URL. @return [Boolean] False if it does not exist.
[ "Gets", "the", "Octokit", "and", "colors", "for", "the", "program", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L43-L51
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_forks_stars_watchers
def get_forks_stars_watchers(repository) { forks: @octokit.forks(repository).length, stars: @octokit.stargazers(repository).length, watchers: @octokit.subscribers(repository).length } end
ruby
def get_forks_stars_watchers(repository) { forks: @octokit.forks(repository).length, stars: @octokit.stargazers(repository).length, watchers: @octokit.subscribers(repository).length } end
[ "def", "get_forks_stars_watchers", "(", "repository", ")", "{", "forks", ":", "@octokit", ".", "forks", "(", "repository", ")", ".", "length", ",", "stars", ":", "@octokit", ".", "stargazers", "(", "repository", ")", ".", "length", ",", "watchers", ":", "@octokit", ".", "subscribers", "(", "repository", ")", ".", "length", "}", "end" ]
Gets the number of forkers, stargazers, and watchers. @param repository [String] The full repository name. @return [Hash] The forks, stars, and watcher count.
[ "Gets", "the", "number", "of", "forkers", "stargazers", "and", "watchers", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L92-L98
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_followers_following
def get_followers_following(username) { following: @octokit.following(username).length, followers: @octokit.followers(username).length } end
ruby
def get_followers_following(username) { following: @octokit.following(username).length, followers: @octokit.followers(username).length } end
[ "def", "get_followers_following", "(", "username", ")", "{", "following", ":", "@octokit", ".", "following", "(", "username", ")", ".", "length", ",", "followers", ":", "@octokit", ".", "followers", "(", "username", ")", ".", "length", "}", "end" ]
Gets the number of followers and users followed by the user. @param username [String] See #get_user_and_check @return [Hash] The number of following and followed users.
[ "Gets", "the", "number", "of", "followers", "and", "users", "followed", "by", "the", "user", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L103-L108
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_user_langs
def get_user_langs(username) repos = get_user_repos(username) langs = {} repos[:public].each do |r| next if repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
ruby
def get_user_langs(username) repos = get_user_repos(username) langs = {} repos[:public].each do |r| next if repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
[ "def", "get_user_langs", "(", "username", ")", "repos", "=", "get_user_repos", "(", "username", ")", "langs", "=", "{", "}", "repos", "[", ":public", "]", ".", "each", "do", "|", "r", "|", "next", "if", "repos", "[", ":forks", "]", ".", "include?", "r", "repo_langs", "=", "@octokit", ".", "languages", "(", "r", ")", "repo_langs", ".", "each", "do", "|", "l", ",", "b", "|", "if", "langs", "[", "l", "]", ".", "nil?", "langs", "[", "l", "]", "=", "b", "else", "langs", "[", "l", "]", "+=", "b", "end", "end", "end", "langs", "end" ]
Gets the langauges and their bytes for the user. @param username [String] See #get_user_and_check @return [Hash] The languages and their bytes, as formatted as { :Ruby => 129890, :CoffeeScript => 5970 }
[ "Gets", "the", "langauges", "and", "their", "bytes", "for", "the", "user", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L151-L166
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_org_langs
def get_org_langs(username) org_repos = get_org_repos(username) langs = {} org_repos[:public].each do |r| next if org_repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
ruby
def get_org_langs(username) org_repos = get_org_repos(username) langs = {} org_repos[:public].each do |r| next if org_repos[:forks].include? r repo_langs = @octokit.languages(r) repo_langs.each do |l, b| if langs[l].nil? langs[l] = b else langs[l] += b end end end langs end
[ "def", "get_org_langs", "(", "username", ")", "org_repos", "=", "get_org_repos", "(", "username", ")", "langs", "=", "{", "}", "org_repos", "[", ":public", "]", ".", "each", "do", "|", "r", "|", "next", "if", "org_repos", "[", ":forks", "]", ".", "include?", "r", "repo_langs", "=", "@octokit", ".", "languages", "(", "r", ")", "repo_langs", ".", "each", "do", "|", "l", ",", "b", "|", "if", "langs", "[", "l", "]", ".", "nil?", "langs", "[", "l", "]", "=", "b", "else", "langs", "[", "l", "]", "+=", "b", "end", "end", "end", "langs", "end" ]
Gets the languages and their bytes for the user's organizations. @param username [String] See #get_user_and_check @return [Hash] See #get_user_langs
[ "Gets", "the", "languages", "and", "their", "bytes", "for", "the", "user", "s", "organizations", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L171-L186
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_color_for_language
def get_color_for_language(lang) color_lang = @colors[lang] color = color_lang['color'] if color_lang.nil? || color.nil? return StringUtility.random_color_six else return color end end
ruby
def get_color_for_language(lang) color_lang = @colors[lang] color = color_lang['color'] if color_lang.nil? || color.nil? return StringUtility.random_color_six else return color end end
[ "def", "get_color_for_language", "(", "lang", ")", "color_lang", "=", "@colors", "[", "lang", "]", "color", "=", "color_lang", "[", "'color'", "]", "if", "color_lang", ".", "nil?", "||", "color", ".", "nil?", "return", "StringUtility", ".", "random_color_six", "else", "return", "color", "end", "end" ]
Gets the defined color for the language. @param lang [String] The language name. @return [String] The 6 digit hexidecimal color. @return [Nil] If there is no defined color for the language.
[ "Gets", "the", "defined", "color", "for", "the", "language", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L192-L200
train
ghuls-apps/ghuls-lib
lib/ghuls/lib.rb
GHULS.Lib.get_language_percentages
def get_language_percentages(langs) total = 0 langs.each { |_, b| total += b } lang_percents = {} langs.each do |l, b| percent = self.class.calculate_percent(b, total.to_f) lang_percents[l] = percent.round(2) end lang_percents end
ruby
def get_language_percentages(langs) total = 0 langs.each { |_, b| total += b } lang_percents = {} langs.each do |l, b| percent = self.class.calculate_percent(b, total.to_f) lang_percents[l] = percent.round(2) end lang_percents end
[ "def", "get_language_percentages", "(", "langs", ")", "total", "=", "0", "langs", ".", "each", "{", "|", "_", ",", "b", "|", "total", "+=", "b", "}", "lang_percents", "=", "{", "}", "langs", ".", "each", "do", "|", "l", ",", "b", "|", "percent", "=", "self", ".", "class", ".", "calculate_percent", "(", "b", ",", "total", ".", "to_f", ")", "lang_percents", "[", "l", "]", "=", "percent", ".", "round", "(", "2", ")", "end", "lang_percents", "end" ]
Gets the percentages for each language in a hash. @param langs [Hash] The language hash obtained by the get_langs methods. @return [Hash] The language percentages formatted as { Ruby: 50%, CoffeeScript: 50% }
[ "Gets", "the", "percentages", "for", "each", "language", "in", "a", "hash", "." ]
2f8324d8508610ee1fe0007bf4a89b39e95b85f6
https://github.com/ghuls-apps/ghuls-lib/blob/2f8324d8508610ee1fe0007bf4a89b39e95b85f6/lib/ghuls/lib.rb#L206-L215
train