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
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.has_xinclude?
def has_xinclude?(doc) ret = false doc.root.namespaces.each do |ns| if (ns.href.casecmp(XINCLUDE_NS) == 0) ret = true break end end ret end
ruby
def has_xinclude?(doc) ret = false doc.root.namespaces.each do |ns| if (ns.href.casecmp(XINCLUDE_NS) == 0) ret = true break end end ret end
[ "def", "has_xinclude?", "(", "doc", ")", "ret", "=", "false", "doc", ".", "root", ".", "namespaces", ".", "each", "do", "|", "ns", "|", "if", "(", "ns", ".", "href", ".", "casecmp", "(", "XINCLUDE_NS", ")", "==", "0", ")", "ret", "=", "true", "break", "end", "end", "ret", "end" ]
Check whether the document has a XInclude namespace
[ "Check", "whether", "the", "document", "has", "a", "XInclude", "namespace" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L135-L144
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.find_remarks
def find_remarks(filter=[]) if (@source.nil?) rfiles = find_xincludes(@doc) else @doc = XML::Document.file(@source) rfiles = [@source_file] + find_xincludes(@doc) end @remarks = rfiles.map {|rf| ind = XML::Document.file(File.expand_path(rf,@source.nil? ? '.' : @source_dir)) ind.root.namespaces.default_prefix = 'db' rems = find_remarks_in_doc(ind, rf) rems }.flatten if (filter.empty?) @remarks else filter.map {|f| @remarks.find_all {|r| f.casecmp(r[:keyword]) == 0} }.flatten end end
ruby
def find_remarks(filter=[]) if (@source.nil?) rfiles = find_xincludes(@doc) else @doc = XML::Document.file(@source) rfiles = [@source_file] + find_xincludes(@doc) end @remarks = rfiles.map {|rf| ind = XML::Document.file(File.expand_path(rf,@source.nil? ? '.' : @source_dir)) ind.root.namespaces.default_prefix = 'db' rems = find_remarks_in_doc(ind, rf) rems }.flatten if (filter.empty?) @remarks else filter.map {|f| @remarks.find_all {|r| f.casecmp(r[:keyword]) == 0} }.flatten end end
[ "def", "find_remarks", "(", "filter", "=", "[", "]", ")", "if", "(", "@source", ".", "nil?", ")", "rfiles", "=", "find_xincludes", "(", "@doc", ")", "else", "@doc", "=", "XML", "::", "Document", ".", "file", "(", "@source", ")", "rfiles", "=", "[", "@source_file", "]", "+", "find_xincludes", "(", "@doc", ")", "end", "@remarks", "=", "rfiles", ".", "map", "{", "|", "rf", "|", "ind", "=", "XML", "::", "Document", ".", "file", "(", "File", ".", "expand_path", "(", "rf", ",", "@source", ".", "nil?", "?", "'.'", ":", "@source_dir", ")", ")", "ind", ".", "root", ".", "namespaces", ".", "default_prefix", "=", "'db'", "rems", "=", "find_remarks_in_doc", "(", "ind", ",", "rf", ")", "rems", "}", ".", "flatten", "if", "(", "filter", ".", "empty?", ")", "@remarks", "else", "filter", ".", "map", "{", "|", "f", "|", "@remarks", ".", "find_all", "{", "|", "r", "|", "f", ".", "casecmp", "(", "r", "[", ":keyword", "]", ")", "==", "0", "}", "}", ".", "flatten", "end", "end" ]
Finds the remarks by looking through all the Xincluded files The remarks returned can be filtered by keyword if an keyword array is passed as an argument.
[ "Finds", "the", "remarks", "by", "looking", "through", "all", "the", "Xincluded", "files" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L199-L219
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.sum_lower_sections
def sum_lower_sections(secs,start,level) i=start sum = 0 while (i < secs.length && secs[i][:level] > level) sum += secs[i][:words] i += 1 end [sum,i] end
ruby
def sum_lower_sections(secs,start,level) i=start sum = 0 while (i < secs.length && secs[i][:level] > level) sum += secs[i][:words] i += 1 end [sum,i] end
[ "def", "sum_lower_sections", "(", "secs", ",", "start", ",", "level", ")", "i", "=", "start", "sum", "=", "0", "while", "(", "i", "<", "secs", ".", "length", "&&", "secs", "[", "i", "]", "[", ":level", "]", ">", "level", ")", "sum", "+=", "secs", "[", "i", "]", "[", ":words", "]", "i", "+=", "1", "end", "[", "sum", ",", "i", "]", "end" ]
Helper for sum_sections
[ "Helper", "for", "sum_sections" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L222-L230
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.sum_sections
def sum_sections(secs, max_level) 0.upto(max_level) do |cur_level| i = 0 while i < secs.length if (secs[i][:level] == cur_level) (ctr,ni) = sum_lower_sections(secs, i+1,cur_level) secs[i][:swords] = ctr i = ni else i += 1 end end end secs end
ruby
def sum_sections(secs, max_level) 0.upto(max_level) do |cur_level| i = 0 while i < secs.length if (secs[i][:level] == cur_level) (ctr,ni) = sum_lower_sections(secs, i+1,cur_level) secs[i][:swords] = ctr i = ni else i += 1 end end end secs end
[ "def", "sum_sections", "(", "secs", ",", "max_level", ")", "0", ".", "upto", "(", "max_level", ")", "do", "|", "cur_level", "|", "i", "=", "0", "while", "i", "<", "secs", ".", "length", "if", "(", "secs", "[", "i", "]", "[", ":level", "]", "==", "cur_level", ")", "(", "ctr", ",", "ni", ")", "=", "sum_lower_sections", "(", "secs", ",", "i", "+", "1", ",", "cur_level", ")", "secs", "[", "i", "]", "[", ":swords", "]", "=", "ctr", "i", "=", "ni", "else", "i", "+=", "1", "end", "end", "end", "secs", "end" ]
Sum the word counts of lower sections
[ "Sum", "the", "word", "counts", "of", "lower", "sections" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L233-L247
train
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.analyze_file
def analyze_file full_name = File.expand_path(@source) changed = File.mtime(@source) @doc = XML::Document.file(@source) raise ArgumentError, "Error: #{@source} is apparently not DocBook 5." unless is_docbook?(@doc) @doc.xinclude if has_xinclude?(@doc) sections = analyze_document(@doc) {:file => full_name, :modified => changed, :sections => sections} end
ruby
def analyze_file full_name = File.expand_path(@source) changed = File.mtime(@source) @doc = XML::Document.file(@source) raise ArgumentError, "Error: #{@source} is apparently not DocBook 5." unless is_docbook?(@doc) @doc.xinclude if has_xinclude?(@doc) sections = analyze_document(@doc) {:file => full_name, :modified => changed, :sections => sections} end
[ "def", "analyze_file", "full_name", "=", "File", ".", "expand_path", "(", "@source", ")", "changed", "=", "File", ".", "mtime", "(", "@source", ")", "@doc", "=", "XML", "::", "Document", ".", "file", "(", "@source", ")", "raise", "ArgumentError", ",", "\"Error: #{@source} is apparently not DocBook 5.\"", "unless", "is_docbook?", "(", "@doc", ")", "@doc", ".", "xinclude", "if", "has_xinclude?", "(", "@doc", ")", "sections", "=", "analyze_document", "(", "@doc", ")", "{", ":file", "=>", "full_name", ",", ":modified", "=>", "changed", ",", ":sections", "=>", "sections", "}", "end" ]
Open the XML document, check for the DocBook5 namespace and finally apply Xinclude tretement to it, if it has a XInclude namespace. Returns a map with the file name, the file's modification time, and the section structure.
[ "Open", "the", "XML", "document", "check", "for", "the", "DocBook5", "namespace", "and", "finally", "apply", "Xinclude", "tretement", "to", "it", "if", "it", "has", "a", "XInclude", "namespace", ".", "Returns", "a", "map", "with", "the", "file", "name", "the", "file", "s", "modification", "time", "and", "the", "section", "structure", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L293-L301
train
suculent/apprepo
lib/apprepo/runner.rb
AppRepo.Runner.upload_binary
def upload_binary if options[:ipa] uploader = AppRepo::Uploader.new(options) result = uploader.upload msg = 'Binary upload failed. Check out the error above.' UI.user_error!(msg) unless result end end
ruby
def upload_binary if options[:ipa] uploader = AppRepo::Uploader.new(options) result = uploader.upload msg = 'Binary upload failed. Check out the error above.' UI.user_error!(msg) unless result end end
[ "def", "upload_binary", "if", "options", "[", ":ipa", "]", "uploader", "=", "AppRepo", "::", "Uploader", ".", "new", "(", "options", ")", "result", "=", "uploader", ".", "upload", "msg", "=", "'Binary upload failed. Check out the error above.'", "UI", ".", "user_error!", "(", "msg", ")", "unless", "result", "end", "end" ]
Upload the binary to AppRepo
[ "Upload", "the", "binary", "to", "AppRepo" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/runner.rb#L52-L59
train
dpep/rb_autographql
lib/autographql/type_builder.rb
AutoGraphQL.TypeBuilder.convert_type
def convert_type type return type if type.is_a? GraphQL::BaseType unless type.is_a? Symbol type = type.to_s.downcase.to_sym end { boolean: GraphQL::BOOLEAN_TYPE, date: GraphQL::Types::DATE, datetime: GraphQL::Types::ISO8601DateTime, decimal: GraphQL::Types::DECIMAL, float: GraphQL::FLOAT_TYPE, int: GraphQL::INT_TYPE, integer: GraphQL::INT_TYPE, json: GraphQL::Types::JSON, string: GraphQL::STRING_TYPE, text: GraphQL::STRING_TYPE, }[type] end
ruby
def convert_type type return type if type.is_a? GraphQL::BaseType unless type.is_a? Symbol type = type.to_s.downcase.to_sym end { boolean: GraphQL::BOOLEAN_TYPE, date: GraphQL::Types::DATE, datetime: GraphQL::Types::ISO8601DateTime, decimal: GraphQL::Types::DECIMAL, float: GraphQL::FLOAT_TYPE, int: GraphQL::INT_TYPE, integer: GraphQL::INT_TYPE, json: GraphQL::Types::JSON, string: GraphQL::STRING_TYPE, text: GraphQL::STRING_TYPE, }[type] end
[ "def", "convert_type", "type", "return", "type", "if", "type", ".", "is_a?", "GraphQL", "::", "BaseType", "unless", "type", ".", "is_a?", "Symbol", "type", "=", "type", ".", "to_s", ".", "downcase", ".", "to_sym", "end", "{", "boolean", ":", "GraphQL", "::", "BOOLEAN_TYPE", ",", "date", ":", "GraphQL", "::", "Types", "::", "DATE", ",", "datetime", ":", "GraphQL", "::", "Types", "::", "ISO8601DateTime", ",", "decimal", ":", "GraphQL", "::", "Types", "::", "DECIMAL", ",", "float", ":", "GraphQL", "::", "FLOAT_TYPE", ",", "int", ":", "GraphQL", "::", "INT_TYPE", ",", "integer", ":", "GraphQL", "::", "INT_TYPE", ",", "json", ":", "GraphQL", "::", "Types", "::", "JSON", ",", "string", ":", "GraphQL", "::", "STRING_TYPE", ",", "text", ":", "GraphQL", "::", "STRING_TYPE", ",", "}", "[", "type", "]", "end" ]
convert Active Record type to GraphQL type
[ "convert", "Active", "Record", "type", "to", "GraphQL", "type" ]
e38c8648fe4e497b92e2a31143745f3e7a6ed439
https://github.com/dpep/rb_autographql/blob/e38c8648fe4e497b92e2a31143745f3e7a6ed439/lib/autographql/type_builder.rb#L130-L149
train
robertwahler/repo_manager
lib/repo_manager/assets/repo_asset.rb
RepoManager.RepoAsset.scm
def scm return @scm if @scm raise NoSuchPathError unless File.exists?(path) raise InvalidRepositoryError unless File.exists?(File.join(path, '.git')) @scm = Git.open(path) end
ruby
def scm return @scm if @scm raise NoSuchPathError unless File.exists?(path) raise InvalidRepositoryError unless File.exists?(File.join(path, '.git')) @scm = Git.open(path) end
[ "def", "scm", "return", "@scm", "if", "@scm", "raise", "NoSuchPathError", "unless", "File", ".", "exists?", "(", "path", ")", "raise", "InvalidRepositoryError", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "path", ",", "'.git'", ")", ")", "@scm", "=", "Git", ".", "open", "(", "path", ")", "end" ]
version control system wrapper
[ "version", "control", "system", "wrapper" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/repo_asset.rb#L21-L26
train
eprothro/cassie
lib/cassie/schema/version.rb
Cassie::Schema.Version.next
def next(bump_type=nil) bump_type ||= :patch bump_index = PARTS.index(bump_type.to_sym) # 0.2.1 - > 0.2 bumped_parts = parts.take(bump_index + 1) # 0.2 - > 0.3 bumped_parts[bump_index] = bumped_parts[bump_index].to_i + 1 # 0.3 - > 0.3.0.0 bumped_parts += [0]*(PARTS.length - (bump_index + 1)) self.class.new(bumped_parts.join('.')) end
ruby
def next(bump_type=nil) bump_type ||= :patch bump_index = PARTS.index(bump_type.to_sym) # 0.2.1 - > 0.2 bumped_parts = parts.take(bump_index + 1) # 0.2 - > 0.3 bumped_parts[bump_index] = bumped_parts[bump_index].to_i + 1 # 0.3 - > 0.3.0.0 bumped_parts += [0]*(PARTS.length - (bump_index + 1)) self.class.new(bumped_parts.join('.')) end
[ "def", "next", "(", "bump_type", "=", "nil", ")", "bump_type", "||=", ":patch", "bump_index", "=", "PARTS", ".", "index", "(", "bump_type", ".", "to_sym", ")", "bumped_parts", "=", "parts", ".", "take", "(", "bump_index", "+", "1", ")", "bumped_parts", "[", "bump_index", "]", "=", "bumped_parts", "[", "bump_index", "]", ".", "to_i", "+", "1", "bumped_parts", "+=", "[", "0", "]", "*", "(", "PARTS", ".", "length", "-", "(", "bump_index", "+", "1", ")", ")", "self", ".", "class", ".", "new", "(", "bumped_parts", ".", "join", "(", "'.'", ")", ")", "end" ]
Builds a new version, wiht a version number incremented from this object's version. Does not propogate any other attributes @option bump_type [Symbol] :build Bump the build version @option bump_type [Symbol] :patch Bump the patch version, set build to 0 @option bump_type [Symbol] :minor Bump the minor version, set patch and build to 0 @option bump_type [Symbol] :major Bump the major version, set minor, patch, and build to 0 @option bump_type [nil] nil Default, bumps patch, sets build to 0 @return [Version]
[ "Builds", "a", "new", "version", "wiht", "a", "version", "number", "incremented", "from", "this", "object", "s", "version", ".", "Does", "not", "propogate", "any", "other", "attributes" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/version.rb#L67-L78
train
robertwahler/repo_manager
lib/repo_manager/git/lib.rb
Git.Lib.native
def native(cmd, opts = [], chdir = true, redirect = '', &block) validate ENV['GIT_DIR'] = @git_dir ENV['GIT_INDEX_FILE'] = @git_index_file ENV['GIT_WORK_TREE'] = @git_work_dir path = @git_work_dir || @git_dir || @path opts = [opts].flatten.map {|s| escape(s) }.join(' ') git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1" out = nil if chdir && (Dir.getwd != path) Dir.chdir(path) { out = run_command(git_cmd, &block) } else out = run_command(git_cmd, &block) end if @logger @logger.info(git_cmd) @logger.debug(out) end if $?.exitstatus > 0 if $?.exitstatus == 1 && out == '' return '' end raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s) end out end
ruby
def native(cmd, opts = [], chdir = true, redirect = '', &block) validate ENV['GIT_DIR'] = @git_dir ENV['GIT_INDEX_FILE'] = @git_index_file ENV['GIT_WORK_TREE'] = @git_work_dir path = @git_work_dir || @git_dir || @path opts = [opts].flatten.map {|s| escape(s) }.join(' ') git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1" out = nil if chdir && (Dir.getwd != path) Dir.chdir(path) { out = run_command(git_cmd, &block) } else out = run_command(git_cmd, &block) end if @logger @logger.info(git_cmd) @logger.debug(out) end if $?.exitstatus > 0 if $?.exitstatus == 1 && out == '' return '' end raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s) end out end
[ "def", "native", "(", "cmd", ",", "opts", "=", "[", "]", ",", "chdir", "=", "true", ",", "redirect", "=", "''", ",", "&", "block", ")", "validate", "ENV", "[", "'GIT_DIR'", "]", "=", "@git_dir", "ENV", "[", "'GIT_INDEX_FILE'", "]", "=", "@git_index_file", "ENV", "[", "'GIT_WORK_TREE'", "]", "=", "@git_work_dir", "path", "=", "@git_work_dir", "||", "@git_dir", "||", "@path", "opts", "=", "[", "opts", "]", ".", "flatten", ".", "map", "{", "|", "s", "|", "escape", "(", "s", ")", "}", ".", "join", "(", "' '", ")", "git_cmd", "=", "\"git #{cmd} #{opts} #{redirect} 2>&1\"", "out", "=", "nil", "if", "chdir", "&&", "(", "Dir", ".", "getwd", "!=", "path", ")", "Dir", ".", "chdir", "(", "path", ")", "{", "out", "=", "run_command", "(", "git_cmd", ",", "&", "block", ")", "}", "else", "out", "=", "run_command", "(", "git_cmd", ",", "&", "block", ")", "end", "if", "@logger", "@logger", ".", "info", "(", "git_cmd", ")", "@logger", ".", "debug", "(", "out", ")", "end", "if", "$?", ".", "exitstatus", ">", "0", "if", "$?", ".", "exitstatus", "==", "1", "&&", "out", "==", "''", "return", "''", "end", "raise", "Git", "::", "CommandFailed", ".", "new", "(", "git_cmd", ",", "$?", ".", "exitstatus", ",", "out", ".", "to_s", ")", "end", "out", "end" ]
liberate the ruby-git's private command method with a few tweaks
[ "liberate", "the", "ruby", "-", "git", "s", "private", "command", "method", "with", "a", "few", "tweaks" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/git/lib.rb#L35-L65
train
thelazycamel/rubychain
lib/rubychain/chain.rb
Rubychain.Chain.add_next_block
def add_next_block(prev_block, data) if valid_block?(prev_block) blockchain << next_block(data) else raise InvalidBlockError end end
ruby
def add_next_block(prev_block, data) if valid_block?(prev_block) blockchain << next_block(data) else raise InvalidBlockError end end
[ "def", "add_next_block", "(", "prev_block", ",", "data", ")", "if", "valid_block?", "(", "prev_block", ")", "blockchain", "<<", "next_block", "(", "data", ")", "else", "raise", "InvalidBlockError", "end", "end" ]
Initialize a new blockchain by creating a new array with the Genesis block #add_next_block => Adds a new block to the blockchain with the given data it will raise an error if the previous_block hash does not match the last_block in our blockchain
[ "Initialize", "a", "new", "blockchain", "by", "creating", "a", "new", "array", "with", "the", "Genesis", "block" ]
7671fe6d25f818a88c8a62c3167438837d37740d
https://github.com/thelazycamel/rubychain/blob/7671fe6d25f818a88c8a62c3167438837d37740d/lib/rubychain/chain.rb#L19-L25
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/services/service.rb
GameOverseer.Service.data_to_method
def data_to_method(data) raise "No safe methods defined!" unless @safe_methods.size > 0 @safe_methods.each do |method| if data['mode'] == method.to_s self.send(data['mode'], data) end end end
ruby
def data_to_method(data) raise "No safe methods defined!" unless @safe_methods.size > 0 @safe_methods.each do |method| if data['mode'] == method.to_s self.send(data['mode'], data) end end end
[ "def", "data_to_method", "(", "data", ")", "raise", "\"No safe methods defined!\"", "unless", "@safe_methods", ".", "size", ">", "0", "@safe_methods", ".", "each", "do", "|", "method", "|", "if", "data", "[", "'mode'", "]", "==", "method", ".", "to_s", "self", ".", "send", "(", "data", "[", "'mode'", "]", ",", "data", ")", "end", "end", "end" ]
Uses the 'mode' from a packet to call the method of the same name @param data [Hash] data from packet
[ "Uses", "the", "mode", "from", "a", "packet", "to", "call", "the", "method", "of", "the", "same", "name" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/services/service.rb#L74-L81
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/services/service.rb
GameOverseer.Service.every
def every(milliseconds, &block) Thread.new do loop do block.call sleep(milliseconds/1000.0) end end end
ruby
def every(milliseconds, &block) Thread.new do loop do block.call sleep(milliseconds/1000.0) end end end
[ "def", "every", "(", "milliseconds", ",", "&", "block", ")", "Thread", ".", "new", "do", "loop", "do", "block", ".", "call", "sleep", "(", "milliseconds", "/", "1000.0", ")", "end", "end", "end" ]
Calls Proc immediately then every milliseconds, async. @param milliseconds [Integer][Float] Time to wait before calling the block @param block [Proc]
[ "Calls", "Proc", "immediately", "then", "every", "milliseconds", "async", "." ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/services/service.rb#L86-L93
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/services/service.rb
GameOverseer.Service.log
def log(string, color = Gosu::Color::RED) GameOverseer::Console.log_with_color(string, color) end
ruby
def log(string, color = Gosu::Color::RED) GameOverseer::Console.log_with_color(string, color) end
[ "def", "log", "(", "string", ",", "color", "=", "Gosu", "::", "Color", "::", "RED", ")", "GameOverseer", "::", "Console", ".", "log_with_color", "(", "string", ",", "color", ")", "end" ]
String to be logged @param string [String] text to log @param color [Gosu::Color] color of text in console
[ "String", "to", "be", "logged" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/services/service.rb#L108-L110
train
xlab-si/server-sent-events-ruby
lib/server_sent_events/event.rb
ServerSentEvents.Event.to_s
def to_s repr = "" repr += "id: #{id}\n" if id repr += "event: #{event}\n" if event if data.empty? repr += "data: \n" else data.split("\n").each { |l| repr += "data: #{l}\n" } end repr += "\n" end
ruby
def to_s repr = "" repr += "id: #{id}\n" if id repr += "event: #{event}\n" if event if data.empty? repr += "data: \n" else data.split("\n").each { |l| repr += "data: #{l}\n" } end repr += "\n" end
[ "def", "to_s", "repr", "=", "\"\"", "repr", "+=", "\"id: #{id}\\n\"", "if", "id", "repr", "+=", "\"event: #{event}\\n\"", "if", "event", "if", "data", ".", "empty?", "repr", "+=", "\"data: \\n\"", "else", "data", ".", "split", "(", "\"\\n\"", ")", ".", "each", "{", "|", "l", "|", "repr", "+=", "\"data: #{l}\\n\"", "}", "end", "repr", "+=", "\"\\n\"", "end" ]
Serialize event into form for transmission. Output of this method call can be written directly into the socket.
[ "Serialize", "event", "into", "form", "for", "transmission", "." ]
f57491a8ab3b08662f657668d3ffe6725dd251db
https://github.com/xlab-si/server-sent-events-ruby/blob/f57491a8ab3b08662f657668d3ffe6725dd251db/lib/server_sent_events/event.rb#L36-L46
train
pwnall/exec_sandbox
lib/exec_sandbox/sandbox.rb
ExecSandbox.Sandbox.push
def push(from, options = {}) to = File.join @path, (options[:to] || File.basename(from)) FileUtils.cp_r from, to permissions = options[:read_only] ? 0770 : 0750 FileUtils.chmod_R permissions, to FileUtils.chown_R @admin_uid, @user_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
ruby
def push(from, options = {}) to = File.join @path, (options[:to] || File.basename(from)) FileUtils.cp_r from, to permissions = options[:read_only] ? 0770 : 0750 FileUtils.chmod_R permissions, to FileUtils.chown_R @admin_uid, @user_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
[ "def", "push", "(", "from", ",", "options", "=", "{", "}", ")", "to", "=", "File", ".", "join", "@path", ",", "(", "options", "[", ":to", "]", "||", "File", ".", "basename", "(", "from", ")", ")", "FileUtils", ".", "cp_r", "from", ",", "to", "permissions", "=", "options", "[", ":read_only", "]", "?", "0770", ":", "0750", "FileUtils", ".", "chmod_R", "permissions", ",", "to", "FileUtils", ".", "chown_R", "@admin_uid", ",", "@user_gid", ",", "to", "to", "end" ]
Empty sandbox. @param [String] admin the name of a user who will be able to peek into the sandbox Copies a file or directory to the sandbox. @param [String] from path to the file or directory to be copied @param [Hash] options tweaks the permissions and the path inside the sandbox @option options [String] :to the path inside the sandbox where the file or directory will be copied (defaults to the name of the source) @option options [Boolean] :read_only if true, the sandbox user will not be able to write to the file / directory @return [String] the absolute path to the copied file / directory inside the sandbox
[ "Empty", "sandbox", "." ]
2e6a80643978d4c2c6d62193463a7ab7d45db723
https://github.com/pwnall/exec_sandbox/blob/2e6a80643978d4c2c6d62193463a7ab7d45db723/lib/exec_sandbox/sandbox.rb#L42-L56
train
pwnall/exec_sandbox
lib/exec_sandbox/sandbox.rb
ExecSandbox.Sandbox.pull
def pull(from, to) from = File.join @path, from return nil unless File.exist? from FileUtils.cp_r from, to FileUtils.chmod_R 0770, to FileUtils.chown_R @admin_uid, @admin_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
ruby
def pull(from, to) from = File.join @path, from return nil unless File.exist? from FileUtils.cp_r from, to FileUtils.chmod_R 0770, to FileUtils.chown_R @admin_uid, @admin_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
[ "def", "pull", "(", "from", ",", "to", ")", "from", "=", "File", ".", "join", "@path", ",", "from", "return", "nil", "unless", "File", ".", "exist?", "from", "FileUtils", ".", "cp_r", "from", ",", "to", "FileUtils", ".", "chmod_R", "0770", ",", "to", "FileUtils", ".", "chown_R", "@admin_uid", ",", "@admin_gid", ",", "to", "to", "end" ]
Copies a file or directory from the sandbox. @param [String] from relative path to the sandbox file or directory @param [String] to path where the file/directory will be copied @param [Hash] options tweaks the permissions and the path inside the sandbox @return [String] the path to the copied file / directory outside the sandbox, or nil if the file / directory does not exist inside the sandbox
[ "Copies", "a", "file", "or", "directory", "from", "the", "sandbox", "." ]
2e6a80643978d4c2c6d62193463a7ab7d45db723
https://github.com/pwnall/exec_sandbox/blob/2e6a80643978d4c2c6d62193463a7ab7d45db723/lib/exec_sandbox/sandbox.rb#L66-L80
train
pwnall/exec_sandbox
lib/exec_sandbox/sandbox.rb
ExecSandbox.Sandbox.run
def run(command, options = {}) limits = options[:limits] || {} io = {} if options[:in] io[:in] = options[:in] in_rd = nil else in_rd, in_wr = IO.pipe in_wr.write options[:in_data] if options[:in_data] in_wr.close io[:in] = in_rd end if options[:out] io[:out] = options[:out] else out_rd, out_wr = IO.pipe io[:out] = out_wr end case options[:err] when :out io[:err] = STDOUT when :none # Don't set io[:err], so the child's stderr will be closed. else io[:err] = STDERR end pid = ExecSandbox::Spawn.spawn command, io, @principal, limits # Close the pipe ends that are meant to be used in the child. in_rd.close if in_rd out_wr.close if out_wr # Collect information about the child. if out_rd out_pieces = [] out_pieces << out_rd.read rescue nil end status = ExecSandbox::Wait4.wait4 pid if out_rd out_pieces << out_rd.read rescue nil out_rd.close status[:out_data] = out_pieces.join('') end status end
ruby
def run(command, options = {}) limits = options[:limits] || {} io = {} if options[:in] io[:in] = options[:in] in_rd = nil else in_rd, in_wr = IO.pipe in_wr.write options[:in_data] if options[:in_data] in_wr.close io[:in] = in_rd end if options[:out] io[:out] = options[:out] else out_rd, out_wr = IO.pipe io[:out] = out_wr end case options[:err] when :out io[:err] = STDOUT when :none # Don't set io[:err], so the child's stderr will be closed. else io[:err] = STDERR end pid = ExecSandbox::Spawn.spawn command, io, @principal, limits # Close the pipe ends that are meant to be used in the child. in_rd.close if in_rd out_wr.close if out_wr # Collect information about the child. if out_rd out_pieces = [] out_pieces << out_rd.read rescue nil end status = ExecSandbox::Wait4.wait4 pid if out_rd out_pieces << out_rd.read rescue nil out_rd.close status[:out_data] = out_pieces.join('') end status end
[ "def", "run", "(", "command", ",", "options", "=", "{", "}", ")", "limits", "=", "options", "[", ":limits", "]", "||", "{", "}", "io", "=", "{", "}", "if", "options", "[", ":in", "]", "io", "[", ":in", "]", "=", "options", "[", ":in", "]", "in_rd", "=", "nil", "else", "in_rd", ",", "in_wr", "=", "IO", ".", "pipe", "in_wr", ".", "write", "options", "[", ":in_data", "]", "if", "options", "[", ":in_data", "]", "in_wr", ".", "close", "io", "[", ":in", "]", "=", "in_rd", "end", "if", "options", "[", ":out", "]", "io", "[", ":out", "]", "=", "options", "[", ":out", "]", "else", "out_rd", ",", "out_wr", "=", "IO", ".", "pipe", "io", "[", ":out", "]", "=", "out_wr", "end", "case", "options", "[", ":err", "]", "when", ":out", "io", "[", ":err", "]", "=", "STDOUT", "when", ":none", "else", "io", "[", ":err", "]", "=", "STDERR", "end", "pid", "=", "ExecSandbox", "::", "Spawn", ".", "spawn", "command", ",", "io", ",", "@principal", ",", "limits", "in_rd", ".", "close", "if", "in_rd", "out_wr", ".", "close", "if", "out_wr", "if", "out_rd", "out_pieces", "=", "[", "]", "out_pieces", "<<", "out_rd", ".", "read", "rescue", "nil", "end", "status", "=", "ExecSandbox", "::", "Wait4", ".", "wait4", "pid", "if", "out_rd", "out_pieces", "<<", "out_rd", ".", "read", "rescue", "nil", "out_rd", ".", "close", "status", "[", ":out_data", "]", "=", "out_pieces", ".", "join", "(", "''", ")", "end", "status", "end" ]
Runs a command in the sandbox. @param [Array, String] command to be run; use an array to pass arguments to the command @param [Hash] options stdin / stdout redirection and resource limitations @option options [Hash] :limits see {Spawn.limit_resources} @option options [String] :in path to a file that is set as the child's stdin @option options [String] :in_data contents to be written to a pipe that is set as the child's stdin; if neither :in nor :in_data are specified, the child will receive the read end of an empty pipe @option options [String] :out path to a file that is set as the child's stdout; if not set, the child will receive the write end of a pipe whose contents is returned in :out_data @option options [Symbol] :err :none closes the child's stderr, :out redirects the child's stderr to stdout; by default, the child's stderr is the same as the parent's @return [Hash] the result of {Wait4.wait4}, plus an :out_data key if no :out option is given
[ "Runs", "a", "command", "in", "the", "sandbox", "." ]
2e6a80643978d4c2c6d62193463a7ab7d45db723
https://github.com/pwnall/exec_sandbox/blob/2e6a80643978d4c2c6d62193463a7ab7d45db723/lib/exec_sandbox/sandbox.rb#L100-L145
train
atd/rails-scheduler
lib/scheduler/model.rb
Scheduler.Model.ocurrences
def ocurrences(st, en = nil) recurrence ? recurrence.events(:starts => st, :until => en) : (start_at.to_date..end_at.to_date).to_a end
ruby
def ocurrences(st, en = nil) recurrence ? recurrence.events(:starts => st, :until => en) : (start_at.to_date..end_at.to_date).to_a end
[ "def", "ocurrences", "(", "st", ",", "en", "=", "nil", ")", "recurrence", "?", "recurrence", ".", "events", "(", ":starts", "=>", "st", ",", ":until", "=>", "en", ")", ":", "(", "start_at", ".", "to_date", "..", "end_at", ".", "to_date", ")", ".", "to_a", "end" ]
Array including all the dates this Scheduler has ocurrences between st and en
[ "Array", "including", "all", "the", "dates", "this", "Scheduler", "has", "ocurrences", "between", "st", "and", "en" ]
849e0a660f32646e768ab9f49296559184fcb9e4
https://github.com/atd/rails-scheduler/blob/849e0a660f32646e768ab9f49296559184fcb9e4/lib/scheduler/model.rb#L105-L109
train
rakeoe/rakeoe
lib/rakeoe/config.rb
RakeOE.Config.dump
def dump puts '******************' puts '* RakeOE::Config *' puts '******************' puts "Directories : #{@directories}" puts "Suffixes : #{@suffixes}" puts "Platform : #{@platform}" puts "Release mode : #{@release}" puts "Test framework : #{@test_fw}" puts "Optimization dbg : #{@optimization_dbg}" puts "Optimization release : #{@optimization_release}" puts "Language Standard for C : #{@language_std_c}" puts "Language Standard for C++ : #{@language_std_cpp}" puts "Software version string : #{@sw_version}" puts "Generate bin file : #{@generate_bin}" puts "Generate hex file : #{@generate_hex}" puts "Generate map file : #{@generate_map}" puts "Strip objects : #{@stripped}" end
ruby
def dump puts '******************' puts '* RakeOE::Config *' puts '******************' puts "Directories : #{@directories}" puts "Suffixes : #{@suffixes}" puts "Platform : #{@platform}" puts "Release mode : #{@release}" puts "Test framework : #{@test_fw}" puts "Optimization dbg : #{@optimization_dbg}" puts "Optimization release : #{@optimization_release}" puts "Language Standard for C : #{@language_std_c}" puts "Language Standard for C++ : #{@language_std_cpp}" puts "Software version string : #{@sw_version}" puts "Generate bin file : #{@generate_bin}" puts "Generate hex file : #{@generate_hex}" puts "Generate map file : #{@generate_map}" puts "Strip objects : #{@stripped}" end
[ "def", "dump", "puts", "'******************'", "puts", "'* RakeOE::Config *'", "puts", "'******************'", "puts", "\"Directories : #{@directories}\"", "puts", "\"Suffixes : #{@suffixes}\"", "puts", "\"Platform : #{@platform}\"", "puts", "\"Release mode : #{@release}\"", "puts", "\"Test framework : #{@test_fw}\"", "puts", "\"Optimization dbg : #{@optimization_dbg}\"", "puts", "\"Optimization release : #{@optimization_release}\"", "puts", "\"Language Standard for C : #{@language_std_c}\"", "puts", "\"Language Standard for C++ : #{@language_std_cpp}\"", "puts", "\"Software version string : #{@sw_version}\"", "puts", "\"Generate bin file : #{@generate_bin}\"", "puts", "\"Generate hex file : #{@generate_hex}\"", "puts", "\"Generate map file : #{@generate_map}\"", "puts", "\"Strip objects : #{@stripped}\"", "end" ]
Dumps configuration to stdout
[ "Dumps", "configuration", "to", "stdout" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/config.rb#L109-L127
train
wwidea/minimalist_authentication
lib/minimalist_authentication/user.rb
MinimalistAuthentication.User.authenticated?
def authenticated?(password) if password_object == password update_hash!(password) if password_object.stale? return true end return false end
ruby
def authenticated?(password) if password_object == password update_hash!(password) if password_object.stale? return true end return false end
[ "def", "authenticated?", "(", "password", ")", "if", "password_object", "==", "password", "update_hash!", "(", "password", ")", "if", "password_object", ".", "stale?", "return", "true", "end", "return", "false", "end" ]
Return true if password matches the hashed_password. If successful checks for an outdated password_hash and updates if necessary.
[ "Return", "true", "if", "password", "matches", "the", "hashed_password", ".", "If", "successful", "checks", "for", "an", "outdated", "password_hash", "and", "updates", "if", "necessary", "." ]
29372225a8ee7132bf3b989b824b36cf306cc656
https://github.com/wwidea/minimalist_authentication/blob/29372225a8ee7132bf3b989b824b36cf306cc656/lib/minimalist_authentication/user.rb#L71-L78
train
alg/circuit_b
lib/circuit_b/fuse.rb
CircuitB.Fuse.open
def open put(:state, :open) if config[:on_break] require 'timeout' handlers = [ config[:on_break] ].flatten.map { |handler| (handler.is_a?(Symbol) ? STANDARD_HANDLERS[handler] : handler) }.compact handlers.each do |handler| begin Timeout::timeout(@break_handler_timeout) { handler.call(self) } rescue Timeout::Error # We ignore handler timeouts rescue # We ignore handler errors end end end end
ruby
def open put(:state, :open) if config[:on_break] require 'timeout' handlers = [ config[:on_break] ].flatten.map { |handler| (handler.is_a?(Symbol) ? STANDARD_HANDLERS[handler] : handler) }.compact handlers.each do |handler| begin Timeout::timeout(@break_handler_timeout) { handler.call(self) } rescue Timeout::Error # We ignore handler timeouts rescue # We ignore handler errors end end end end
[ "def", "open", "put", "(", ":state", ",", ":open", ")", "if", "config", "[", ":on_break", "]", "require", "'timeout'", "handlers", "=", "[", "config", "[", ":on_break", "]", "]", ".", "flatten", ".", "map", "{", "|", "handler", "|", "(", "handler", ".", "is_a?", "(", "Symbol", ")", "?", "STANDARD_HANDLERS", "[", "handler", "]", ":", "handler", ")", "}", ".", "compact", "handlers", ".", "each", "do", "|", "handler", "|", "begin", "Timeout", "::", "timeout", "(", "@break_handler_timeout", ")", "{", "handler", ".", "call", "(", "self", ")", "}", "rescue", "Timeout", "::", "Error", "rescue", "end", "end", "end", "end" ]
Open the fuse
[ "Open", "the", "fuse" ]
d9126c59636c6578e37179e47043b3d84834d1d4
https://github.com/alg/circuit_b/blob/d9126c59636c6578e37179e47043b3d84834d1d4/lib/circuit_b/fuse.rb#L87-L107
train
j0hnds/cron-spec
lib/cron-spec/cron_specification_factory.rb
CronSpec.CronSpecificationFactory.parse
def parse(value_spec) case value_spec when WildcardPattern WildcardCronValue.new(@lower_limit, @upper_limit) when @single_value_pattern SingleValueCronValue.new(@lower_limit, @upper_limit, convert_value($1)) when @range_pattern RangeCronValue.new(@lower_limit, @upper_limit, convert_value($1), convert_value($2)) when @step_pattern StepCronValue.new(@lower_limit, @upper_limit, $1.to_i) else raise "Unrecognized cron specification pattern." end end
ruby
def parse(value_spec) case value_spec when WildcardPattern WildcardCronValue.new(@lower_limit, @upper_limit) when @single_value_pattern SingleValueCronValue.new(@lower_limit, @upper_limit, convert_value($1)) when @range_pattern RangeCronValue.new(@lower_limit, @upper_limit, convert_value($1), convert_value($2)) when @step_pattern StepCronValue.new(@lower_limit, @upper_limit, $1.to_i) else raise "Unrecognized cron specification pattern." end end
[ "def", "parse", "(", "value_spec", ")", "case", "value_spec", "when", "WildcardPattern", "WildcardCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ")", "when", "@single_value_pattern", "SingleValueCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ",", "convert_value", "(", "$1", ")", ")", "when", "@range_pattern", "RangeCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ",", "convert_value", "(", "$1", ")", ",", "convert_value", "(", "$2", ")", ")", "when", "@step_pattern", "StepCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ",", "$1", ".", "to_i", ")", "else", "raise", "\"Unrecognized cron specification pattern.\"", "end", "end" ]
Constructs a new CronSpecificationFactory Parses a unit of a cron specification. The supported patterns for parsing are one of: * Wildcard '*' * Single Scalar Value [0-9]+|(sun|mon|tue|wed|thu|fri|sat)|(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec) * Range value (0-9, mon-fri, etc.) * Step value (*/[0-9]+)
[ "Constructs", "a", "new", "CronSpecificationFactory" ]
ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa
https://github.com/j0hnds/cron-spec/blob/ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa/lib/cron-spec/cron_specification_factory.rb#L31-L44
train
robertwahler/repo_manager
lib/repo_manager/views/view_helper.rb
RepoManager.ViewHelper.path_to
def path_to(*args) case when args.length == 1 base_path = :repo_manager asset = args when args.length == 2 base_path, asset = *args when args.length > 2 raise ArgumentError, "Too many arguments" else raise ArgumentError, "Specify at least the file asset" end case base_path when :repo_manager root = File.expand_path('../../../../', __FILE__) else raise "unknown base_path" end File.join(root, asset) end
ruby
def path_to(*args) case when args.length == 1 base_path = :repo_manager asset = args when args.length == 2 base_path, asset = *args when args.length > 2 raise ArgumentError, "Too many arguments" else raise ArgumentError, "Specify at least the file asset" end case base_path when :repo_manager root = File.expand_path('../../../../', __FILE__) else raise "unknown base_path" end File.join(root, asset) end
[ "def", "path_to", "(", "*", "args", ")", "case", "when", "args", ".", "length", "==", "1", "base_path", "=", ":repo_manager", "asset", "=", "args", "when", "args", ".", "length", "==", "2", "base_path", ",", "asset", "=", "*", "args", "when", "args", ".", "length", ">", "2", "raise", "ArgumentError", ",", "\"Too many arguments\"", "else", "raise", "ArgumentError", ",", "\"Specify at least the file asset\"", "end", "case", "base_path", "when", ":repo_manager", "root", "=", "File", ".", "expand_path", "(", "'../../../../'", ",", "__FILE__", ")", "else", "raise", "\"unknown base_path\"", "end", "File", ".", "join", "(", "root", ",", "asset", ")", "end" ]
path_to returns absolute installed path to various folders packaged with the RepoManager gem @example manually require and include before use require 'repo_manager/views/view_helper' include RepoManager::ViewHelper @example default to repo_manager root path_to("views/templates/bla.rb") @example repo_manager root path_to(:repo_manager, "views/templates/bla.rb") @example :bootstrap path_to(:bootstrap, "bootstrap/css/bootstrap.css") @overload path_to(*args) @param [Symbol] base_path which gem folder should be root @param [String] file_asset path to file asset parented in the given folder @return [String] absolute path to asset
[ "path_to", "returns", "absolute", "installed", "path", "to", "various", "folders", "packaged", "with", "the", "RepoManager", "gem" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/view_helper.rb#L30-L52
train
romanbsd/mongoid_colored_logger
lib/mongoid_colored_logger/logger_decorator.rb
MongoidColoredLogger.LoggerDecorator.colorize_legacy_message
def colorize_legacy_message(message) message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} end
ruby
def colorize_legacy_message(message) message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} end
[ "def", "colorize_legacy_message", "(", "message", ")", "message", ".", "sub", "(", "'MONGODB'", ",", "color", "(", "'MONGODB'", ",", "odd?", "?", "CYAN", ":", "MAGENTA", ")", ")", ".", "sub", "(", "%r{", "\\[", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "BLUE", ")", "}", ".", "sub", "(", "%r{", "\\]", "\\.", "\\w", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "YELLOW", ")", "}", "end" ]
Used for Mongoid < 3.0
[ "Used", "for", "Mongoid", "<", "3", ".", "0" ]
8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3
https://github.com/romanbsd/mongoid_colored_logger/blob/8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3/lib/mongoid_colored_logger/logger_decorator.rb#L49-L53
train
romanbsd/mongoid_colored_logger
lib/mongoid_colored_logger/logger_decorator.rb
MongoidColoredLogger.LoggerDecorator.colorize_message
def colorize_message(message) message = message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} message.sub('MOPED:', color('MOPED:', odd? ? CYAN : MAGENTA)). sub(/\{.+?\}\s/) { |m| color(m, BLUE) }. sub(/COMMAND|QUERY|KILL_CURSORS|INSERT|DELETE|UPDATE|GET_MORE|STARTED/) { |m| color(m, YELLOW) }. sub(/SUCCEEDED/) { |m| color(m, GREEN) }. sub(/FAILED/) { |m| color(m, RED) }. sub(/[\d\.]+(s|ms)/) { |m| color(m, GREEN) } end
ruby
def colorize_message(message) message = message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} message.sub('MOPED:', color('MOPED:', odd? ? CYAN : MAGENTA)). sub(/\{.+?\}\s/) { |m| color(m, BLUE) }. sub(/COMMAND|QUERY|KILL_CURSORS|INSERT|DELETE|UPDATE|GET_MORE|STARTED/) { |m| color(m, YELLOW) }. sub(/SUCCEEDED/) { |m| color(m, GREEN) }. sub(/FAILED/) { |m| color(m, RED) }. sub(/[\d\.]+(s|ms)/) { |m| color(m, GREEN) } end
[ "def", "colorize_message", "(", "message", ")", "message", "=", "message", ".", "sub", "(", "'MONGODB'", ",", "color", "(", "'MONGODB'", ",", "odd?", "?", "CYAN", ":", "MAGENTA", ")", ")", ".", "sub", "(", "%r{", "\\[", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "BLUE", ")", "}", ".", "sub", "(", "%r{", "\\]", "\\.", "\\w", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "YELLOW", ")", "}", "message", ".", "sub", "(", "'MOPED:'", ",", "color", "(", "'MOPED:'", ",", "odd?", "?", "CYAN", ":", "MAGENTA", ")", ")", ".", "sub", "(", "/", "\\{", "\\}", "\\s", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "BLUE", ")", "}", ".", "sub", "(", "/", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "YELLOW", ")", "}", ".", "sub", "(", "/", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "GREEN", ")", "}", ".", "sub", "(", "/", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "RED", ")", "}", ".", "sub", "(", "/", "\\d", "\\.", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "GREEN", ")", "}", "end" ]
Used for Mongoid >= 3.0
[ "Used", "for", "Mongoid", ">", "=", "3", ".", "0" ]
8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3
https://github.com/romanbsd/mongoid_colored_logger/blob/8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3/lib/mongoid_colored_logger/logger_decorator.rb#L56-L66
train
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.get_queue
def get_queue(name=:default_queue) name = name.to_sym queue = @queues[name] unless queue @queues[name] = GBDispatch::Queue.new(name) queue = @queues[name] end queue end
ruby
def get_queue(name=:default_queue) name = name.to_sym queue = @queues[name] unless queue @queues[name] = GBDispatch::Queue.new(name) queue = @queues[name] end queue end
[ "def", "get_queue", "(", "name", "=", ":default_queue", ")", "name", "=", "name", ".", "to_sym", "queue", "=", "@queues", "[", "name", "]", "unless", "queue", "@queues", "[", "name", "]", "=", "GBDispatch", "::", "Queue", ".", "new", "(", "name", ")", "queue", "=", "@queues", "[", "name", "]", "end", "queue", "end" ]
Returns queue of given name. If queue doesn't exists it will create you a new one. Remember that for each allocated queue, there is new thread allocated. @param name [String, Symbol] if not passed, default queue will be returned. @return [GBDispatch::Queue]
[ "Returns", "queue", "of", "given", "name", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L17-L25
train
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.run_async_on_queue
def run_async_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.async.perform_now ->() { yield } end
ruby
def run_async_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.async.perform_now ->() { yield } end
[ "def", "run_async_on_queue", "(", "queue", ")", "raise", "ArgumentError", ".", "new", "'Queue must be GBDispatch::Queue'", "unless", "queue", ".", "is_a?", "GBDispatch", "::", "Queue", "queue", ".", "async", ".", "perform_now", "->", "(", ")", "{", "yield", "}", "end" ]
Run asynchronously given block of code on given queue. This is a proxy for {GBDispatch::Queue#perform_now} method. @param queue [GBDispatch::Queue] queue on which block will be executed @return [nil] @example my_queue = GBDispatch::Manager.instance.get_queue :my_queue GBDispatch::Manager.instance.run_async_on_queue my_queue do #my delayed code here - probably slow one :) puts 'Delayed Hello World!' end
[ "Run", "asynchronously", "given", "block", "of", "code", "on", "given", "queue", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L38-L41
train
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.run_sync_on_queue
def run_sync_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue future = queue.await.perform_now ->() { yield } future.value end
ruby
def run_sync_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue future = queue.await.perform_now ->() { yield } future.value end
[ "def", "run_sync_on_queue", "(", "queue", ")", "raise", "ArgumentError", ".", "new", "'Queue must be GBDispatch::Queue'", "unless", "queue", ".", "is_a?", "GBDispatch", "::", "Queue", "future", "=", "queue", ".", "await", ".", "perform_now", "->", "(", ")", "{", "yield", "}", "future", ".", "value", "end" ]
Run given block of code on given queue and wait for result. This method use {GBDispatch::Queue#perform_now} and wait for result. @param queue [GBDispatch::Queue] queue on which block will be executed @example sets +my_result+ to 42 my_queue = GBDispatch::Manager.instance.get_queue :my_queue my_result = GBDispatch::Manager.instance.run_sync_on_queue my_queue do # my complicated code here puts 'Delayed Hello World!' # return value 42 end
[ "Run", "given", "block", "of", "code", "on", "given", "queue", "and", "wait", "for", "result", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L55-L59
train
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.run_after_on_queue
def run_after_on_queue(time, queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.perform_after time, ->(){ yield } end
ruby
def run_after_on_queue(time, queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.perform_after time, ->(){ yield } end
[ "def", "run_after_on_queue", "(", "time", ",", "queue", ")", "raise", "ArgumentError", ".", "new", "'Queue must be GBDispatch::Queue'", "unless", "queue", ".", "is_a?", "GBDispatch", "::", "Queue", "queue", ".", "perform_after", "time", ",", "->", "(", ")", "{", "yield", "}", "end" ]
Run given block of code on given queue with delay. @param time [Fixnum, Float] delay in seconds @param queue [GBDispatch::Queue] queue on which block will be executed @return [nil] @example Will print 'Hello word!' after 5 seconds. my_queue = GBDispatch::Manager.instance.get_queue :my_queue my_result = GBDispatch::Manager.instance.run_after_on_queue 5, my_queue do puts 'Hello World!' end
[ "Run", "given", "block", "of", "code", "on", "given", "queue", "with", "delay", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L71-L74
train
eanlain/calligraphy
lib/calligraphy/utils.rb
Calligraphy.Utils.map_array_of_hashes
def map_array_of_hashes(arr_hashes) return if arr_hashes.nil? [].tap do |output_array| arr_hashes.each do |hash| output_array.push hash.values end end end
ruby
def map_array_of_hashes(arr_hashes) return if arr_hashes.nil? [].tap do |output_array| arr_hashes.each do |hash| output_array.push hash.values end end end
[ "def", "map_array_of_hashes", "(", "arr_hashes", ")", "return", "if", "arr_hashes", ".", "nil?", "[", "]", ".", "tap", "do", "|", "output_array", "|", "arr_hashes", ".", "each", "do", "|", "hash", "|", "output_array", ".", "push", "hash", ".", "values", "end", "end", "end" ]
Given an array of hashes, returns an array of hash values.
[ "Given", "an", "array", "of", "hashes", "returns", "an", "array", "of", "hash", "values", "." ]
19290d38322287fcb8e0152a7ed3b7f01033b57e
https://github.com/eanlain/calligraphy/blob/19290d38322287fcb8e0152a7ed3b7f01033b57e/lib/calligraphy/utils.rb#L36-L44
train
eanlain/calligraphy
lib/calligraphy/utils.rb
Calligraphy.Utils.extract_lock_token
def extract_lock_token(if_header) token = if_header.scan(Calligraphy::LOCK_TOKEN_REGEX) token.flatten.first if token.is_a? Array end
ruby
def extract_lock_token(if_header) token = if_header.scan(Calligraphy::LOCK_TOKEN_REGEX) token.flatten.first if token.is_a? Array end
[ "def", "extract_lock_token", "(", "if_header", ")", "token", "=", "if_header", ".", "scan", "(", "Calligraphy", "::", "LOCK_TOKEN_REGEX", ")", "token", ".", "flatten", ".", "first", "if", "token", ".", "is_a?", "Array", "end" ]
Extracts a lock token from an If headers.
[ "Extracts", "a", "lock", "token", "from", "an", "If", "headers", "." ]
19290d38322287fcb8e0152a7ed3b7f01033b57e
https://github.com/eanlain/calligraphy/blob/19290d38322287fcb8e0152a7ed3b7f01033b57e/lib/calligraphy/utils.rb#L47-L50
train
eprothro/cassie
lib/cassie/statements/execution.rb
Cassie::Statements.Execution.execute
def execute(opts={}) @result = result_class.new(session.execute(statement, execution_options.merge(opts)), result_opts) result.success? end
ruby
def execute(opts={}) @result = result_class.new(session.execute(statement, execution_options.merge(opts)), result_opts) result.success? end
[ "def", "execute", "(", "opts", "=", "{", "}", ")", "@result", "=", "result_class", ".", "new", "(", "session", ".", "execute", "(", "statement", ",", "execution_options", ".", "merge", "(", "opts", ")", ")", ",", "result_opts", ")", "result", ".", "success?", "end" ]
Executes the statment and populates result @param [Hash{Symbol => Object}] cassandra_driver execution options @return [Boolean] indicating a successful execution or not
[ "Executes", "the", "statment", "and", "populates", "result" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution.rb#L59-L62
train
eprothro/cassie
lib/cassie/statements/execution.rb
Cassie::Statements.Execution.execution_options
def execution_options {}.tap do |opts| # @todo rework consistency module to be more # abstract implementation for all execution options opts[:consistency] = consistency if consistency opts[:paging_state] = paging_state if respond_to?(:paging_state) && paging_state opts[:page_size] = stateless_page_size if respond_to?(:stateless_page_size) && stateless_page_size end end
ruby
def execution_options {}.tap do |opts| # @todo rework consistency module to be more # abstract implementation for all execution options opts[:consistency] = consistency if consistency opts[:paging_state] = paging_state if respond_to?(:paging_state) && paging_state opts[:page_size] = stateless_page_size if respond_to?(:stateless_page_size) && stateless_page_size end end
[ "def", "execution_options", "{", "}", ".", "tap", "do", "|", "opts", "|", "opts", "[", ":consistency", "]", "=", "consistency", "if", "consistency", "opts", "[", ":paging_state", "]", "=", "paging_state", "if", "respond_to?", "(", ":paging_state", ")", "&&", "paging_state", "opts", "[", ":page_size", "]", "=", "stateless_page_size", "if", "respond_to?", "(", ":stateless_page_size", ")", "&&", "stateless_page_size", "end", "end" ]
The session exection options configured for statement execution @return [Hash{Symbol => Object}]
[ "The", "session", "exection", "options", "configured", "for", "statement", "execution" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution.rb#L74-L82
train
robertwahler/repo_manager
lib/repo_manager/tasks/add/asset.rb
RepoManager.Add.save_writable_attributes
def save_writable_attributes(asset, attributes) valid_keys = [:parent, :path] accessable_attributes = {} attributes.each do |key, value| accessable_attributes[key] = value.dup if valid_keys.include?(key) end asset.configuration.save(accessable_attributes) end
ruby
def save_writable_attributes(asset, attributes) valid_keys = [:parent, :path] accessable_attributes = {} attributes.each do |key, value| accessable_attributes[key] = value.dup if valid_keys.include?(key) end asset.configuration.save(accessable_attributes) end
[ "def", "save_writable_attributes", "(", "asset", ",", "attributes", ")", "valid_keys", "=", "[", ":parent", ",", ":path", "]", "accessable_attributes", "=", "{", "}", "attributes", ".", "each", "do", "|", "key", ",", "value", "|", "accessable_attributes", "[", "key", "]", "=", "value", ".", "dup", "if", "valid_keys", ".", "include?", "(", "key", ")", "end", "asset", ".", "configuration", ".", "save", "(", "accessable_attributes", ")", "end" ]
write only the attributes that we have set
[ "write", "only", "the", "attributes", "that", "we", "have", "set" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/add/asset.rb#L199-L206
train
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.method_missing
def method_missing(method_sym, *arguments, &block) # Only refresh data if its more than 0.25 seconds old et = @last_read_timestamp.nil? ? 0 : (Time.now - @last_read_timestamp) @logger.debug "Elapsed time since last read #{et}" if et > 250 @logger.info "More than 250 milliseconds have passed since last read. Triggering refresh." read() end if @values.include? method_sym @values[method_sym] else @logger.debug "method_missing failed to find #{method_sym} in the Meter.values cache" super end end
ruby
def method_missing(method_sym, *arguments, &block) # Only refresh data if its more than 0.25 seconds old et = @last_read_timestamp.nil? ? 0 : (Time.now - @last_read_timestamp) @logger.debug "Elapsed time since last read #{et}" if et > 250 @logger.info "More than 250 milliseconds have passed since last read. Triggering refresh." read() end if @values.include? method_sym @values[method_sym] else @logger.debug "method_missing failed to find #{method_sym} in the Meter.values cache" super end end
[ "def", "method_missing", "(", "method_sym", ",", "*", "arguments", ",", "&", "block", ")", "et", "=", "@last_read_timestamp", ".", "nil?", "?", "0", ":", "(", "Time", ".", "now", "-", "@last_read_timestamp", ")", "@logger", ".", "debug", "\"Elapsed time since last read #{et}\"", "if", "et", ">", "250", "@logger", ".", "info", "\"More than 250 milliseconds have passed since last read. Triggering refresh.\"", "read", "(", ")", "end", "if", "@values", ".", "include?", "method_sym", "@values", "[", "method_sym", "]", "else", "@logger", ".", "debug", "\"method_missing failed to find #{method_sym} in the Meter.values cache\"", "super", "end", "end" ]
Attribute handler that delegates attribute reads to the values hash
[ "Attribute", "handler", "that", "delegates", "attribute", "reads", "to", "the", "values", "hash" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L140-L155
train
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.calculate_measurement
def calculate_measurement(m1, m2, m3) if power_configuration == :single_phase_2wire m1 elsif power_configuration == :single_phase_3wire (m1 + m2) elsif power_configuration == :three_phase_3wire (m1 + m3) elsif power_configuration == :three_phase_4wire (m1 + m2 + m3) end end
ruby
def calculate_measurement(m1, m2, m3) if power_configuration == :single_phase_2wire m1 elsif power_configuration == :single_phase_3wire (m1 + m2) elsif power_configuration == :three_phase_3wire (m1 + m3) elsif power_configuration == :three_phase_4wire (m1 + m2 + m3) end end
[ "def", "calculate_measurement", "(", "m1", ",", "m2", ",", "m3", ")", "if", "power_configuration", "==", ":single_phase_2wire", "m1", "elsif", "power_configuration", "==", ":single_phase_3wire", "(", "m1", "+", "m2", ")", "elsif", "power_configuration", "==", ":three_phase_3wire", "(", "m1", "+", "m3", ")", "elsif", "power_configuration", "==", ":three_phase_4wire", "(", "m1", "+", "m2", "+", "m3", ")", "end", "end" ]
Returns the correct measurement for voltage, current, and power based on the corresponding power_configuration
[ "Returns", "the", "correct", "measurement", "for", "voltage", "current", "and", "power", "based", "on", "the", "corresponding", "power_configuration" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L512-L522
train
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.as_datetime
def as_datetime(s) begin d = DateTime.new("20#{s[0,2]}".to_i, s[2,2].to_i, s[4,2].to_i, s[8,2].to_i, s[10,2].to_i, s[12,2].to_i, '-4') rescue logger.error "Could not create valid datetime from #{s}\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')" d = DateTime.now() end d end
ruby
def as_datetime(s) begin d = DateTime.new("20#{s[0,2]}".to_i, s[2,2].to_i, s[4,2].to_i, s[8,2].to_i, s[10,2].to_i, s[12,2].to_i, '-4') rescue logger.error "Could not create valid datetime from #{s}\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')" d = DateTime.now() end d end
[ "def", "as_datetime", "(", "s", ")", "begin", "d", "=", "DateTime", ".", "new", "(", "\"20#{s[0,2]}\"", ".", "to_i", ",", "s", "[", "2", ",", "2", "]", ".", "to_i", ",", "s", "[", "4", ",", "2", "]", ".", "to_i", ",", "s", "[", "8", ",", "2", "]", ".", "to_i", ",", "s", "[", "10", ",", "2", "]", ".", "to_i", ",", "s", "[", "12", ",", "2", "]", ".", "to_i", ",", "'-4'", ")", "rescue", "logger", ".", "error", "\"Could not create valid datetime from #{s}\\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')\"", "d", "=", "DateTime", ".", "now", "(", ")", "end", "d", "end" ]
Returns a Ruby datatime derived from the string representing the time on the meter when the values were captured The raw string's format is YYMMDDWWHHMMSS where YY is year without century, and WW is week day with Sunday as the first day of the week
[ "Returns", "a", "Ruby", "datatime", "derived", "from", "the", "string", "representing", "the", "time", "on", "the", "meter", "when", "the", "values", "were", "captured", "The", "raw", "string", "s", "format", "is", "YYMMDDWWHHMMSS", "where", "YY", "is", "year", "without", "century", "and", "WW", "is", "week", "day", "with", "Sunday", "as", "the", "first", "day", "of", "the", "week" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L527-L535
train
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.to_f_with_decimal_places
def to_f_with_decimal_places(s, p=1) unless s.nil? v = (s.to_f / (10 ** p)) logger.debug "Casting #{s.inspect} -> #{v.inspect}" v else logger.error "Could not cast #{s} to #{p} decimal places" end end
ruby
def to_f_with_decimal_places(s, p=1) unless s.nil? v = (s.to_f / (10 ** p)) logger.debug "Casting #{s.inspect} -> #{v.inspect}" v else logger.error "Could not cast #{s} to #{p} decimal places" end end
[ "def", "to_f_with_decimal_places", "(", "s", ",", "p", "=", "1", ")", "unless", "s", ".", "nil?", "v", "=", "(", "s", ".", "to_f", "/", "(", "10", "**", "p", ")", ")", "logger", ".", "debug", "\"Casting #{s.inspect} -> #{v.inspect}\"", "v", "else", "logger", ".", "error", "\"Could not cast #{s} to #{p} decimal places\"", "end", "end" ]
Generic way of casting strings to numbers with the decimal in the correct place
[ "Generic", "way", "of", "casting", "strings", "to", "numbers", "with", "the", "decimal", "in", "the", "correct", "place" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L552-L560
train
rvolz/docbook_status
lib/docbook_status/history.rb
DocbookStatus.History.add
def add(ts, word_count) # Ruby 1.8 doesn't have DateTime#to_date, so we check that here begin k = ts.to_date rescue NoMethodError k = Date.parse(ts.to_s) end if @history[:archive][k].nil? @history[:archive][k] = { min: word_count, max: word_count, start: word_count, end: word_count, ctr: 1 } else @history[:archive][k][:min] = word_count if @history[:archive][k][:min] > word_count @history[:archive][k][:max] = word_count if @history[:archive][k][:max] < word_count @history[:archive][k][:end] = word_count @history[:archive][k][:ctr] += 1 end end
ruby
def add(ts, word_count) # Ruby 1.8 doesn't have DateTime#to_date, so we check that here begin k = ts.to_date rescue NoMethodError k = Date.parse(ts.to_s) end if @history[:archive][k].nil? @history[:archive][k] = { min: word_count, max: word_count, start: word_count, end: word_count, ctr: 1 } else @history[:archive][k][:min] = word_count if @history[:archive][k][:min] > word_count @history[:archive][k][:max] = word_count if @history[:archive][k][:max] < word_count @history[:archive][k][:end] = word_count @history[:archive][k][:ctr] += 1 end end
[ "def", "add", "(", "ts", ",", "word_count", ")", "begin", "k", "=", "ts", ".", "to_date", "rescue", "NoMethodError", "k", "=", "Date", ".", "parse", "(", "ts", ".", "to_s", ")", "end", "if", "@history", "[", ":archive", "]", "[", "k", "]", ".", "nil?", "@history", "[", ":archive", "]", "[", "k", "]", "=", "{", "min", ":", "word_count", ",", "max", ":", "word_count", ",", "start", ":", "word_count", ",", "end", ":", "word_count", ",", "ctr", ":", "1", "}", "else", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":min", "]", "=", "word_count", "if", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":min", "]", ">", "word_count", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":max", "]", "=", "word_count", "if", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":max", "]", "<", "word_count", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":end", "]", "=", "word_count", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":ctr", "]", "+=", "1", "end", "end" ]
Add to the history
[ "Add", "to", "the", "history" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/history.rb#L74-L89
train
Falkor/falkorlib
lib/falkorlib/git/flow.rb
FalkorLib.GitFlow.command
def command(name, type = 'feature', action = 'start', path = Dir.pwd, optional_args = '') error "Invalid git-flow type '#{type}'" unless %w(feature release hotfix support).include?(type) error "Invalid action '#{action}'" unless %w(start finish).include?(action) error "You must provide a name" if name == '' error "The name '#{name}' cannot contain spaces" if name =~ /\s+/ exit_status = 1 Dir.chdir( FalkorLib::Git.rootdir(path) ) do exit_status = run %( git flow #{type} #{action} #{optional_args} #{name} ) end exit_status end
ruby
def command(name, type = 'feature', action = 'start', path = Dir.pwd, optional_args = '') error "Invalid git-flow type '#{type}'" unless %w(feature release hotfix support).include?(type) error "Invalid action '#{action}'" unless %w(start finish).include?(action) error "You must provide a name" if name == '' error "The name '#{name}' cannot contain spaces" if name =~ /\s+/ exit_status = 1 Dir.chdir( FalkorLib::Git.rootdir(path) ) do exit_status = run %( git flow #{type} #{action} #{optional_args} #{name} ) end exit_status end
[ "def", "command", "(", "name", ",", "type", "=", "'feature'", ",", "action", "=", "'start'", ",", "path", "=", "Dir", ".", "pwd", ",", "optional_args", "=", "''", ")", "error", "\"Invalid git-flow type '#{type}'\"", "unless", "%w(", "feature", "release", "hotfix", "support", ")", ".", "include?", "(", "type", ")", "error", "\"Invalid action '#{action}'\"", "unless", "%w(", "start", "finish", ")", ".", "include?", "(", "action", ")", "error", "\"You must provide a name\"", "if", "name", "==", "''", "error", "\"The name '#{name}' cannot contain spaces\"", "if", "name", "=~", "/", "\\s", "/", "exit_status", "=", "1", "Dir", ".", "chdir", "(", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ")", "do", "exit_status", "=", "run", "%( git flow #{type} #{action} #{optional_args} #{name} )", "end", "exit_status", "end" ]
generic function to run any of the gitflow commands
[ "generic", "function", "to", "run", "any", "of", "the", "gitflow", "commands" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/flow.rb#L154-L166
train
Falkor/falkorlib
lib/falkorlib/git/flow.rb
FalkorLib.GitFlow.guess_gitflow_config
def guess_gitflow_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) return {} if (!use_git or !FalkorLib::GitFlow.init?(path)) rootdir = FalkorLib::Git.rootdir(path) local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:gitflow] if local_config[:gitflow] config = FalkorLib::Config::GitFlow::DEFAULTS.clone [ :master, :develop ].each do |br| config[:branches][br.to_sym] = FalkorLib::Git.config("gitflow.branch.#{br}", rootdir) end [ :feature, :release, :hotfix, :support, :versiontag ].each do |p| config[:prefix][p.to_sym] = FalkorLib::Git.config("gitflow.prefix.#{p}", rootdir) end config end
ruby
def guess_gitflow_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) return {} if (!use_git or !FalkorLib::GitFlow.init?(path)) rootdir = FalkorLib::Git.rootdir(path) local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:gitflow] if local_config[:gitflow] config = FalkorLib::Config::GitFlow::DEFAULTS.clone [ :master, :develop ].each do |br| config[:branches][br.to_sym] = FalkorLib::Git.config("gitflow.branch.#{br}", rootdir) end [ :feature, :release, :hotfix, :support, :versiontag ].each do |p| config[:prefix][p.to_sym] = FalkorLib::Git.config("gitflow.prefix.#{p}", rootdir) end config end
[ "def", "guess_gitflow_config", "(", "dir", "=", "Dir", ".", "pwd", ",", "options", "=", "{", "}", ")", "path", "=", "normalized_path", "(", "dir", ")", "use_git", "=", "FalkorLib", "::", "Git", ".", "init?", "(", "path", ")", "return", "{", "}", "if", "(", "!", "use_git", "or", "!", "FalkorLib", "::", "GitFlow", ".", "init?", "(", "path", ")", ")", "rootdir", "=", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", "local_config", "=", "FalkorLib", "::", "Config", ".", "get", "(", "rootdir", ",", ":local", ")", "return", "local_config", "[", ":gitflow", "]", "if", "local_config", "[", ":gitflow", "]", "config", "=", "FalkorLib", "::", "Config", "::", "GitFlow", "::", "DEFAULTS", ".", "clone", "[", ":master", ",", ":develop", "]", ".", "each", "do", "|", "br", "|", "config", "[", ":branches", "]", "[", "br", ".", "to_sym", "]", "=", "FalkorLib", "::", "Git", ".", "config", "(", "\"gitflow.branch.#{br}\"", ",", "rootdir", ")", "end", "[", ":feature", ",", ":release", ",", ":hotfix", ",", ":support", ",", ":versiontag", "]", ".", "each", "do", "|", "p", "|", "config", "[", ":prefix", "]", "[", "p", ".", "to_sym", "]", "=", "FalkorLib", "::", "Git", ".", "config", "(", "\"gitflow.prefix.#{p}\"", ",", "rootdir", ")", "end", "config", "end" ]
master_branch guess_gitflow_config Guess the gitflow configuration
[ "master_branch", "guess_gitflow_config", "Guess", "the", "gitflow", "configuration" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/flow.rb#L191-L206
train
STUDITEMPS/jobmensa_assets
lib/jobmensa_assets/image_processor.rb
JobmensaAssets.ImageProcessor.call
def call(file, *args, format: nil) img = ::MiniMagick::Image.new(file.path) img.quiet img.format(format.to_s.downcase, nil) if format send(@method, img, *args) post_processing(img) ::File.open(img.path, "rb") end
ruby
def call(file, *args, format: nil) img = ::MiniMagick::Image.new(file.path) img.quiet img.format(format.to_s.downcase, nil) if format send(@method, img, *args) post_processing(img) ::File.open(img.path, "rb") end
[ "def", "call", "(", "file", ",", "*", "args", ",", "format", ":", "nil", ")", "img", "=", "::", "MiniMagick", "::", "Image", ".", "new", "(", "file", ".", "path", ")", "img", ".", "quiet", "img", ".", "format", "(", "format", ".", "to_s", ".", "downcase", ",", "nil", ")", "if", "format", "send", "(", "@method", ",", "img", ",", "*", "args", ")", "post_processing", "(", "img", ")", "::", "File", ".", "open", "(", "img", ".", "path", ",", "\"rb\"", ")", "end" ]
Overwrite refile call method to supress format warnings and do post-processing
[ "Overwrite", "refile", "call", "method", "to", "supress", "format", "warnings", "and", "do", "post", "-", "processing" ]
9ef443a28d939130621d4310fdb174764a00baac
https://github.com/STUDITEMPS/jobmensa_assets/blob/9ef443a28d939130621d4310fdb174764a00baac/lib/jobmensa_assets/image_processor.rb#L15-L23
train
STUDITEMPS/jobmensa_assets
lib/jobmensa_assets/image_processor.rb
JobmensaAssets.ImageProcessor.post_processing
def post_processing(img) img.combine_options do |cmd| cmd.strip # Deletes metatags cmd.colorspace 'sRGB' # Change colorspace cmd.auto_orient # Reset rotation cmd.quiet # Suppress warnings end end
ruby
def post_processing(img) img.combine_options do |cmd| cmd.strip # Deletes metatags cmd.colorspace 'sRGB' # Change colorspace cmd.auto_orient # Reset rotation cmd.quiet # Suppress warnings end end
[ "def", "post_processing", "(", "img", ")", "img", ".", "combine_options", "do", "|", "cmd", "|", "cmd", ".", "strip", "cmd", ".", "colorspace", "'sRGB'", "cmd", ".", "auto_orient", "cmd", ".", "quiet", "end", "end" ]
Should be called for every jobmensa processor
[ "Should", "be", "called", "for", "every", "jobmensa", "processor" ]
9ef443a28d939130621d4310fdb174764a00baac
https://github.com/STUDITEMPS/jobmensa_assets/blob/9ef443a28d939130621d4310fdb174764a00baac/lib/jobmensa_assets/image_processor.rb#L29-L36
train
paulRbr/gares
lib/gares/train.rb
Gares.Train.document
def document if !@document @document = Nokogiri::HTML(self.class.request_sncf(number, date)) if !itinerary_available? @document = Nokogiri::HTML(self.class.request_sncf_itinerary(0)) end end if @document.at('#no_results') fail TrainNotFound, @document.at('#no_results b').inner_html end @document end
ruby
def document if !@document @document = Nokogiri::HTML(self.class.request_sncf(number, date)) if !itinerary_available? @document = Nokogiri::HTML(self.class.request_sncf_itinerary(0)) end end if @document.at('#no_results') fail TrainNotFound, @document.at('#no_results b').inner_html end @document end
[ "def", "document", "if", "!", "@document", "@document", "=", "Nokogiri", "::", "HTML", "(", "self", ".", "class", ".", "request_sncf", "(", "number", ",", "date", ")", ")", "if", "!", "itinerary_available?", "@document", "=", "Nokogiri", "::", "HTML", "(", "self", ".", "class", ".", "request_sncf_itinerary", "(", "0", ")", ")", "end", "end", "if", "@document", ".", "at", "(", "'#no_results'", ")", "fail", "TrainNotFound", ",", "@document", ".", "at", "(", "'#no_results b'", ")", ".", "inner_html", "end", "@document", "end" ]
Returns a new Nokogiri document for parsing.
[ "Returns", "a", "new", "Nokogiri", "document", "for", "parsing", "." ]
6646da7c98ffe51f419e9bd6d8d87204ac72da67
https://github.com/paulRbr/gares/blob/6646da7c98ffe51f419e9bd6d8d87204ac72da67/lib/gares/train.rb#L91-L102
train
Nedomas/securities
lib/securities/stock.rb
Securities.Stock.generate_history_url
def generate_history_url url = 'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv' % [ @symbol, @start_date.to_date.month - 1, @start_date.to_date.day, @start_date.to_date.year, @end_date.to_date.month - 1, @end_date.to_date.day, @end_date.to_date.year, TYPE_CODES_ARRAY[@type] ] return url end
ruby
def generate_history_url url = 'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv' % [ @symbol, @start_date.to_date.month - 1, @start_date.to_date.day, @start_date.to_date.year, @end_date.to_date.month - 1, @end_date.to_date.day, @end_date.to_date.year, TYPE_CODES_ARRAY[@type] ] return url end
[ "def", "generate_history_url", "url", "=", "'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv'", "%", "[", "@symbol", ",", "@start_date", ".", "to_date", ".", "month", "-", "1", ",", "@start_date", ".", "to_date", ".", "day", ",", "@start_date", ".", "to_date", ".", "year", ",", "@end_date", ".", "to_date", ".", "month", "-", "1", ",", "@end_date", ".", "to_date", ".", "day", ",", "@end_date", ".", "to_date", ".", "year", ",", "TYPE_CODES_ARRAY", "[", "@type", "]", "]", "return", "url", "end" ]
History URL generator Generating URL for various types of requests within stocks. Using Yahoo Finance http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv s = stock symbol Period start date a = start month b = start day c = start year Period end date d = end month e = end day f = end year g = type Type values allowed: 'd' for daily (the default), 'w' for weekly, 'm' for monthly and 'v' for dividends.
[ "History", "URL", "generator" ]
e2c4953edcb7315d49663f2e5b71aaf6b27d97d1
https://github.com/Nedomas/securities/blob/e2c4953edcb7315d49663f2e5b71aaf6b27d97d1/lib/securities/stock.rb#L48-L62
train
Nedomas/securities
lib/securities/stock.rb
Securities.Stock.validate_input
def validate_input parameters unless parameters.is_a?(Hash) raise StockException, 'Given parameters have to be a hash.' end # Check if stock symbol is specified. unless parameters.has_key?(:symbol) raise StockException, 'No stock symbol specified.' end # Check if stock symbol is a string. unless parameters[:symbol].is_a?(String) raise StockException, 'Stock symbol must be a string.' end # Use today date if :end_date is not specified. unless parameters.has_key?(:end_date) parameters[:end_date] = Date.today.strftime("%Y-%m-%d") end unless parameters.has_key?(:start_date) raise StockException, 'Start date must be specified.' end unless DATE_REGEX.match(parameters[:start_date]) raise StockException, 'Invalid start date specified. Format YYYY-MM-DD.' end unless DATE_REGEX.match(parameters[:end_date]) raise StockException, 'Invalid end date specified. Format YYYY-MM-DD.' end unless parameters[:start_date].to_date < parameters[:end_date].to_date raise StockException, 'End date must be greater than the start date.' end unless parameters[:start_date].to_date < Date.today raise StockException, 'Start date must not be in the future.' end # Set to default :type if key isn't specified. parameters[:type] = :daily if !parameters.has_key?(:type) unless TYPE_CODES_ARRAY.has_key?(parameters[:type]) raise StockException, 'Invalid type specified.' end end
ruby
def validate_input parameters unless parameters.is_a?(Hash) raise StockException, 'Given parameters have to be a hash.' end # Check if stock symbol is specified. unless parameters.has_key?(:symbol) raise StockException, 'No stock symbol specified.' end # Check if stock symbol is a string. unless parameters[:symbol].is_a?(String) raise StockException, 'Stock symbol must be a string.' end # Use today date if :end_date is not specified. unless parameters.has_key?(:end_date) parameters[:end_date] = Date.today.strftime("%Y-%m-%d") end unless parameters.has_key?(:start_date) raise StockException, 'Start date must be specified.' end unless DATE_REGEX.match(parameters[:start_date]) raise StockException, 'Invalid start date specified. Format YYYY-MM-DD.' end unless DATE_REGEX.match(parameters[:end_date]) raise StockException, 'Invalid end date specified. Format YYYY-MM-DD.' end unless parameters[:start_date].to_date < parameters[:end_date].to_date raise StockException, 'End date must be greater than the start date.' end unless parameters[:start_date].to_date < Date.today raise StockException, 'Start date must not be in the future.' end # Set to default :type if key isn't specified. parameters[:type] = :daily if !parameters.has_key?(:type) unless TYPE_CODES_ARRAY.has_key?(parameters[:type]) raise StockException, 'Invalid type specified.' end end
[ "def", "validate_input", "parameters", "unless", "parameters", ".", "is_a?", "(", "Hash", ")", "raise", "StockException", ",", "'Given parameters have to be a hash.'", "end", "unless", "parameters", ".", "has_key?", "(", ":symbol", ")", "raise", "StockException", ",", "'No stock symbol specified.'", "end", "unless", "parameters", "[", ":symbol", "]", ".", "is_a?", "(", "String", ")", "raise", "StockException", ",", "'Stock symbol must be a string.'", "end", "unless", "parameters", ".", "has_key?", "(", ":end_date", ")", "parameters", "[", ":end_date", "]", "=", "Date", ".", "today", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "end", "unless", "parameters", ".", "has_key?", "(", ":start_date", ")", "raise", "StockException", ",", "'Start date must be specified.'", "end", "unless", "DATE_REGEX", ".", "match", "(", "parameters", "[", ":start_date", "]", ")", "raise", "StockException", ",", "'Invalid start date specified. Format YYYY-MM-DD.'", "end", "unless", "DATE_REGEX", ".", "match", "(", "parameters", "[", ":end_date", "]", ")", "raise", "StockException", ",", "'Invalid end date specified. Format YYYY-MM-DD.'", "end", "unless", "parameters", "[", ":start_date", "]", ".", "to_date", "<", "parameters", "[", ":end_date", "]", ".", "to_date", "raise", "StockException", ",", "'End date must be greater than the start date.'", "end", "unless", "parameters", "[", ":start_date", "]", ".", "to_date", "<", "Date", ".", "today", "raise", "StockException", ",", "'Start date must not be in the future.'", "end", "parameters", "[", ":type", "]", "=", ":daily", "if", "!", "parameters", ".", "has_key?", "(", ":type", ")", "unless", "TYPE_CODES_ARRAY", ".", "has_key?", "(", "parameters", "[", ":type", "]", ")", "raise", "StockException", ",", "'Invalid type specified.'", "end", "end" ]
Input parameters validation
[ "Input", "parameters", "validation" ]
e2c4953edcb7315d49663f2e5b71aaf6b27d97d1
https://github.com/Nedomas/securities/blob/e2c4953edcb7315d49663f2e5b71aaf6b27d97d1/lib/securities/stock.rb#L68-L113
train
praxis/praxis-blueprints
lib/praxis-blueprints/renderer.rb
Praxis.Renderer.render_collection
def render_collection(collection, member_fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) render(collection, [member_fields], view, context: context) end
ruby
def render_collection(collection, member_fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) render(collection, [member_fields], view, context: context) end
[ "def", "render_collection", "(", "collection", ",", "member_fields", ",", "view", "=", "nil", ",", "context", ":", "Attributor", "::", "DEFAULT_ROOT_CONTEXT", ")", "render", "(", "collection", ",", "[", "member_fields", "]", ",", "view", ",", "context", ":", "context", ")", "end" ]
Renders an a collection using a given list of per-member fields. @param [Object] object the object to render @param [Hash] fields the set of fields, as from FieldExpander, to apply to each member of the collection.
[ "Renders", "an", "a", "collection", "using", "a", "given", "list", "of", "per", "-", "member", "fields", "." ]
57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c
https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/renderer.rb#L34-L36
train
praxis/praxis-blueprints
lib/praxis-blueprints/renderer.rb
Praxis.Renderer.render
def render(object, fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) if fields.is_a? Array sub_fields = fields[0] object.each_with_index.collect do |sub_object, i| sub_context = context + ["at(#{i})"] render(sub_object, sub_fields, view, context: sub_context) end elsif object.is_a? Praxis::Blueprint @cache[object.object_id][fields.object_id] ||= _render(object, fields, view, context: context) else _render(object, fields, view, context: context) end rescue SystemStackError raise CircularRenderingError.new(object, context) end
ruby
def render(object, fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) if fields.is_a? Array sub_fields = fields[0] object.each_with_index.collect do |sub_object, i| sub_context = context + ["at(#{i})"] render(sub_object, sub_fields, view, context: sub_context) end elsif object.is_a? Praxis::Blueprint @cache[object.object_id][fields.object_id] ||= _render(object, fields, view, context: context) else _render(object, fields, view, context: context) end rescue SystemStackError raise CircularRenderingError.new(object, context) end
[ "def", "render", "(", "object", ",", "fields", ",", "view", "=", "nil", ",", "context", ":", "Attributor", "::", "DEFAULT_ROOT_CONTEXT", ")", "if", "fields", ".", "is_a?", "Array", "sub_fields", "=", "fields", "[", "0", "]", "object", ".", "each_with_index", ".", "collect", "do", "|", "sub_object", ",", "i", "|", "sub_context", "=", "context", "+", "[", "\"at(#{i})\"", "]", "render", "(", "sub_object", ",", "sub_fields", ",", "view", ",", "context", ":", "sub_context", ")", "end", "elsif", "object", ".", "is_a?", "Praxis", "::", "Blueprint", "@cache", "[", "object", ".", "object_id", "]", "[", "fields", ".", "object_id", "]", "||=", "_render", "(", "object", ",", "fields", ",", "view", ",", "context", ":", "context", ")", "else", "_render", "(", "object", ",", "fields", ",", "view", ",", "context", ":", "context", ")", "end", "rescue", "SystemStackError", "raise", "CircularRenderingError", ".", "new", "(", "object", ",", "context", ")", "end" ]
Renders an object using a given list of fields. @param [Object] object the object to render @param [Hash] fields the correct set of fields, as from FieldExpander
[ "Renders", "an", "object", "using", "a", "given", "list", "of", "fields", "." ]
57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c
https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/renderer.rb#L42-L56
train
ohler55/opee
lib/opee/log.rb
Opee.Log.log
def log(severity, message, tid) now = Time.now ss = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'][severity] ss = '' if ss.nil? if @formatter.nil? msg = "#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\n" else msg = @formatter.call(ss, now, tid, message) end @logger.add(severity, msg) @forward.log(severity, message, tid) unless @forward.nil? end
ruby
def log(severity, message, tid) now = Time.now ss = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'][severity] ss = '' if ss.nil? if @formatter.nil? msg = "#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\n" else msg = @formatter.call(ss, now, tid, message) end @logger.add(severity, msg) @forward.log(severity, message, tid) unless @forward.nil? end
[ "def", "log", "(", "severity", ",", "message", ",", "tid", ")", "now", "=", "Time", ".", "now", "ss", "=", "[", "'DEBUG'", ",", "'INFO'", ",", "'WARN'", ",", "'ERROR'", ",", "'FATAL'", "]", "[", "severity", "]", "ss", "=", "''", "if", "ss", ".", "nil?", "if", "@formatter", ".", "nil?", "msg", "=", "\"#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\\n\"", "else", "msg", "=", "@formatter", ".", "call", "(", "ss", ",", "now", ",", "tid", ",", "message", ")", "end", "@logger", ".", "add", "(", "severity", ",", "msg", ")", "@forward", ".", "log", "(", "severity", ",", "message", ",", "tid", ")", "unless", "@forward", ".", "nil?", "end" ]
Writes a message if the severity is high enough. This method is executed asynchronously. @param [Fixnum] severity one of the Logger levels @param [String] message string to log @param [Fixnum|String] tid thread id of the thread generating the message
[ "Writes", "a", "message", "if", "the", "severity", "is", "high", "enough", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L69-L80
train
ohler55/opee
lib/opee/log.rb
Opee.Log.stream=
def stream=(stream) logger = Logger.new(stream) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
ruby
def stream=(stream) logger = Logger.new(stream) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
[ "def", "stream", "=", "(", "stream", ")", "logger", "=", "Logger", ".", "new", "(", "stream", ")", "logger", ".", "level", "=", "@logger", ".", "level", "logger", ".", "formatter", "=", "@logger", ".", "formatter", "@logger", "=", "logger", "end" ]
Sets the logger to use the stream specified. This method is executed asynchronously. @param [IO] stream stream to write log messages to
[ "Sets", "the", "logger", "to", "use", "the", "stream", "specified", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L85-L90
train
ohler55/opee
lib/opee/log.rb
Opee.Log.set_filename
def set_filename(filename, shift_age=7, shift_size=1048576) logger = Logger.new(filename, shift_age, shift_size) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
ruby
def set_filename(filename, shift_age=7, shift_size=1048576) logger = Logger.new(filename, shift_age, shift_size) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
[ "def", "set_filename", "(", "filename", ",", "shift_age", "=", "7", ",", "shift_size", "=", "1048576", ")", "logger", "=", "Logger", ".", "new", "(", "filename", ",", "shift_age", ",", "shift_size", ")", "logger", ".", "level", "=", "@logger", ".", "level", "logger", ".", "formatter", "=", "@logger", ".", "formatter", "@logger", "=", "logger", "end" ]
Creates a new Logger to write log messages to using the parameters specified. This method is executed asynchronously. @param [String] filename filename of active log file @param [Fixmun] shift_age maximum number of archive files to save @param [Fixmun] shift_size maximum file size
[ "Creates", "a", "new", "Logger", "to", "write", "log", "messages", "to", "using", "the", "parameters", "specified", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L97-L102
train
ohler55/opee
lib/opee/log.rb
Opee.Log.severity=
def severity=(level) if level.is_a?(String) severity = { 'FATAL' => Logger::Severity::FATAL, 'ERROR' => Logger::Severity::ERROR, 'WARN' => Logger::Severity::WARN, 'INFO' => Logger::Severity::INFO, 'DEBUG' => Logger::Severity::DEBUG, '4' => Logger::Severity::FATAL, '3' => Logger::Severity::ERROR, '2' => Logger::Severity::WARN, '1' => Logger::Severity::INFO, '0' => Logger::Severity::DEBUG }[level.upcase()] raise "#{level} is not a severity" if severity.nil? level = severity elsif level < Logger::Severity::DEBUG || Logger::Severity::FATAL < level raise "#{level} is not a severity" end @logger.level = level end
ruby
def severity=(level) if level.is_a?(String) severity = { 'FATAL' => Logger::Severity::FATAL, 'ERROR' => Logger::Severity::ERROR, 'WARN' => Logger::Severity::WARN, 'INFO' => Logger::Severity::INFO, 'DEBUG' => Logger::Severity::DEBUG, '4' => Logger::Severity::FATAL, '3' => Logger::Severity::ERROR, '2' => Logger::Severity::WARN, '1' => Logger::Severity::INFO, '0' => Logger::Severity::DEBUG }[level.upcase()] raise "#{level} is not a severity" if severity.nil? level = severity elsif level < Logger::Severity::DEBUG || Logger::Severity::FATAL < level raise "#{level} is not a severity" end @logger.level = level end
[ "def", "severity", "=", "(", "level", ")", "if", "level", ".", "is_a?", "(", "String", ")", "severity", "=", "{", "'FATAL'", "=>", "Logger", "::", "Severity", "::", "FATAL", ",", "'ERROR'", "=>", "Logger", "::", "Severity", "::", "ERROR", ",", "'WARN'", "=>", "Logger", "::", "Severity", "::", "WARN", ",", "'INFO'", "=>", "Logger", "::", "Severity", "::", "INFO", ",", "'DEBUG'", "=>", "Logger", "::", "Severity", "::", "DEBUG", ",", "'4'", "=>", "Logger", "::", "Severity", "::", "FATAL", ",", "'3'", "=>", "Logger", "::", "Severity", "::", "ERROR", ",", "'2'", "=>", "Logger", "::", "Severity", "::", "WARN", ",", "'1'", "=>", "Logger", "::", "Severity", "::", "INFO", ",", "'0'", "=>", "Logger", "::", "Severity", "::", "DEBUG", "}", "[", "level", ".", "upcase", "(", ")", "]", "raise", "\"#{level} is not a severity\"", "if", "severity", ".", "nil?", "level", "=", "severity", "elsif", "level", "<", "Logger", "::", "Severity", "::", "DEBUG", "||", "Logger", "::", "Severity", "::", "FATAL", "<", "level", "raise", "\"#{level} is not a severity\"", "end", "@logger", ".", "level", "=", "level", "end" ]
Sets the severity level of the logger. This method is executed asynchronously. @param [String|Fixnum] level value to set the severity to
[ "Sets", "the", "severity", "level", "of", "the", "logger", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L121-L141
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/finding.rb
StatModule.Finding.categories=
def categories=(categories) raise TypeException unless categories.is_a?(Array) categories.each { |item| raise TypeException unless Category.all.include?(item) raise DuplicateElementException if @categories.include?(item) @categories.push(item) } end
ruby
def categories=(categories) raise TypeException unless categories.is_a?(Array) categories.each { |item| raise TypeException unless Category.all.include?(item) raise DuplicateElementException if @categories.include?(item) @categories.push(item) } end
[ "def", "categories", "=", "(", "categories", ")", "raise", "TypeException", "unless", "categories", ".", "is_a?", "(", "Array", ")", "categories", ".", "each", "{", "|", "item", "|", "raise", "TypeException", "unless", "Category", ".", "all", ".", "include?", "(", "item", ")", "raise", "DuplicateElementException", "if", "@categories", ".", "include?", "(", "item", ")", "@categories", ".", "push", "(", "item", ")", "}", "end" ]
Set array of categories Params: +categories+:: array of StatModule::Category
[ "Set", "array", "of", "categories" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/finding.rb#L92-L99
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/finding.rb
StatModule.Finding.print
def print(formatted = false) result = "#{rule}, #{description}" if formatted if failure result = "#{FORMATTING_BALL} #{result}".colorize(:red) else result = "#{FORMATTING_WARNING} #{result}".colorize(:yellow) end end result += "\n#{location.print}" unless location.nil? result += "\nRECOMMENDATION: #{recommendation}" unless recommendation.nil? result end
ruby
def print(formatted = false) result = "#{rule}, #{description}" if formatted if failure result = "#{FORMATTING_BALL} #{result}".colorize(:red) else result = "#{FORMATTING_WARNING} #{result}".colorize(:yellow) end end result += "\n#{location.print}" unless location.nil? result += "\nRECOMMENDATION: #{recommendation}" unless recommendation.nil? result end
[ "def", "print", "(", "formatted", "=", "false", ")", "result", "=", "\"#{rule}, #{description}\"", "if", "formatted", "if", "failure", "result", "=", "\"#{FORMATTING_BALL} #{result}\"", ".", "colorize", "(", ":red", ")", "else", "result", "=", "\"#{FORMATTING_WARNING} #{result}\"", ".", "colorize", "(", ":yellow", ")", "end", "end", "result", "+=", "\"\\n#{location.print}\"", "unless", "location", ".", "nil?", "result", "+=", "\"\\nRECOMMENDATION: #{recommendation}\"", "unless", "recommendation", ".", "nil?", "result", "end" ]
Get formatted information about findings Params: +formatted+:: indicate weather print boring or pretty colorful finding
[ "Get", "formatted", "information", "about", "findings" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/finding.rb#L181-L193
train
dennmart/wanikani-gem
lib/wanikani/critical_items.rb
Wanikani.CriticalItems.critical_items
def critical_items(percentage = 75) raise ArgumentError, "Percentage must be an Integer between 0 and 100" if !percentage.between?(0, 100) response = api_response("critical-items", percentage) return response["requested_information"] end
ruby
def critical_items(percentage = 75) raise ArgumentError, "Percentage must be an Integer between 0 and 100" if !percentage.between?(0, 100) response = api_response("critical-items", percentage) return response["requested_information"] end
[ "def", "critical_items", "(", "percentage", "=", "75", ")", "raise", "ArgumentError", ",", "\"Percentage must be an Integer between 0 and 100\"", "if", "!", "percentage", ".", "between?", "(", "0", ",", "100", ")", "response", "=", "api_response", "(", "\"critical-items\"", ",", "percentage", ")", "return", "response", "[", "\"requested_information\"", "]", "end" ]
Gets the user's current items under 'Critical Items'. @param percentage [Integer] the maximum percentage of correctness. @return [Array<Hash>] critical items and their related information.
[ "Gets", "the", "user", "s", "current", "items", "under", "Critical", "Items", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/critical_items.rb#L8-L12
train
rocky/rbx-trepanning
app/method.rb
Trepanning.Method.find_method_with_line
def find_method_with_line(cm, line) unless cm.kind_of?(Rubinius::CompiledMethod) return nil end lines = lines_of_method(cm) return cm if lines.member?(line) scope = cm.scope return nil unless scope and scope.current_script cm = scope.current_script.compiled_code lines = lines_of_method(cm) until lines.member?(line) do child = scope scope = scope.parent unless scope # child is the top-most scope. Search down from here. cm = child.current_script.compiled_code pair = locate_line(line, cm) ## pair = cm.locate_line(line) return pair ? pair[0] : nil end cm = scope.current_script.compiled_code lines = lines_of_method(cm) end return cm end
ruby
def find_method_with_line(cm, line) unless cm.kind_of?(Rubinius::CompiledMethod) return nil end lines = lines_of_method(cm) return cm if lines.member?(line) scope = cm.scope return nil unless scope and scope.current_script cm = scope.current_script.compiled_code lines = lines_of_method(cm) until lines.member?(line) do child = scope scope = scope.parent unless scope # child is the top-most scope. Search down from here. cm = child.current_script.compiled_code pair = locate_line(line, cm) ## pair = cm.locate_line(line) return pair ? pair[0] : nil end cm = scope.current_script.compiled_code lines = lines_of_method(cm) end return cm end
[ "def", "find_method_with_line", "(", "cm", ",", "line", ")", "unless", "cm", ".", "kind_of?", "(", "Rubinius", "::", "CompiledMethod", ")", "return", "nil", "end", "lines", "=", "lines_of_method", "(", "cm", ")", "return", "cm", "if", "lines", ".", "member?", "(", "line", ")", "scope", "=", "cm", ".", "scope", "return", "nil", "unless", "scope", "and", "scope", ".", "current_script", "cm", "=", "scope", ".", "current_script", ".", "compiled_code", "lines", "=", "lines_of_method", "(", "cm", ")", "until", "lines", ".", "member?", "(", "line", ")", "do", "child", "=", "scope", "scope", "=", "scope", ".", "parent", "unless", "scope", "cm", "=", "child", ".", "current_script", ".", "compiled_code", "pair", "=", "locate_line", "(", "line", ",", "cm", ")", "return", "pair", "?", "pair", "[", "0", "]", ":", "nil", "end", "cm", "=", "scope", ".", "current_script", ".", "compiled_code", "lines", "=", "lines_of_method", "(", "cm", ")", "end", "return", "cm", "end" ]
Returns a CompiledMethod for the specified line. We search the current method +meth+ and then up the parent scope. If we hit the top and we can't find +line+ that way, then we reverse the search from the top and search down. This will add all siblings of ancestors of +meth+.
[ "Returns", "a", "CompiledMethod", "for", "the", "specified", "line", ".", "We", "search", "the", "current", "method", "+", "meth", "+", "and", "then", "up", "the", "parent", "scope", ".", "If", "we", "hit", "the", "top", "and", "we", "can", "t", "find", "+", "line", "+", "that", "way", "then", "we", "reverse", "the", "search", "from", "the", "top", "and", "search", "down", ".", "This", "will", "add", "all", "siblings", "of", "ancestors", "of", "+", "meth", "+", "." ]
192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1
https://github.com/rocky/rbx-trepanning/blob/192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1/app/method.rb#L78-L103
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/channels/channel_manager.rb
GameOverseer.ChannelManager.register_channel
def register_channel(channel, service) _channel = channel.downcase unless @channels[_channel] @channels[_channel] = service GameOverseer::Console.log("ChannelManager> mapped '#{_channel}' to '#{service.class}'.") else raise "Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it." end end
ruby
def register_channel(channel, service) _channel = channel.downcase unless @channels[_channel] @channels[_channel] = service GameOverseer::Console.log("ChannelManager> mapped '#{_channel}' to '#{service.class}'.") else raise "Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it." end end
[ "def", "register_channel", "(", "channel", ",", "service", ")", "_channel", "=", "channel", ".", "downcase", "unless", "@channels", "[", "_channel", "]", "@channels", "[", "_channel", "]", "=", "service", "GameOverseer", "::", "Console", ".", "log", "(", "\"ChannelManager> mapped '#{_channel}' to '#{service.class}'.\"", ")", "else", "raise", "\"Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it.\"", "end", "end" ]
Enables a service to subscribe to a channel @param channel [String] @param service [Service]
[ "Enables", "a", "service", "to", "subscribe", "to", "a", "channel" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/channels/channel_manager.rb#L18-L26
train
nysa/ruby-opencnam
lib/opencnam/client.rb
Opencnam.Client.phone
def phone(phone_number, options = {}) # Build query string options = { :account_sid => account_sid, :auth_token => auth_token, :format => 'text', }.merge(options) options[:format] = options[:format].to_s.strip.downcase # Check for supported format unless %w(text json).include? options[:format] raise ArgumentError.new "Unsupported format: #{options[:format]}" end # Send request http = Net::HTTP.new(API_HOST, (use_ssl? ? '443' : '80')) http.use_ssl = true if use_ssl? query = URI.encode_www_form(options) res = http.request_get("/v2/phone/#{phone_number.strip}?#{query}") # Look up was unsuccessful raise OpencnamError.new res.message unless res.kind_of? Net::HTTPOK return res.body if options[:format] == 'text' return parse_json(res.body) if options[:format] == 'json' end
ruby
def phone(phone_number, options = {}) # Build query string options = { :account_sid => account_sid, :auth_token => auth_token, :format => 'text', }.merge(options) options[:format] = options[:format].to_s.strip.downcase # Check for supported format unless %w(text json).include? options[:format] raise ArgumentError.new "Unsupported format: #{options[:format]}" end # Send request http = Net::HTTP.new(API_HOST, (use_ssl? ? '443' : '80')) http.use_ssl = true if use_ssl? query = URI.encode_www_form(options) res = http.request_get("/v2/phone/#{phone_number.strip}?#{query}") # Look up was unsuccessful raise OpencnamError.new res.message unless res.kind_of? Net::HTTPOK return res.body if options[:format] == 'text' return parse_json(res.body) if options[:format] == 'json' end
[ "def", "phone", "(", "phone_number", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":account_sid", "=>", "account_sid", ",", ":auth_token", "=>", "auth_token", ",", ":format", "=>", "'text'", ",", "}", ".", "merge", "(", "options", ")", "options", "[", ":format", "]", "=", "options", "[", ":format", "]", ".", "to_s", ".", "strip", ".", "downcase", "unless", "%w(", "text", "json", ")", ".", "include?", "options", "[", ":format", "]", "raise", "ArgumentError", ".", "new", "\"Unsupported format: #{options[:format]}\"", "end", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "API_HOST", ",", "(", "use_ssl?", "?", "'443'", ":", "'80'", ")", ")", "http", ".", "use_ssl", "=", "true", "if", "use_ssl?", "query", "=", "URI", ".", "encode_www_form", "(", "options", ")", "res", "=", "http", ".", "request_get", "(", "\"/v2/phone/#{phone_number.strip}?#{query}\"", ")", "raise", "OpencnamError", ".", "new", "res", ".", "message", "unless", "res", ".", "kind_of?", "Net", "::", "HTTPOK", "return", "res", ".", "body", "if", "options", "[", ":format", "]", "==", "'text'", "return", "parse_json", "(", "res", ".", "body", ")", "if", "options", "[", ":format", "]", "==", "'json'", "end" ]
Look up a phone number and return the caller's name. @param [String] phone_number The phone number to look up @param [Hash] options Described below @option options [String] :account_sid Specify a different OpenCNAM account_sid @option options [String] :auth_token Specify a different OpenCNAM auth_token @option options [String, Symbol] :format (:text) The format to retrieve, can be :text or :json @return [String, Hash] the phone number owner's name if :format is :string, or a Hash of additional fields from OpenCNAM if :format is :json (:created, :updated, :name, :price, :uri, and :number)
[ "Look", "up", "a", "phone", "number", "and", "return", "the", "caller", "s", "name", "." ]
7c9e62f6efc59466ab307977bc04070d19c4cadf
https://github.com/nysa/ruby-opencnam/blob/7c9e62f6efc59466ab307977bc04070d19c4cadf/lib/opencnam/client.rb#L51-L76
train
betterplace/spell_number
lib/spell_number/speller.rb
SpellNumber.Speller.two_digit_number
def two_digit_number(number, combined = false) words = combined ? simple_number_to_words_combined(number) : simple_number_to_words(number) return words if(words != 'not_found') rest = number % 10 format = "spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}" first_digit = simple_number_to_words(number - rest) second_digit = simple_number_to_words_combined(rest) I18n.t(format, :locale => @options[:locale], :first_digit => first_digit, :second_digit => second_digit) end
ruby
def two_digit_number(number, combined = false) words = combined ? simple_number_to_words_combined(number) : simple_number_to_words(number) return words if(words != 'not_found') rest = number % 10 format = "spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}" first_digit = simple_number_to_words(number - rest) second_digit = simple_number_to_words_combined(rest) I18n.t(format, :locale => @options[:locale], :first_digit => first_digit, :second_digit => second_digit) end
[ "def", "two_digit_number", "(", "number", ",", "combined", "=", "false", ")", "words", "=", "combined", "?", "simple_number_to_words_combined", "(", "number", ")", ":", "simple_number_to_words", "(", "number", ")", "return", "words", "if", "(", "words", "!=", "'not_found'", ")", "rest", "=", "number", "%", "10", "format", "=", "\"spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}\"", "first_digit", "=", "simple_number_to_words", "(", "number", "-", "rest", ")", "second_digit", "=", "simple_number_to_words_combined", "(", "rest", ")", "I18n", ".", "t", "(", "format", ",", ":locale", "=>", "@options", "[", ":locale", "]", ",", ":first_digit", "=>", "first_digit", ",", ":second_digit", "=>", "second_digit", ")", "end" ]
Transforms a two-digit number from 0 to 99
[ "Transforms", "a", "two", "-", "digit", "number", "from", "0", "to", "99" ]
3dbe6208f365ae5bd848392d1fda134874425c8c
https://github.com/betterplace/spell_number/blob/3dbe6208f365ae5bd848392d1fda134874425c8c/lib/spell_number/speller.rb#L54-L63
train
betterplace/spell_number
lib/spell_number/speller.rb
SpellNumber.Speller.simple_number_to_words_combined
def simple_number_to_words_combined(number) words = I18n.t("spell_number.numbers.number_#{number}_combined", :locale => @options[:locale], :default => 'not_found') words = simple_number_to_words(number) if(words == 'not_found') words end
ruby
def simple_number_to_words_combined(number) words = I18n.t("spell_number.numbers.number_#{number}_combined", :locale => @options[:locale], :default => 'not_found') words = simple_number_to_words(number) if(words == 'not_found') words end
[ "def", "simple_number_to_words_combined", "(", "number", ")", "words", "=", "I18n", ".", "t", "(", "\"spell_number.numbers.number_#{number}_combined\"", ",", ":locale", "=>", "@options", "[", ":locale", "]", ",", ":default", "=>", "'not_found'", ")", "words", "=", "simple_number_to_words", "(", "number", ")", "if", "(", "words", "==", "'not_found'", ")", "words", "end" ]
Returns the "combined" number if it exists in the file, otherwise it will return the simple_number_to_words
[ "Returns", "the", "combined", "number", "if", "it", "exists", "in", "the", "file", "otherwise", "it", "will", "return", "the", "simple_number_to_words" ]
3dbe6208f365ae5bd848392d1fda134874425c8c
https://github.com/betterplace/spell_number/blob/3dbe6208f365ae5bd848392d1fda134874425c8c/lib/spell_number/speller.rb#L67-L71
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.combine_pdfs
def combine_pdfs(combine_pdfs_data, opts = {}) data, _status_code, _headers = combine_pdfs_with_http_info(combine_pdfs_data, opts) data end
ruby
def combine_pdfs(combine_pdfs_data, opts = {}) data, _status_code, _headers = combine_pdfs_with_http_info(combine_pdfs_data, opts) data end
[ "def", "combine_pdfs", "(", "combine_pdfs_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "combine_pdfs_with_http_info", "(", "combine_pdfs_data", ",", "opts", ")", "data", "end" ]
Merge submission PDFs, template PDFs, or custom files @param combine_pdfs_data @param [Hash] opts the optional parameters @return [CreateCombinedSubmissionResponse]
[ "Merge", "submission", "PDFs", "template", "PDFs", "or", "custom", "files" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L138-L141
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.combine_submissions
def combine_submissions(combined_submission_data, opts = {}) data, _status_code, _headers = combine_submissions_with_http_info(combined_submission_data, opts) data end
ruby
def combine_submissions(combined_submission_data, opts = {}) data, _status_code, _headers = combine_submissions_with_http_info(combined_submission_data, opts) data end
[ "def", "combine_submissions", "(", "combined_submission_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "combine_submissions_with_http_info", "(", "combined_submission_data", ",", "opts", ")", "data", "end" ]
Merge generated PDFs together @param combined_submission_data @param [Hash] opts the optional parameters @return [CreateCombinedSubmissionResponse]
[ "Merge", "generated", "PDFs", "together" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L191-L194
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.create_custom_file_from_upload
def create_custom_file_from_upload(create_custom_file_data, opts = {}) data, _status_code, _headers = create_custom_file_from_upload_with_http_info(create_custom_file_data, opts) data end
ruby
def create_custom_file_from_upload(create_custom_file_data, opts = {}) data, _status_code, _headers = create_custom_file_from_upload_with_http_info(create_custom_file_data, opts) data end
[ "def", "create_custom_file_from_upload", "(", "create_custom_file_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_custom_file_from_upload_with_http_info", "(", "create_custom_file_data", ",", "opts", ")", "data", "end" ]
Create a new custom file from a cached presign upload @param create_custom_file_data @param [Hash] opts the optional parameters @return [CreateCustomFileResponse]
[ "Create", "a", "new", "custom", "file", "from", "a", "cached", "presign", "upload" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L244-L247
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.create_data_request_token
def create_data_request_token(data_request_id, opts = {}) data, _status_code, _headers = create_data_request_token_with_http_info(data_request_id, opts) data end
ruby
def create_data_request_token(data_request_id, opts = {}) data, _status_code, _headers = create_data_request_token_with_http_info(data_request_id, opts) data end
[ "def", "create_data_request_token", "(", "data_request_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_data_request_token_with_http_info", "(", "data_request_id", ",", "opts", ")", "data", "end" ]
Creates a new data request token for form authentication @param data_request_id @param [Hash] opts the optional parameters @return [CreateSubmissionDataRequestTokenResponse]
[ "Creates", "a", "new", "data", "request", "token", "for", "form", "authentication" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L297-L300
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.create_template_from_upload
def create_template_from_upload(create_template_data, opts = {}) data, _status_code, _headers = create_template_from_upload_with_http_info(create_template_data, opts) data end
ruby
def create_template_from_upload(create_template_data, opts = {}) data, _status_code, _headers = create_template_from_upload_with_http_info(create_template_data, opts) data end
[ "def", "create_template_from_upload", "(", "create_template_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_template_from_upload_with_http_info", "(", "create_template_data", ",", "opts", ")", "data", "end" ]
Create a new PDF template from a cached presign upload @param create_template_data @param [Hash] opts the optional parameters @return [PendingTemplate]
[ "Create", "a", "new", "PDF", "template", "from", "a", "cached", "presign", "upload" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L409-L412
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.expire_combined_submission
def expire_combined_submission(combined_submission_id, opts = {}) data, _status_code, _headers = expire_combined_submission_with_http_info(combined_submission_id, opts) data end
ruby
def expire_combined_submission(combined_submission_id, opts = {}) data, _status_code, _headers = expire_combined_submission_with_http_info(combined_submission_id, opts) data end
[ "def", "expire_combined_submission", "(", "combined_submission_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "expire_combined_submission_with_http_info", "(", "combined_submission_id", ",", "opts", ")", "data", "end" ]
Expire a combined submission @param combined_submission_id @param [Hash] opts the optional parameters @return [CombinedSubmission]
[ "Expire", "a", "combined", "submission" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L462-L465
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.expire_submission
def expire_submission(submission_id, opts = {}) data, _status_code, _headers = expire_submission_with_http_info(submission_id, opts) data end
ruby
def expire_submission(submission_id, opts = {}) data, _status_code, _headers = expire_submission_with_http_info(submission_id, opts) data end
[ "def", "expire_submission", "(", "submission_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "expire_submission_with_http_info", "(", "submission_id", ",", "opts", ")", "data", "end" ]
Expire a PDF submission @param submission_id @param [Hash] opts the optional parameters @return [Submission]
[ "Expire", "a", "PDF", "submission" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L513-L516
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.generate_pdf
def generate_pdf(template_id, submission_data, opts = {}) data, _status_code, _headers = generate_pdf_with_http_info(template_id, submission_data, opts) data end
ruby
def generate_pdf(template_id, submission_data, opts = {}) data, _status_code, _headers = generate_pdf_with_http_info(template_id, submission_data, opts) data end
[ "def", "generate_pdf", "(", "template_id", ",", "submission_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "generate_pdf_with_http_info", "(", "template_id", ",", "submission_data", ",", "opts", ")", "data", "end" ]
Generates a new PDF @param template_id @param submission_data @param [Hash] opts the optional parameters @return [CreateSubmissionResponse]
[ "Generates", "a", "new", "PDF" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L565-L568
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_data_request
def get_data_request(data_request_id, opts = {}) data, _status_code, _headers = get_data_request_with_http_info(data_request_id, opts) data end
ruby
def get_data_request(data_request_id, opts = {}) data, _status_code, _headers = get_data_request_with_http_info(data_request_id, opts) data end
[ "def", "get_data_request", "(", "data_request_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_data_request_with_http_info", "(", "data_request_id", ",", "opts", ")", "data", "end" ]
Look up a submission data request @param data_request_id @param [Hash] opts the optional parameters @return [SubmissionDataRequest]
[ "Look", "up", "a", "submission", "data", "request" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L674-L677
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_submission
def get_submission(submission_id, opts = {}) data, _status_code, _headers = get_submission_with_http_info(submission_id, opts) data end
ruby
def get_submission(submission_id, opts = {}) data, _status_code, _headers = get_submission_with_http_info(submission_id, opts) data end
[ "def", "get_submission", "(", "submission_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_submission_with_http_info", "(", "submission_id", ",", "opts", ")", "data", "end" ]
Check the status of a PDF @param submission_id @param [Hash] opts the optional parameters @option opts [BOOLEAN] :include_data @return [Submission]
[ "Check", "the", "status", "of", "a", "PDF" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L771-L774
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_submission_batch
def get_submission_batch(submission_batch_id, opts = {}) data, _status_code, _headers = get_submission_batch_with_http_info(submission_batch_id, opts) data end
ruby
def get_submission_batch(submission_batch_id, opts = {}) data, _status_code, _headers = get_submission_batch_with_http_info(submission_batch_id, opts) data end
[ "def", "get_submission_batch", "(", "submission_batch_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_submission_batch_with_http_info", "(", "submission_batch_id", ",", "opts", ")", "data", "end" ]
Check the status of a submission batch job @param submission_batch_id @param [Hash] opts the optional parameters @option opts [BOOLEAN] :include_submissions @return [SubmissionBatch]
[ "Check", "the", "status", "of", "a", "submission", "batch", "job" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L825-L828
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_template
def get_template(template_id, opts = {}) data, _status_code, _headers = get_template_with_http_info(template_id, opts) data end
ruby
def get_template(template_id, opts = {}) data, _status_code, _headers = get_template_with_http_info(template_id, opts) data end
[ "def", "get_template", "(", "template_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_template_with_http_info", "(", "template_id", ",", "opts", ")", "data", "end" ]
Check the status of an uploaded template @param template_id @param [Hash] opts the optional parameters @return [Template]
[ "Check", "the", "status", "of", "an", "uploaded", "template" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L878-L881
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_template_schema
def get_template_schema(template_id, opts = {}) data, _status_code, _headers = get_template_schema_with_http_info(template_id, opts) data end
ruby
def get_template_schema(template_id, opts = {}) data, _status_code, _headers = get_template_schema_with_http_info(template_id, opts) data end
[ "def", "get_template_schema", "(", "template_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_template_schema_with_http_info", "(", "template_id", ",", "opts", ")", "data", "end" ]
Fetch the JSON schema for a template @param template_id @param [Hash] opts the optional parameters @return [Hash<String, Object>]
[ "Fetch", "the", "JSON", "schema", "for", "a", "template" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L929-L932
train
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.update_data_request
def update_data_request(data_request_id, update_submission_data_request_data, opts = {}) data, _status_code, _headers = update_data_request_with_http_info(data_request_id, update_submission_data_request_data, opts) data end
ruby
def update_data_request(data_request_id, update_submission_data_request_data, opts = {}) data, _status_code, _headers = update_data_request_with_http_info(data_request_id, update_submission_data_request_data, opts) data end
[ "def", "update_data_request", "(", "data_request_id", ",", "update_submission_data_request_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_data_request_with_http_info", "(", "data_request_id", ",", "update_submission_data_request_data", ",", "opts", ")", "data", "end" ]
Update a submission data request @param data_request_id @param update_submission_data_request_data @param [Hash] opts the optional parameters @return [UpdateDataRequestResponse]
[ "Update", "a", "submission", "data", "request" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L1089-L1092
train
grzlus/acts_as_nested_interval
lib/acts_as_nested_interval/instance_methods.rb
ActsAsNestedInterval.InstanceMethods.next_root_lft
def next_root_lft last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots? last_root.try(:right) || 0.to_r end
ruby
def next_root_lft last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots? last_root.try(:right) || 0.to_r end
[ "def", "next_root_lft", "last_root", "=", "nested_interval_scope", ".", "roots", ".", "order", "(", "rgtp", ":", ":desc", ",", "rgtq", ":", ":desc", ")", ".", "first", "raise", "Exception", ".", "new", "(", "\"Only one root allowed\"", ")", "if", "last_root", ".", "present?", "&&", "!", "self", ".", "class", ".", "nested_interval", ".", "multiple_roots?", "last_root", ".", "try", "(", ":right", ")", "||", "0", ".", "to_r", "end" ]
Returns left end of interval for next root.
[ "Returns", "left", "end", "of", "interval", "for", "next", "root", "." ]
9a588bf515570e4a1e1311dc58dc5eea8bfffd8e
https://github.com/grzlus/acts_as_nested_interval/blob/9a588bf515570e4a1e1311dc58dc5eea8bfffd8e/lib/acts_as_nested_interval/instance_methods.rb#L39-L43
train
mudbugmedia/fusebox
lib/fusebox/request.rb
Fusebox.Request.report
def report (opts = {}) default_options = { :user => 'all', :group_subaccount => true, :report_type => 'basic' } opts.reverse_merge! default_options post 'report', opts, "report_#{opts[:report_type]}".to_sym end
ruby
def report (opts = {}) default_options = { :user => 'all', :group_subaccount => true, :report_type => 'basic' } opts.reverse_merge! default_options post 'report', opts, "report_#{opts[:report_type]}".to_sym end
[ "def", "report", "(", "opts", "=", "{", "}", ")", "default_options", "=", "{", ":user", "=>", "'all'", ",", ":group_subaccount", "=>", "true", ",", ":report_type", "=>", "'basic'", "}", "opts", ".", "reverse_merge!", "default_options", "post", "'report'", ",", "opts", ",", "\"report_#{opts[:report_type]}\"", ".", "to_sym", "end" ]
This request will provide information about one or more accounts under your platform in CSV format @see https://www.fusemail.com/support/api-documentation/requests#report report API documentation @param [Array] opts @option opts [String] :user ('all') The username you wish to query for information; you may also enter the username "all" to get information about all users under your platform @option opts [Boolean] :group_subaccount (true) Provide information not only for the Group Administration account but also for the group sub-accounts under the Group Administration account @option opts ['basic', 'extended'] :report_type ('basic') Level of detailed in returned results @return [Response]
[ "This", "request", "will", "provide", "information", "about", "one", "or", "more", "accounts", "under", "your", "platform", "in", "CSV", "format" ]
2c691495b180380552947ce67477b51c14676eee
https://github.com/mudbugmedia/fusebox/blob/2c691495b180380552947ce67477b51c14676eee/lib/fusebox/request.rb#L277-L286
train
mudbugmedia/fusebox
lib/fusebox/request.rb
Fusebox.Request.load_auth_from_yaml
def load_auth_from_yaml self.class.auth_yaml_paths.map { |path| File.expand_path(path) }.select { |path| File.exist?(path) }.each do |path| auth = YAML.load(File.read(path)) @username = auth['username'] @password = auth['password'] return if @username && @password end raise "Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}" end
ruby
def load_auth_from_yaml self.class.auth_yaml_paths.map { |path| File.expand_path(path) }.select { |path| File.exist?(path) }.each do |path| auth = YAML.load(File.read(path)) @username = auth['username'] @password = auth['password'] return if @username && @password end raise "Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}" end
[ "def", "load_auth_from_yaml", "self", ".", "class", ".", "auth_yaml_paths", ".", "map", "{", "|", "path", "|", "File", ".", "expand_path", "(", "path", ")", "}", ".", "select", "{", "|", "path", "|", "File", ".", "exist?", "(", "path", ")", "}", ".", "each", "do", "|", "path", "|", "auth", "=", "YAML", ".", "load", "(", "File", ".", "read", "(", "path", ")", ")", "@username", "=", "auth", "[", "'username'", "]", "@password", "=", "auth", "[", "'password'", "]", "return", "if", "@username", "&&", "@password", "end", "raise", "\"Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}\"", "end" ]
Load the platform authentication informaiton from a YAML file @see Request.auth_yaml_paths
[ "Load", "the", "platform", "authentication", "informaiton", "from", "a", "YAML", "file" ]
2c691495b180380552947ce67477b51c14676eee
https://github.com/mudbugmedia/fusebox/blob/2c691495b180380552947ce67477b51c14676eee/lib/fusebox/request.rb#L329-L338
train
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.download_manifest_only
def download_manifest_only FastlaneCore::UI.message('download_manifest_only...') rsa_key = load_rsa_key(rsa_keypath) success = true if !rsa_key.nil? FastlaneCore::UI.message('Logging in with RSA key for download...') Net::SSH.start(host, user, key_data: rsa_key, keys_only: true) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end else FastlaneCore::UI.message('Logging in for download...') Net::SSH.start(host, user, password: password) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end end success end
ruby
def download_manifest_only FastlaneCore::UI.message('download_manifest_only...') rsa_key = load_rsa_key(rsa_keypath) success = true if !rsa_key.nil? FastlaneCore::UI.message('Logging in with RSA key for download...') Net::SSH.start(host, user, key_data: rsa_key, keys_only: true) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end else FastlaneCore::UI.message('Logging in for download...') Net::SSH.start(host, user, password: password) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end end success end
[ "def", "download_manifest_only", "FastlaneCore", "::", "UI", ".", "message", "(", "'download_manifest_only...'", ")", "rsa_key", "=", "load_rsa_key", "(", "rsa_keypath", ")", "success", "=", "true", "if", "!", "rsa_key", ".", "nil?", "FastlaneCore", "::", "UI", ".", "message", "(", "'Logging in with RSA key for download...'", ")", "Net", "::", "SSH", ".", "start", "(", "host", ",", "user", ",", "key_data", ":", "rsa_key", ",", "keys_only", ":", "true", ")", "do", "|", "ssh", "|", "FastlaneCore", "::", "UI", ".", "message", "(", "'Uploading UPA & Manifest...'", ")", "success", "=", "ssh_sftp_download", "(", "ssh", ",", "manifest_path", ")", "end", "else", "FastlaneCore", "::", "UI", ".", "message", "(", "'Logging in for download...'", ")", "Net", "::", "SSH", ".", "start", "(", "host", ",", "user", ",", "password", ":", "password", ")", "do", "|", "ssh", "|", "FastlaneCore", "::", "UI", ".", "message", "(", "'Uploading UPA & Manifest...'", ")", "success", "=", "ssh_sftp_download", "(", "ssh", ",", "manifest_path", ")", "end", "end", "success", "end" ]
Download metadata only rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength
[ "Download", "metadata", "only" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L92-L110
train
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.check_ipa
def check_ipa(local_ipa_path) if File.exist?(local_ipa_path) FastlaneCore::UI.important('IPA found at ' + local_ipa_path) return true else FastlaneCore::UI.verbose('IPA at given path does not exist yet.') return false end end
ruby
def check_ipa(local_ipa_path) if File.exist?(local_ipa_path) FastlaneCore::UI.important('IPA found at ' + local_ipa_path) return true else FastlaneCore::UI.verbose('IPA at given path does not exist yet.') return false end end
[ "def", "check_ipa", "(", "local_ipa_path", ")", "if", "File", ".", "exist?", "(", "local_ipa_path", ")", "FastlaneCore", "::", "UI", ".", "important", "(", "'IPA found at '", "+", "local_ipa_path", ")", "return", "true", "else", "FastlaneCore", "::", "UI", ".", "verbose", "(", "'IPA at given path does not exist yet.'", ")", "return", "false", "end", "end" ]
Check IPA existence locally @param local_ipa_path
[ "Check", "IPA", "existence", "locally" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L147-L155
train
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.download_manifest
def download_manifest(sftp) FastlaneCore::UI.message('Checking remote Manifest') json = nil remote_manifest_path = remote_manifest_path(appcode) begin sftp.stat!(remote_manifest_path) do |response| if response.ok? FastlaneCore::UI.success('Loading remote manifest:') manifest = sftp.download!(remote_manifest_path) json = JSON.parse(manifest) end end rescue FastlaneCore::UI.message('No previous Manifest found') end json end
ruby
def download_manifest(sftp) FastlaneCore::UI.message('Checking remote Manifest') json = nil remote_manifest_path = remote_manifest_path(appcode) begin sftp.stat!(remote_manifest_path) do |response| if response.ok? FastlaneCore::UI.success('Loading remote manifest:') manifest = sftp.download!(remote_manifest_path) json = JSON.parse(manifest) end end rescue FastlaneCore::UI.message('No previous Manifest found') end json end
[ "def", "download_manifest", "(", "sftp", ")", "FastlaneCore", "::", "UI", ".", "message", "(", "'Checking remote Manifest'", ")", "json", "=", "nil", "remote_manifest_path", "=", "remote_manifest_path", "(", "appcode", ")", "begin", "sftp", ".", "stat!", "(", "remote_manifest_path", ")", "do", "|", "response", "|", "if", "response", ".", "ok?", "FastlaneCore", "::", "UI", ".", "success", "(", "'Loading remote manifest:'", ")", "manifest", "=", "sftp", ".", "download!", "(", "remote_manifest_path", ")", "json", "=", "JSON", ".", "parse", "(", "manifest", ")", "end", "end", "rescue", "FastlaneCore", "::", "UI", ".", "message", "(", "'No previous Manifest found'", ")", "end", "json", "end" ]
Downloads remote manifest, self.appcode required by options. @param sftp @param [String] remote_path @returns [JSON] json or nil
[ "Downloads", "remote", "manifest", "self", ".", "appcode", "required", "by", "options", "." ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L201-L217
train
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.upload_ipa
def upload_ipa(sftp, local_ipa_path, remote_ipa_path) msg = "[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}" FastlaneCore::UI.message(msg) result = sftp.upload!(local_ipa_path, remote_ipa_path) do |event, _uploader, *_args| case event when :open then putc '.' when :put then putc '.' $stdout.flush when :close then puts "\n" when :finish then FastlaneCore::UI.success('IPA upload successful') end end end
ruby
def upload_ipa(sftp, local_ipa_path, remote_ipa_path) msg = "[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}" FastlaneCore::UI.message(msg) result = sftp.upload!(local_ipa_path, remote_ipa_path) do |event, _uploader, *_args| case event when :open then putc '.' when :put then putc '.' $stdout.flush when :close then puts "\n" when :finish then FastlaneCore::UI.success('IPA upload successful') end end end
[ "def", "upload_ipa", "(", "sftp", ",", "local_ipa_path", ",", "remote_ipa_path", ")", "msg", "=", "\"[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}\"", "FastlaneCore", "::", "UI", ".", "message", "(", "msg", ")", "result", "=", "sftp", ".", "upload!", "(", "local_ipa_path", ",", "remote_ipa_path", ")", "do", "|", "event", ",", "_uploader", ",", "*", "_args", "|", "case", "event", "when", ":open", "then", "putc", "'.'", "when", ":put", "then", "putc", "'.'", "$stdout", ".", "flush", "when", ":close", "then", "puts", "\"\\n\"", "when", ":finish", "then", "FastlaneCore", "::", "UI", ".", "success", "(", "'IPA upload successful'", ")", "end", "end", "end" ]
Upload current IPA @param sftp @param [String] local_ipa_path @param [String] remote_ipa_path
[ "Upload", "current", "IPA" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L224-L240
train
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.upload_manifest
def upload_manifest(sftp, local_path, remote_path) msg = '[Uploading Manifest] ' + local_path + ' to ' + remote_path FastlaneCore::UI.message(msg) result = sftp.upload!(local_path, remote_path) do |event, _uploader, *_args| case event when :finish then FastlaneCore::UI.success('Manifest upload successful') end end end
ruby
def upload_manifest(sftp, local_path, remote_path) msg = '[Uploading Manifest] ' + local_path + ' to ' + remote_path FastlaneCore::UI.message(msg) result = sftp.upload!(local_path, remote_path) do |event, _uploader, *_args| case event when :finish then FastlaneCore::UI.success('Manifest upload successful') end end end
[ "def", "upload_manifest", "(", "sftp", ",", "local_path", ",", "remote_path", ")", "msg", "=", "'[Uploading Manifest] '", "+", "local_path", "+", "' to '", "+", "remote_path", "FastlaneCore", "::", "UI", ".", "message", "(", "msg", ")", "result", "=", "sftp", ".", "upload!", "(", "local_path", ",", "remote_path", ")", "do", "|", "event", ",", "_uploader", ",", "*", "_args", "|", "case", "event", "when", ":finish", "then", "FastlaneCore", "::", "UI", ".", "success", "(", "'Manifest upload successful'", ")", "end", "end", "end" ]
Upload current manifest.json @param sftp @param [String] manifest_path @param [String] remote_manifest_path
[ "Upload", "current", "manifest", ".", "json" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L247-L256
train
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.load_rsa_key
def load_rsa_key(rsa_keypath) File.open(rsa_keypath, 'r') do |file| rsa_key = nil rsa_key = [file.read] if !rsa_key.nil? FastlaneCore::UI.success('Successfully loaded RSA key...') else FastlaneCore::UI.user_error!('Failed to load RSA key...') end rsa_key end end
ruby
def load_rsa_key(rsa_keypath) File.open(rsa_keypath, 'r') do |file| rsa_key = nil rsa_key = [file.read] if !rsa_key.nil? FastlaneCore::UI.success('Successfully loaded RSA key...') else FastlaneCore::UI.user_error!('Failed to load RSA key...') end rsa_key end end
[ "def", "load_rsa_key", "(", "rsa_keypath", ")", "File", ".", "open", "(", "rsa_keypath", ",", "'r'", ")", "do", "|", "file", "|", "rsa_key", "=", "nil", "rsa_key", "=", "[", "file", ".", "read", "]", "if", "!", "rsa_key", ".", "nil?", "FastlaneCore", "::", "UI", ".", "success", "(", "'Successfully loaded RSA key...'", ")", "else", "FastlaneCore", "::", "UI", ".", "user_error!", "(", "'Failed to load RSA key...'", ")", "end", "rsa_key", "end", "end" ]
Private methods - Local Operations
[ "Private", "methods", "-", "Local", "Operations" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L284-L295
train
ivanzotov/constructor
pages/app/models/constructor_pages/field.rb
ConstructorPages.Field.check_code_name
def check_code_name(code_name) [code_name.pluralize, code_name.singularize].each {|name| %w{self_and_ancestors descendants}.each {|m| return false if template.send(m).map(&:code_name).include?(name)}} true end
ruby
def check_code_name(code_name) [code_name.pluralize, code_name.singularize].each {|name| %w{self_and_ancestors descendants}.each {|m| return false if template.send(m).map(&:code_name).include?(name)}} true end
[ "def", "check_code_name", "(", "code_name", ")", "[", "code_name", ".", "pluralize", ",", "code_name", ".", "singularize", "]", ".", "each", "{", "|", "name", "|", "%w{", "self_and_ancestors", "descendants", "}", ".", "each", "{", "|", "m", "|", "return", "false", "if", "template", ".", "send", "(", "m", ")", ".", "map", "(", "&", ":code_name", ")", ".", "include?", "(", "name", ")", "}", "}", "true", "end" ]
Check if there is code_name in template branch
[ "Check", "if", "there", "is", "code_name", "in", "template", "branch" ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/field.rb#L52-L57
train
fulldecent/structured-acceptance-test
implementations/ruby/lib/location.rb
StatModule.Location.print
def print result = "in #{path}" if !begin_line.nil? && !end_line.nil? if begin_line != end_line if !begin_column.nil? && !end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}" elsif !begin_column.nil? && end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}" elsif begin_column.nil? && !end_column.nil? result += ", line #{begin_line} to line #{end_line}:#{end_column}" else result += ", lines #{begin_line}-#{end_line}" end else if begin_column.nil? result += ", line #{begin_line}" else result += ", line #{begin_line}:#{begin_column}" result += "-#{end_column}" unless end_column.nil? end end end result end
ruby
def print result = "in #{path}" if !begin_line.nil? && !end_line.nil? if begin_line != end_line if !begin_column.nil? && !end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}" elsif !begin_column.nil? && end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}" elsif begin_column.nil? && !end_column.nil? result += ", line #{begin_line} to line #{end_line}:#{end_column}" else result += ", lines #{begin_line}-#{end_line}" end else if begin_column.nil? result += ", line #{begin_line}" else result += ", line #{begin_line}:#{begin_column}" result += "-#{end_column}" unless end_column.nil? end end end result end
[ "def", "print", "result", "=", "\"in #{path}\"", "if", "!", "begin_line", ".", "nil?", "&&", "!", "end_line", ".", "nil?", "if", "begin_line", "!=", "end_line", "if", "!", "begin_column", ".", "nil?", "&&", "!", "end_column", ".", "nil?", "result", "+=", "\", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}\"", "elsif", "!", "begin_column", ".", "nil?", "&&", "end_column", ".", "nil?", "result", "+=", "\", line #{begin_line}:#{begin_column} to line #{end_line}\"", "elsif", "begin_column", ".", "nil?", "&&", "!", "end_column", ".", "nil?", "result", "+=", "\", line #{begin_line} to line #{end_line}:#{end_column}\"", "else", "result", "+=", "\", lines #{begin_line}-#{end_line}\"", "end", "else", "if", "begin_column", ".", "nil?", "result", "+=", "\", line #{begin_line}\"", "else", "result", "+=", "\", line #{begin_line}:#{begin_column}\"", "result", "+=", "\"-#{end_column}\"", "unless", "end_column", ".", "nil?", "end", "end", "end", "result", "end" ]
Get formatted information about location
[ "Get", "formatted", "information", "about", "location" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/location.rb#L103-L126
train
dennmart/wanikani-gem
lib/wanikani/level.rb
Wanikani.Level.level_items_list
def level_items_list(type, levels) levels = levels.join(',') if levels.is_a?(Array) response = api_response(type, levels) # The vocabulary API call without specifying levels returns a Hash instead # of an Array, so this is a hacky way of dealing with it. if response["requested_information"].is_a?(Hash) return response["requested_information"]["general"] else return response["requested_information"] end end
ruby
def level_items_list(type, levels) levels = levels.join(',') if levels.is_a?(Array) response = api_response(type, levels) # The vocabulary API call without specifying levels returns a Hash instead # of an Array, so this is a hacky way of dealing with it. if response["requested_information"].is_a?(Hash) return response["requested_information"]["general"] else return response["requested_information"] end end
[ "def", "level_items_list", "(", "type", ",", "levels", ")", "levels", "=", "levels", ".", "join", "(", "','", ")", "if", "levels", ".", "is_a?", "(", "Array", ")", "response", "=", "api_response", "(", "type", ",", "levels", ")", "if", "response", "[", "\"requested_information\"", "]", ".", "is_a?", "(", "Hash", ")", "return", "response", "[", "\"requested_information\"", "]", "[", "\"general\"", "]", "else", "return", "response", "[", "\"requested_information\"", "]", "end", "end" ]
Fetches the specified item type list from WaniKani's API @param type [String] The type of item to fetch. @param levels [Integer, Array<Integer>] a specific level or array of levels to fetch items for. @return [Hash] list of items of the specified type and levels.
[ "Fetches", "the", "specified", "item", "type", "list", "from", "WaniKani", "s", "API" ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/level.rb#L55-L66
train
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.check_expired_resources
def check_expired_resources net_resources = ::NetResource.expired net_resources.each do |resource| http = EM::HttpRequest.new(resource.url).get http.callback{ |response| resource.set_next_update if resource_changed?(resource, response) resource.body = response.response update_changed_resource(resource, response) notify_subscribers(resource) end } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
ruby
def check_expired_resources net_resources = ::NetResource.expired net_resources.each do |resource| http = EM::HttpRequest.new(resource.url).get http.callback{ |response| resource.set_next_update if resource_changed?(resource, response) resource.body = response.response update_changed_resource(resource, response) notify_subscribers(resource) end } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
[ "def", "check_expired_resources", "net_resources", "=", "::", "NetResource", ".", "expired", "net_resources", ".", "each", "do", "|", "resource", "|", "http", "=", "EM", "::", "HttpRequest", ".", "new", "(", "resource", ".", "url", ")", ".", "get", "http", ".", "callback", "{", "|", "response", "|", "resource", ".", "set_next_update", "if", "resource_changed?", "(", "resource", ",", "response", ")", "resource", ".", "body", "=", "response", ".", "response", "update_changed_resource", "(", "resource", ",", "response", ")", "notify_subscribers", "(", "resource", ")", "end", "}", "http", ".", "errback", "{", "|", "response", "|", "}", "end", "end" ]
Adds a periodic timer to the Eventmachine reactor loop and immediately starts grabbing expired resources and checking them. Gets all of the expired NetResources from the database and sends an HTTP GET requests for each one. Subscribers to a NetResource will be notified if it has changed since the last time it was grabbed.
[ "Adds", "a", "periodic", "timer", "to", "the", "Eventmachine", "reactor", "loop", "and", "immediately", "starts", "grabbing", "expired", "resources", "and", "checking", "them", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L20-L38
train
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.notify_subscribers
def notify_subscribers(resource) resource.subscriptions.each do |subscription| http = EM::HttpRequest.new(subscription.url).post(:body => {:data => resource.body}) http.callback{ |response| puts "POSTed updated data for #{resource.url}, #{resource.body.length} characters" } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
ruby
def notify_subscribers(resource) resource.subscriptions.each do |subscription| http = EM::HttpRequest.new(subscription.url).post(:body => {:data => resource.body}) http.callback{ |response| puts "POSTed updated data for #{resource.url}, #{resource.body.length} characters" } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
[ "def", "notify_subscribers", "(", "resource", ")", "resource", ".", "subscriptions", ".", "each", "do", "|", "subscription", "|", "http", "=", "EM", "::", "HttpRequest", ".", "new", "(", "subscription", ".", "url", ")", ".", "post", "(", ":body", "=>", "{", ":data", "=>", "resource", ".", "body", "}", ")", "http", ".", "callback", "{", "|", "response", "|", "puts", "\"POSTed updated data for #{resource.url}, #{resource.body.length} characters\"", "}", "http", ".", "errback", "{", "|", "response", "|", "}", "end", "end" ]
Notifies each of a NetResource's subscribers that the resource has changed by doing an HTTP POST request to the subscriber's callback url. The POST body contains a key called "data" which contains the feed value.
[ "Notifies", "each", "of", "a", "NetResource", "s", "subscribers", "that", "the", "resource", "has", "changed", "by", "doing", "an", "HTTP", "POST", "request", "to", "the", "subscriber", "s", "callback", "url", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L45-L56
train
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.resource_changed?
def resource_changed?(resource, response) changed = false puts "checking for changes on #{resource.url}" puts "response.response.hash: #{response.response.hash}" puts "resource.last_modified_hash: #{resource.last_modified_hash}" if response.response.hash != resource.last_modified_hash puts "changed!!!!\n\n\n\n" changed = true end end
ruby
def resource_changed?(resource, response) changed = false puts "checking for changes on #{resource.url}" puts "response.response.hash: #{response.response.hash}" puts "resource.last_modified_hash: #{resource.last_modified_hash}" if response.response.hash != resource.last_modified_hash puts "changed!!!!\n\n\n\n" changed = true end end
[ "def", "resource_changed?", "(", "resource", ",", "response", ")", "changed", "=", "false", "puts", "\"checking for changes on #{resource.url}\"", "puts", "\"response.response.hash: #{response.response.hash}\"", "puts", "\"resource.last_modified_hash: #{resource.last_modified_hash}\"", "if", "response", ".", "response", ".", "hash", "!=", "resource", ".", "last_modified_hash", "puts", "\"changed!!!!\\n\\n\\n\\n\"", "changed", "=", "true", "end", "end" ]
Determines whether a resource has changed by comparing its saved hash value with the hash value of the response content.
[ "Determines", "whether", "a", "resource", "has", "changed", "by", "comparing", "its", "saved", "hash", "value", "with", "the", "hash", "value", "of", "the", "response", "content", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L61-L70
train
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.update_changed_resource
def update_changed_resource(resource, response) resource.last_modified_hash = response.response.hash resource.last_updated = Time.now resource.body = response.response resource.save end
ruby
def update_changed_resource(resource, response) resource.last_modified_hash = response.response.hash resource.last_updated = Time.now resource.body = response.response resource.save end
[ "def", "update_changed_resource", "(", "resource", ",", "response", ")", "resource", ".", "last_modified_hash", "=", "response", ".", "response", ".", "hash", "resource", ".", "last_updated", "=", "Time", ".", "now", "resource", ".", "body", "=", "response", ".", "response", "resource", ".", "save", "end" ]
Updates the resource's fields when the resource has changed. The last_modified_hash is set to the hash value of the response body, the response body itself is saved so that it can be sent to consumers during notifications, and the resource's last_updated time is set to the current time.
[ "Updates", "the", "resource", "s", "fields", "when", "the", "resource", "has", "changed", ".", "The", "last_modified_hash", "is", "set", "to", "the", "hash", "value", "of", "the", "response", "body", "the", "response", "body", "itself", "is", "saved", "so", "that", "it", "can", "be", "sent", "to", "consumers", "during", "notifications", "and", "the", "resource", "s", "last_updated", "time", "is", "set", "to", "the", "current", "time", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L78-L83
train
Falkor/falkorlib
lib/falkorlib/config.rb
FalkorLib.Config.default
def default res = FalkorLib::Config::DEFAULTS.clone $LOADED_FEATURES.each do |path| res[:git] = FalkorLib::Config::Git::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:gitflow] = FalkorLib::Config::GitFlow::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:versioning] = FalkorLib::Config::Versioning::DEFAULTS if path.include?('lib/falkorlib/versioning.rb') if path.include?('lib/falkorlib/puppet.rb') res[:puppet] = FalkorLib::Config::Puppet::DEFAULTS res[:templates][:puppet][:modules] = FalkorLib::Config::Puppet::Modules::DEFAULTS[:metadata] end end # Check the potential local customizations [:local, :private].each do |type| custom_cfg = File.join( res[:root], res[:config_files][type.to_sym]) if File.exist?( custom_cfg ) res.deep_merge!( load_config( custom_cfg ) ) end end res end
ruby
def default res = FalkorLib::Config::DEFAULTS.clone $LOADED_FEATURES.each do |path| res[:git] = FalkorLib::Config::Git::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:gitflow] = FalkorLib::Config::GitFlow::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:versioning] = FalkorLib::Config::Versioning::DEFAULTS if path.include?('lib/falkorlib/versioning.rb') if path.include?('lib/falkorlib/puppet.rb') res[:puppet] = FalkorLib::Config::Puppet::DEFAULTS res[:templates][:puppet][:modules] = FalkorLib::Config::Puppet::Modules::DEFAULTS[:metadata] end end # Check the potential local customizations [:local, :private].each do |type| custom_cfg = File.join( res[:root], res[:config_files][type.to_sym]) if File.exist?( custom_cfg ) res.deep_merge!( load_config( custom_cfg ) ) end end res end
[ "def", "default", "res", "=", "FalkorLib", "::", "Config", "::", "DEFAULTS", ".", "clone", "$LOADED_FEATURES", ".", "each", "do", "|", "path", "|", "res", "[", ":git", "]", "=", "FalkorLib", "::", "Config", "::", "Git", "::", "DEFAULTS", "if", "path", ".", "include?", "(", "'lib/falkorlib/git.rb'", ")", "res", "[", ":gitflow", "]", "=", "FalkorLib", "::", "Config", "::", "GitFlow", "::", "DEFAULTS", "if", "path", ".", "include?", "(", "'lib/falkorlib/git.rb'", ")", "res", "[", ":versioning", "]", "=", "FalkorLib", "::", "Config", "::", "Versioning", "::", "DEFAULTS", "if", "path", ".", "include?", "(", "'lib/falkorlib/versioning.rb'", ")", "if", "path", ".", "include?", "(", "'lib/falkorlib/puppet.rb'", ")", "res", "[", ":puppet", "]", "=", "FalkorLib", "::", "Config", "::", "Puppet", "::", "DEFAULTS", "res", "[", ":templates", "]", "[", ":puppet", "]", "[", ":modules", "]", "=", "FalkorLib", "::", "Config", "::", "Puppet", "::", "Modules", "::", "DEFAULTS", "[", ":metadata", "]", "end", "end", "[", ":local", ",", ":private", "]", ".", "each", "do", "|", "type", "|", "custom_cfg", "=", "File", ".", "join", "(", "res", "[", ":root", "]", ",", "res", "[", ":config_files", "]", "[", "type", ".", "to_sym", "]", ")", "if", "File", ".", "exist?", "(", "custom_cfg", ")", "res", ".", "deep_merge!", "(", "load_config", "(", "custom_cfg", ")", ")", "end", "end", "res", "end" ]
Build the default configuration hash, to be used to initiate the default. The hash is built depending on the loaded files.
[ "Build", "the", "default", "configuration", "hash", "to", "be", "used", "to", "initiate", "the", "default", ".", "The", "hash", "is", "built", "depending", "on", "the", "loaded", "files", "." ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/config.rb#L83-L102
train
Falkor/falkorlib
lib/falkorlib/config.rb
FalkorLib.Config.config_file
def config_file(dir = Dir.pwd, type = :local, options = {}) path = normalized_path(dir) path = FalkorLib::Git.rootdir(path) if FalkorLib::Git.init?(path) raise FalkorLib::Error, "Wrong FalkorLib configuration type" unless FalkorLib.config[:config_files].keys.include?( type.to_sym) (options[:file]) ? options[:file] : File.join(path, FalkorLib.config[:config_files][type.to_sym]) end
ruby
def config_file(dir = Dir.pwd, type = :local, options = {}) path = normalized_path(dir) path = FalkorLib::Git.rootdir(path) if FalkorLib::Git.init?(path) raise FalkorLib::Error, "Wrong FalkorLib configuration type" unless FalkorLib.config[:config_files].keys.include?( type.to_sym) (options[:file]) ? options[:file] : File.join(path, FalkorLib.config[:config_files][type.to_sym]) end
[ "def", "config_file", "(", "dir", "=", "Dir", ".", "pwd", ",", "type", "=", ":local", ",", "options", "=", "{", "}", ")", "path", "=", "normalized_path", "(", "dir", ")", "path", "=", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", "if", "FalkorLib", "::", "Git", ".", "init?", "(", "path", ")", "raise", "FalkorLib", "::", "Error", ",", "\"Wrong FalkorLib configuration type\"", "unless", "FalkorLib", ".", "config", "[", ":config_files", "]", ".", "keys", ".", "include?", "(", "type", ".", "to_sym", ")", "(", "options", "[", ":file", "]", ")", "?", "options", "[", ":file", "]", ":", "File", ".", "join", "(", "path", ",", "FalkorLib", ".", "config", "[", ":config_files", "]", "[", "type", ".", "to_sym", "]", ")", "end" ]
get get_or_save wrapper for get and save operations
[ "get", "get_or_save", "wrapper", "for", "get", "and", "save", "operations" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/config.rb#L119-L124
train
ktemkin/ruby-ise
lib/ise/project_navigator.rb
ISE.ProjectNavigator.most_recent_project_path
def most_recent_project_path #Re-load the preference file, so we have the most recent project. @preferences = PreferenceFile.load #And retrieve the first project in the recent projects list. project = preference(RecentProjectsPath).split(', ').first #If the project exists, return it; otherwise, return nil. File::exists?(project) ? project : nil end
ruby
def most_recent_project_path #Re-load the preference file, so we have the most recent project. @preferences = PreferenceFile.load #And retrieve the first project in the recent projects list. project = preference(RecentProjectsPath).split(', ').first #If the project exists, return it; otherwise, return nil. File::exists?(project) ? project : nil end
[ "def", "most_recent_project_path", "@preferences", "=", "PreferenceFile", ".", "load", "project", "=", "preference", "(", "RecentProjectsPath", ")", ".", "split", "(", "', '", ")", ".", "first", "File", "::", "exists?", "(", "project", ")", "?", "project", ":", "nil", "end" ]
Returns most recently open project. If Project Navigator has a project open, that project will be used. This function re-loads the preferences file upon each call, to ensure we don't have stale data. TODO: When more than one ISE version is loaded, parse _all_ of the recent projects, and then return the project with the latest timestamp.
[ "Returns", "most", "recently", "open", "project", ".", "If", "Project", "Navigator", "has", "a", "project", "open", "that", "project", "will", "be", "used", ".", "This", "function", "re", "-", "loads", "the", "preferences", "file", "upon", "each", "call", "to", "ensure", "we", "don", "t", "have", "stale", "data", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project_navigator.rb#L62-L73
train
bachya/cliutils
lib/cliutils/configurator.rb
CLIUtils.Configurator.ingest_prefs
def ingest_prefs(prefs) fail 'Invaid Prefs class' unless prefs.kind_of?(Prefs) prefs.prompts.each do |p| section_sym = p.config_section.to_sym add_section(section_sym) unless @data.key?(section_sym) @data[section_sym].merge!(p.config_key.to_sym => p.answer) end end
ruby
def ingest_prefs(prefs) fail 'Invaid Prefs class' unless prefs.kind_of?(Prefs) prefs.prompts.each do |p| section_sym = p.config_section.to_sym add_section(section_sym) unless @data.key?(section_sym) @data[section_sym].merge!(p.config_key.to_sym => p.answer) end end
[ "def", "ingest_prefs", "(", "prefs", ")", "fail", "'Invaid Prefs class'", "unless", "prefs", ".", "kind_of?", "(", "Prefs", ")", "prefs", ".", "prompts", ".", "each", "do", "|", "p", "|", "section_sym", "=", "p", ".", "config_section", ".", "to_sym", "add_section", "(", "section_sym", ")", "unless", "@data", ".", "key?", "(", "section_sym", ")", "@data", "[", "section_sym", "]", ".", "merge!", "(", "p", ".", "config_key", ".", "to_sym", "=>", "p", ".", "answer", ")", "end", "end" ]
Ingests a Prefs class and adds its answers to the configuration data. @param [Prefs] prefs The Prefs class to examine @return [void]
[ "Ingests", "a", "Prefs", "class", "and", "adds", "its", "answers", "to", "the", "configuration", "data", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/configurator.rb#L101-L108
train
bachya/cliutils
lib/cliutils/configurator.rb
CLIUtils.Configurator.method_missing
def method_missing(name, *args, &block) if name[-1,1] == '=' @data[name[0..-2].to_sym] = args[0] else @data[name.to_sym] ||= {} end end
ruby
def method_missing(name, *args, &block) if name[-1,1] == '=' @data[name[0..-2].to_sym] = args[0] else @data[name.to_sym] ||= {} end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "name", "[", "-", "1", ",", "1", "]", "==", "'='", "@data", "[", "name", "[", "0", "..", "-", "2", "]", ".", "to_sym", "]", "=", "args", "[", "0", "]", "else", "@data", "[", "name", ".", "to_sym", "]", "||=", "{", "}", "end", "end" ]
Hook that fires when a non-existent method is called. Allows this module to return data from the config Hash when given a method name that matches a key. @param [<String, Symbol>] name The name of the method @param [Array] args The arguments @yield if a block is passed @return [Hash] The hash with the method's name as key
[ "Hook", "that", "fires", "when", "a", "non", "-", "existent", "method", "is", "called", ".", "Allows", "this", "module", "to", "return", "data", "from", "the", "config", "Hash", "when", "given", "a", "method", "name", "that", "matches", "a", "key", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/configurator.rb#L117-L123
train
eprothro/cassie
lib/cassie/schema/version_loader.rb
Cassie::Schema.VersionLoader.load
def load return false unless filename require filename begin # ensure the migration class is now defined version.migration_class_name.constantize if version.migration.is_a?(Cassie::Schema::Migration) version else false end rescue NameError raise NameError.new("Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.") end end
ruby
def load return false unless filename require filename begin # ensure the migration class is now defined version.migration_class_name.constantize if version.migration.is_a?(Cassie::Schema::Migration) version else false end rescue NameError raise NameError.new("Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.") end end
[ "def", "load", "return", "false", "unless", "filename", "require", "filename", "begin", "version", ".", "migration_class_name", ".", "constantize", "if", "version", ".", "migration", ".", "is_a?", "(", "Cassie", "::", "Schema", "::", "Migration", ")", "version", "else", "false", "end", "rescue", "NameError", "raise", "NameError", ".", "new", "(", "\"Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.\"", ")", "end", "end" ]
Requires the ruby file, thus loading the Migration class into the ObjectSpace. @return [Version, Boolean] The Version object if successful. In other words, if object representing the version returns a Cassie::Schema::Migration object. Otherwise returns false. @raise [NameError] if the migration class could not be loaded
[ "Requires", "the", "ruby", "file", "thus", "loading", "the", "Migration", "class", "into", "the", "ObjectSpace", "." ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/version_loader.rb#L14-L29
train
govdelivery/govdelivery-tms-ruby
lib/govdelivery/tms/instance_resource.rb
GovDelivery::TMS::InstanceResource.ClassMethods.nullable_attributes
def nullable_attributes(*attrs) @nullable_attributes ||= [] if attrs.any? @nullable_attributes.map!(&:to_sym).concat(attrs).uniq! if attrs.any? end @nullable_attributes end
ruby
def nullable_attributes(*attrs) @nullable_attributes ||= [] if attrs.any? @nullable_attributes.map!(&:to_sym).concat(attrs).uniq! if attrs.any? end @nullable_attributes end
[ "def", "nullable_attributes", "(", "*", "attrs", ")", "@nullable_attributes", "||=", "[", "]", "if", "attrs", ".", "any?", "@nullable_attributes", ".", "map!", "(", "&", ":to_sym", ")", ".", "concat", "(", "attrs", ")", ".", "uniq!", "if", "attrs", ".", "any?", "end", "@nullable_attributes", "end" ]
Nullable attributes are sent as null in the request
[ "Nullable", "attributes", "are", "sent", "as", "null", "in", "the", "request" ]
073d6a451222cda3cddf29b6ac246af353f82335
https://github.com/govdelivery/govdelivery-tms-ruby/blob/073d6a451222cda3cddf29b6ac246af353f82335/lib/govdelivery/tms/instance_resource.rb#L50-L56
train
flori/bullshit
lib/bullshit.rb
Bullshit.ModuleFunctions.array_window
def array_window(array, window_size) window_size < 1 and raise ArgumentError, "window_size = #{window_size} < 1" window_size = window_size.to_i window_size += 1 if window_size % 2 == 0 radius = window_size / 2 array.each_index do |i| ws = window_size from = i - radius negative_from = false if from < 0 negative_from = true ws += from from = 0 end a = array[from, ws] if (diff = window_size - a.size) > 0 mean = a.inject(0.0) { |s, x| s + x } / a.size a = if negative_from [ mean ] * diff + a else a + [ mean ] * diff end end yield a end nil end
ruby
def array_window(array, window_size) window_size < 1 and raise ArgumentError, "window_size = #{window_size} < 1" window_size = window_size.to_i window_size += 1 if window_size % 2 == 0 radius = window_size / 2 array.each_index do |i| ws = window_size from = i - radius negative_from = false if from < 0 negative_from = true ws += from from = 0 end a = array[from, ws] if (diff = window_size - a.size) > 0 mean = a.inject(0.0) { |s, x| s + x } / a.size a = if negative_from [ mean ] * diff + a else a + [ mean ] * diff end end yield a end nil end
[ "def", "array_window", "(", "array", ",", "window_size", ")", "window_size", "<", "1", "and", "raise", "ArgumentError", ",", "\"window_size = #{window_size} < 1\"", "window_size", "=", "window_size", ".", "to_i", "window_size", "+=", "1", "if", "window_size", "%", "2", "==", "0", "radius", "=", "window_size", "/", "2", "array", ".", "each_index", "do", "|", "i", "|", "ws", "=", "window_size", "from", "=", "i", "-", "radius", "negative_from", "=", "false", "if", "from", "<", "0", "negative_from", "=", "true", "ws", "+=", "from", "from", "=", "0", "end", "a", "=", "array", "[", "from", ",", "ws", "]", "if", "(", "diff", "=", "window_size", "-", "a", ".", "size", ")", ">", "0", "mean", "=", "a", ".", "inject", "(", "0.0", ")", "{", "|", "s", ",", "x", "|", "s", "+", "x", "}", "/", "a", ".", "size", "a", "=", "if", "negative_from", "[", "mean", "]", "*", "diff", "+", "a", "else", "a", "+", "[", "mean", "]", "*", "diff", "end", "end", "yield", "a", "end", "nil", "end" ]
Let a window of size +window_size+ slide over the array +array+ and yield to the window array.
[ "Let", "a", "window", "of", "size", "+", "window_size", "+", "slide", "over", "the", "array", "+", "array", "+", "and", "yield", "to", "the", "window", "array", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L33-L59
train
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.<<
def <<(times) r = times.shift @repeat += 1 if @times[:repeat].last != r @times[:repeat] << r TIMES.zip(times) { |t, time| @times[t] << time.to_f } self end
ruby
def <<(times) r = times.shift @repeat += 1 if @times[:repeat].last != r @times[:repeat] << r TIMES.zip(times) { |t, time| @times[t] << time.to_f } self end
[ "def", "<<", "(", "times", ")", "r", "=", "times", ".", "shift", "@repeat", "+=", "1", "if", "@times", "[", ":repeat", "]", ".", "last", "!=", "r", "@times", "[", ":repeat", "]", "<<", "r", "TIMES", ".", "zip", "(", "times", ")", "{", "|", "t", ",", "time", "|", "@times", "[", "t", "]", "<<", "time", ".", "to_f", "}", "self", "end" ]
Add the array +times+ to this clock's time measurements. +times+ consists of the time measurements in float values in order of TIMES.
[ "Add", "the", "array", "+", "times", "+", "to", "this", "clock", "s", "time", "measurements", ".", "+", "times", "+", "consists", "of", "the", "time", "measurements", "in", "float", "values", "in", "order", "of", "TIMES", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L172-L178
train