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
ideonetwork/lato-core
lib/lato_core/interfaces/apihelpers.rb
LatoCore.Interface::Apihelpers.core__send_request_success
def core__send_request_success(payload) response = { result: true, error_message: nil } response[:payload] = payload if payload render json: response end
ruby
def core__send_request_success(payload) response = { result: true, error_message: nil } response[:payload] = payload if payload render json: response end
[ "def", "core__send_request_success", "(", "payload", ")", "response", "=", "{", "result", ":", "true", ",", "error_message", ":", "nil", "}", "response", "[", ":payload", "]", "=", "payload", "if", "payload", "render", "json", ":", "response", "end" ]
This function render a normal success response with a custom payload.
[ "This", "function", "render", "a", "normal", "success", "response", "with", "a", "custom", "payload", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/apihelpers.rb#L8-L12
train
ideonetwork/lato-core
lib/lato_core/interfaces/apihelpers.rb
LatoCore.Interface::Apihelpers.core__send_request_fail
def core__send_request_fail(error, payload: nil) response = { result: false, error_message: error } response[:payload] = payload if payload render json: response end
ruby
def core__send_request_fail(error, payload: nil) response = { result: false, error_message: error } response[:payload] = payload if payload render json: response end
[ "def", "core__send_request_fail", "(", "error", ",", "payload", ":", "nil", ")", "response", "=", "{", "result", ":", "false", ",", "error_message", ":", "error", "}", "response", "[", ":payload", "]", "=", "payload", "if", "payload", "render", "json", ":", "response", "end" ]
This function render an error message with a possible custom payload.
[ "This", "function", "render", "an", "error", "message", "with", "a", "possible", "custom", "payload", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/apihelpers.rb#L15-L19
train
evgenyneu/siba
lib/siba/siba_file.rb
Siba.SibaFile.shell_ok?
def shell_ok?(command) # Using Open3 instead of `` or system("cmd") in order to hide stderr output sout, status = Open3.capture2e command return status.to_i == 0 rescue return false end
ruby
def shell_ok?(command) # Using Open3 instead of `` or system("cmd") in order to hide stderr output sout, status = Open3.capture2e command return status.to_i == 0 rescue return false end
[ "def", "shell_ok?", "(", "command", ")", "sout", ",", "status", "=", "Open3", ".", "capture2e", "command", "return", "status", ".", "to_i", "==", "0", "rescue", "return", "false", "end" ]
Runs the shell command. Works the same way as Kernel.system method but without showing the output. Returns true if it was successfull.
[ "Runs", "the", "shell", "command", ".", "Works", "the", "same", "way", "as", "Kernel", ".", "system", "method", "but", "without", "showing", "the", "output", ".", "Returns", "true", "if", "it", "was", "successfull", "." ]
04cd0eca8222092c14ce4a662b48f5f113ffe6df
https://github.com/evgenyneu/siba/blob/04cd0eca8222092c14ce4a662b48f5f113ffe6df/lib/siba/siba_file.rb#L65-L71
train
reggieb/Disclaimer
app/models/disclaimer/document.rb
Disclaimer.Document.modify_via_segment_holder_acts_as_list_method
def modify_via_segment_holder_acts_as_list_method(method, segment) segment_holder = segment_holder_for(segment) raise segment_not_associated_message(method, segment) unless segment_holder segment_holder.send(method) end
ruby
def modify_via_segment_holder_acts_as_list_method(method, segment) segment_holder = segment_holder_for(segment) raise segment_not_associated_message(method, segment) unless segment_holder segment_holder.send(method) end
[ "def", "modify_via_segment_holder_acts_as_list_method", "(", "method", ",", "segment", ")", "segment_holder", "=", "segment_holder_for", "(", "segment", ")", "raise", "segment_not_associated_message", "(", "method", ",", "segment", ")", "unless", "segment_holder", "segment_holder", ".", "send", "(", "method", ")", "end" ]
This method, together with method missing, is used to allow segments to be ordered within a document. It allows an acts_as_list method to be passed to the segment_holder holding a segment, so as to alter its position. For example: document.move_to_top document.segments.last will move the last segment so that it becomes the first within document.segments. The syntax is: document.<acts_as_list_method> <the_segment_to_be_moved> The segment must already belong to the document
[ "This", "method", "together", "with", "method", "missing", "is", "used", "to", "allow", "segments", "to", "be", "ordered", "within", "a", "document", ".", "It", "allows", "an", "acts_as_list", "method", "to", "be", "passed", "to", "the", "segment_holder", "holding", "a", "segment", "so", "as", "to", "alter", "its", "position", "." ]
591511cfb41c355b22ce13898298688e069cf2ce
https://github.com/reggieb/Disclaimer/blob/591511cfb41c355b22ce13898298688e069cf2ce/app/models/disclaimer/document.rb#L55-L59
train
leshill/mongodoc
lib/mongo_doc/document.rb
MongoDoc.Document.update
def update(attrs, safe = false) self.attributes = attrs if new_record? _root.send(:_save, safe) if _root _save(safe) else _update_attributes(converted_attributes(attrs), safe) end end
ruby
def update(attrs, safe = false) self.attributes = attrs if new_record? _root.send(:_save, safe) if _root _save(safe) else _update_attributes(converted_attributes(attrs), safe) end end
[ "def", "update", "(", "attrs", ",", "safe", "=", "false", ")", "self", ".", "attributes", "=", "attrs", "if", "new_record?", "_root", ".", "send", "(", ":_save", ",", "safe", ")", "if", "_root", "_save", "(", "safe", ")", "else", "_update_attributes", "(", "converted_attributes", "(", "attrs", ")", ",", "safe", ")", "end", "end" ]
Update without checking validations. The +Document+ will be saved without validations if it is a new record.
[ "Update", "without", "checking", "validations", ".", "The", "+", "Document", "+", "will", "be", "saved", "without", "validations", "if", "it", "is", "a", "new", "record", "." ]
fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4
https://github.com/leshill/mongodoc/blob/fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4/lib/mongo_doc/document.rb#L120-L128
train
Birdie0/qna_maker
lib/qna_maker/endpoints/download_kb.rb
QnAMaker.Client.download_kb
def download_kb response = @http.get( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 200 response.parse when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'].join(' ') when 404 raise NotFoundError, response.parse['error']['message'].join(' ') else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
def download_kb response = @http.get( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 200 response.parse when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'].join(' ') when 404 raise NotFoundError, response.parse['error']['message'].join(' ') else raise UnknownError, "Oh no! (#{response.code})" end end
[ "def", "download_kb", "response", "=", "@http", ".", "get", "(", "\"#{BASE_URL}/#{@knowledgebase_id}\"", ")", "case", "response", ".", "code", "when", "200", "response", ".", "parse", "when", "400", "raise", "BadArgumentError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "401", "raise", "UnauthorizedError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "403", "raise", "ForbiddenError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "404", "raise", "NotFoundError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "else", "raise", "UnknownError", ",", "\"Oh no! (#{response.code})\"", "end", "end" ]
Downloads all the data associated with the specified knowledge base @return [String] SAS url (valid for 30 mins) to tsv file in blob storage
[ "Downloads", "all", "the", "data", "associated", "with", "the", "specified", "knowledge", "base" ]
5ac204ede100355352438b8ff4fe30ad84d9257b
https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/download_kb.rb#L8-L27
train
webzakimbo/bcome-kontrol
lib/objects/orchestration/interactive_terraform.rb
Bcome::Orchestration.InteractiveTerraform.form_var_string
def form_var_string terraform_vars = terraform_metadata ec2_credentials = @node.network_driver.raw_fog_credentials cleaned_data = terraform_vars.select{|k,v| !v.is_a?(Hash) && !v.is_a?(Array) } # we can't yet handle nested terraform metadata on the command line so no arrays or hashes all_vars = cleaned_data.merge({ :access_key => ec2_credentials["aws_access_key_id"], :secret_key => ec2_credentials["aws_secret_access_key"] }) all_vars.collect{|key, value| "-var #{key}=\"#{value}\""}.join("\s") end
ruby
def form_var_string terraform_vars = terraform_metadata ec2_credentials = @node.network_driver.raw_fog_credentials cleaned_data = terraform_vars.select{|k,v| !v.is_a?(Hash) && !v.is_a?(Array) } # we can't yet handle nested terraform metadata on the command line so no arrays or hashes all_vars = cleaned_data.merge({ :access_key => ec2_credentials["aws_access_key_id"], :secret_key => ec2_credentials["aws_secret_access_key"] }) all_vars.collect{|key, value| "-var #{key}=\"#{value}\""}.join("\s") end
[ "def", "form_var_string", "terraform_vars", "=", "terraform_metadata", "ec2_credentials", "=", "@node", ".", "network_driver", ".", "raw_fog_credentials", "cleaned_data", "=", "terraform_vars", ".", "select", "{", "|", "k", ",", "v", "|", "!", "v", ".", "is_a?", "(", "Hash", ")", "&&", "!", "v", ".", "is_a?", "(", "Array", ")", "}", "all_vars", "=", "cleaned_data", ".", "merge", "(", "{", ":access_key", "=>", "ec2_credentials", "[", "\"aws_access_key_id\"", "]", ",", ":secret_key", "=>", "ec2_credentials", "[", "\"aws_secret_access_key\"", "]", "}", ")", "all_vars", ".", "collect", "{", "|", "key", ",", "value", "|", "\"-var #{key}=\\\"#{value}\\\"\"", "}", ".", "join", "(", "\"\\s\"", ")", "end" ]
Get the terraform variables for this stack, and merge in with our EC2 access keys
[ "Get", "the", "terraform", "variables", "for", "this", "stack", "and", "merge", "in", "with", "our", "EC2", "access", "keys" ]
59129cc7c8bb6c39e457abed783aa23c1d60cd05
https://github.com/webzakimbo/bcome-kontrol/blob/59129cc7c8bb6c39e457abed783aa23c1d60cd05/lib/objects/orchestration/interactive_terraform.rb#L49-L63
train
ManageIQ/polisher
lib/polisher/gem/files.rb
Polisher.GemFiles.has_file_satisfied_by?
def has_file_satisfied_by?(spec_file) file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) } end
ruby
def has_file_satisfied_by?(spec_file) file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) } end
[ "def", "has_file_satisfied_by?", "(", "spec_file", ")", "file_paths", ".", "any?", "{", "|", "gem_file", "|", "RPM", "::", "Spec", ".", "file_satisfies?", "(", "spec_file", ",", "gem_file", ")", "}", "end" ]
module ClassMethods Return bool indicating if spec file satisfies any file in gem
[ "module", "ClassMethods", "Return", "bool", "indicating", "if", "spec", "file", "satisfies", "any", "file", "in", "gem" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/files.rb#L63-L65
train
ManageIQ/polisher
lib/polisher/gem/files.rb
Polisher.GemFiles.unpack
def unpack(&bl) dir = nil pkg = ::Gem::Installer.new gem_path, :unpack => true if bl Dir.mktmpdir do |tmpdir| pkg.unpack tmpdir bl.call tmpdir end else dir = Dir.mktmpdir pkg.unpack dir end dir end
ruby
def unpack(&bl) dir = nil pkg = ::Gem::Installer.new gem_path, :unpack => true if bl Dir.mktmpdir do |tmpdir| pkg.unpack tmpdir bl.call tmpdir end else dir = Dir.mktmpdir pkg.unpack dir end dir end
[ "def", "unpack", "(", "&", "bl", ")", "dir", "=", "nil", "pkg", "=", "::", "Gem", "::", "Installer", ".", "new", "gem_path", ",", ":unpack", "=>", "true", "if", "bl", "Dir", ".", "mktmpdir", "do", "|", "tmpdir", "|", "pkg", ".", "unpack", "tmpdir", "bl", ".", "call", "tmpdir", "end", "else", "dir", "=", "Dir", ".", "mktmpdir", "pkg", ".", "unpack", "dir", "end", "dir", "end" ]
Unpack files & return unpacked directory If block is specified, it will be invoked with directory after which directory will be removed
[ "Unpack", "files", "&", "return", "unpacked", "directory" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/files.rb#L71-L86
train
ManageIQ/polisher
lib/polisher/gem/files.rb
Polisher.GemFiles.each_file
def each_file(&bl) unpack do |dir| Pathname.new(dir).find do |path| next if path.to_s == dir.to_s pathstr = path.to_s.gsub("#{dir}/", '') bl.call pathstr unless pathstr.blank? end end end
ruby
def each_file(&bl) unpack do |dir| Pathname.new(dir).find do |path| next if path.to_s == dir.to_s pathstr = path.to_s.gsub("#{dir}/", '') bl.call pathstr unless pathstr.blank? end end end
[ "def", "each_file", "(", "&", "bl", ")", "unpack", "do", "|", "dir", "|", "Pathname", ".", "new", "(", "dir", ")", ".", "find", "do", "|", "path", "|", "next", "if", "path", ".", "to_s", "==", "dir", ".", "to_s", "pathstr", "=", "path", ".", "to_s", ".", "gsub", "(", "\"#{dir}/\"", ",", "''", ")", "bl", ".", "call", "pathstr", "unless", "pathstr", ".", "blank?", "end", "end", "end" ]
Iterate over each file in gem invoking block with path
[ "Iterate", "over", "each", "file", "in", "gem", "invoking", "block", "with", "path" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/files.rb#L89-L97
train
razor-x/config_curator
lib/config_curator/units/component.rb
ConfigCurator.Component.install_component
def install_component if (backend != :stdlib && command?('rsync')) || backend == :rsync FileUtils.mkdir_p destination_path cmd = [command?('rsync'), '-rtc', '--del', '--links', "#{source_path}/", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) else FileUtils.remove_entry_secure destination_path if Dir.exist? destination_path FileUtils.mkdir_p destination_path FileUtils.cp_r "#{source_path}/.", destination_path, preserve: true end end
ruby
def install_component if (backend != :stdlib && command?('rsync')) || backend == :rsync FileUtils.mkdir_p destination_path cmd = [command?('rsync'), '-rtc', '--del', '--links', "#{source_path}/", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) else FileUtils.remove_entry_secure destination_path if Dir.exist? destination_path FileUtils.mkdir_p destination_path FileUtils.cp_r "#{source_path}/.", destination_path, preserve: true end end
[ "def", "install_component", "if", "(", "backend", "!=", ":stdlib", "&&", "command?", "(", "'rsync'", ")", ")", "||", "backend", "==", ":rsync", "FileUtils", ".", "mkdir_p", "destination_path", "cmd", "=", "[", "command?", "(", "'rsync'", ")", ",", "'-rtc'", ",", "'--del'", ",", "'--links'", ",", "\"#{source_path}/\"", ",", "destination_path", "]", "logger", ".", "debug", "{", "\"Running command: #{cmd.join ' '}\"", "}", "system", "(", "*", "cmd", ")", "else", "FileUtils", ".", "remove_entry_secure", "destination_path", "if", "Dir", ".", "exist?", "destination_path", "FileUtils", ".", "mkdir_p", "destination_path", "FileUtils", ".", "cp_r", "\"#{source_path}/.\"", ",", "destination_path", ",", "preserve", ":", "true", "end", "end" ]
Recursively creates the necessary directories and installs the component. Any files in the install directory not in the source directory are removed. Use rsync if available.
[ "Recursively", "creates", "the", "necessary", "directories", "and", "installs", "the", "component", ".", "Any", "files", "in", "the", "install", "directory", "not", "in", "the", "source", "directory", "are", "removed", ".", "Use", "rsync", "if", "available", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/component.rb#L49-L60
train
razor-x/config_curator
lib/config_curator/units/component.rb
ConfigCurator.Component.set_mode
def set_mode chmod = command? 'chmod' find = command? 'find' return unless chmod && find {fmode: 'f', dmode: 'd'}.each do |k, v| next if send(k).nil? cmd = [find, destination_path, '-type', v, '-exec'] cmd.concat [chmod, send(k).to_s(8), '{}', '+'] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end end
ruby
def set_mode chmod = command? 'chmod' find = command? 'find' return unless chmod && find {fmode: 'f', dmode: 'd'}.each do |k, v| next if send(k).nil? cmd = [find, destination_path, '-type', v, '-exec'] cmd.concat [chmod, send(k).to_s(8), '{}', '+'] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end end
[ "def", "set_mode", "chmod", "=", "command?", "'chmod'", "find", "=", "command?", "'find'", "return", "unless", "chmod", "&&", "find", "{", "fmode", ":", "'f'", ",", "dmode", ":", "'d'", "}", ".", "each", "do", "|", "k", ",", "v", "|", "next", "if", "send", "(", "k", ")", ".", "nil?", "cmd", "=", "[", "find", ",", "destination_path", ",", "'-type'", ",", "v", ",", "'-exec'", "]", "cmd", ".", "concat", "[", "chmod", ",", "send", "(", "k", ")", ".", "to_s", "(", "8", ")", ",", "'{}'", ",", "'+'", "]", "logger", ".", "debug", "{", "\"Running command: #{cmd.join ' '}\"", "}", "system", "(", "*", "cmd", ")", "end", "end" ]
Recursively sets file mode. @todo Make this more platform independent.
[ "Recursively", "sets", "file", "mode", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/component.rb#L64-L77
train
razor-x/config_curator
lib/config_curator/units/component.rb
ConfigCurator.Component.set_owner
def set_owner return unless owner || group chown = command? 'chown' return unless chown cmd = [chown, '-R', "#{owner}:#{group}", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end
ruby
def set_owner return unless owner || group chown = command? 'chown' return unless chown cmd = [chown, '-R', "#{owner}:#{group}", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end
[ "def", "set_owner", "return", "unless", "owner", "||", "group", "chown", "=", "command?", "'chown'", "return", "unless", "chown", "cmd", "=", "[", "chown", ",", "'-R'", ",", "\"#{owner}:#{group}\"", ",", "destination_path", "]", "logger", ".", "debug", "{", "\"Running command: #{cmd.join ' '}\"", "}", "system", "(", "*", "cmd", ")", "end" ]
Recursively sets file owner and group. @todo Make this more platform independent.
[ "Recursively", "sets", "file", "owner", "and", "group", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/component.rb#L81-L90
train
wizardwerdna/pokerstats
lib/pokerstats/hand_statistics.rb
Pokerstats.HandStatistics.calculate_player_position
def calculate_player_position screen_name @cached_player_position = {} @player_hashes.sort!{|a,b| button_relative_seat(a) <=> button_relative_seat(b)} @player_hashes = [@player_hashes.pop] + @player_hashes unless @player_hashes.first[:seat] == @button_player_index @player_hashes.each_with_index{|player, index| player[:position] = index, @cached_player_position[player[:screen_name]] = index} @cached_player_position[screen_name] end
ruby
def calculate_player_position screen_name @cached_player_position = {} @player_hashes.sort!{|a,b| button_relative_seat(a) <=> button_relative_seat(b)} @player_hashes = [@player_hashes.pop] + @player_hashes unless @player_hashes.first[:seat] == @button_player_index @player_hashes.each_with_index{|player, index| player[:position] = index, @cached_player_position[player[:screen_name]] = index} @cached_player_position[screen_name] end
[ "def", "calculate_player_position", "screen_name", "@cached_player_position", "=", "{", "}", "@player_hashes", ".", "sort!", "{", "|", "a", ",", "b", "|", "button_relative_seat", "(", "a", ")", "<=>", "button_relative_seat", "(", "b", ")", "}", "@player_hashes", "=", "[", "@player_hashes", ".", "pop", "]", "+", "@player_hashes", "unless", "@player_hashes", ".", "first", "[", ":seat", "]", "==", "@button_player_index", "@player_hashes", ".", "each_with_index", "{", "|", "player", ",", "index", "|", "player", "[", ":position", "]", "=", "index", ",", "@cached_player_position", "[", "player", "[", ":screen_name", "]", "]", "=", "index", "}", "@cached_player_position", "[", "screen_name", "]", "end" ]
long computation is cached, which cache is cleared every time a new player is registered
[ "long", "computation", "is", "cached", "which", "cache", "is", "cleared", "every", "time", "a", "new", "player", "is", "registered" ]
315a4db29630c586fb080d084fa17dcad9494a84
https://github.com/wizardwerdna/pokerstats/blob/315a4db29630c586fb080d084fa17dcad9494a84/lib/pokerstats/hand_statistics.rb#L119-L125
train
wizardwerdna/pokerstats
lib/pokerstats/hand_statistics.rb
Pokerstats.HandStatistics.betting_order?
def betting_order?(screen_name_first, screen_name_second) if button?(screen_name_first) false elsif button?(screen_name_second) true else position(screen_name_first) < position(screen_name_second) end end
ruby
def betting_order?(screen_name_first, screen_name_second) if button?(screen_name_first) false elsif button?(screen_name_second) true else position(screen_name_first) < position(screen_name_second) end end
[ "def", "betting_order?", "(", "screen_name_first", ",", "screen_name_second", ")", "if", "button?", "(", "screen_name_first", ")", "false", "elsif", "button?", "(", "screen_name_second", ")", "true", "else", "position", "(", "screen_name_first", ")", "<", "position", "(", "screen_name_second", ")", "end", "end" ]
player screen_name_first goes before player screen_name_second
[ "player", "screen_name_first", "goes", "before", "player", "screen_name_second" ]
315a4db29630c586fb080d084fa17dcad9494a84
https://github.com/wizardwerdna/pokerstats/blob/315a4db29630c586fb080d084fa17dcad9494a84/lib/pokerstats/hand_statistics.rb#L132-L140
train
bruce/paginator
lib/paginator/pager.rb
Paginator.Pager.page
def page(number) number = (n = number.to_i) > 0 ? n : 1 Page.new(self, number, lambda { offset = (number - 1) * @per_page args = [offset] args << @per_page if @select.arity == 2 @select.call(*args) }) end
ruby
def page(number) number = (n = number.to_i) > 0 ? n : 1 Page.new(self, number, lambda { offset = (number - 1) * @per_page args = [offset] args << @per_page if @select.arity == 2 @select.call(*args) }) end
[ "def", "page", "(", "number", ")", "number", "=", "(", "n", "=", "number", ".", "to_i", ")", ">", "0", "?", "n", ":", "1", "Page", ".", "new", "(", "self", ",", "number", ",", "lambda", "{", "offset", "=", "(", "number", "-", "1", ")", "*", "@per_page", "args", "=", "[", "offset", "]", "args", "<<", "@per_page", "if", "@select", ".", "arity", "==", "2", "@select", ".", "call", "(", "*", "args", ")", "}", ")", "end" ]
Retrieve page object by number
[ "Retrieve", "page", "object", "by", "number" ]
31f6f618674b4bb4d9e052e4b2f49865125ef413
https://github.com/bruce/paginator/blob/31f6f618674b4bb4d9e052e4b2f49865125ef413/lib/paginator/pager.rb#L48-L56
train
wordjelly/Auth
lib/auth/mailgun.rb
Auth.Mailgun.add_webhook_identifier_to_email
def add_webhook_identifier_to_email(email) email.message.mailgun_variables = {} email.message.mailgun_variables["webhook_identifier"] = BSON::ObjectId.new.to_s email end
ruby
def add_webhook_identifier_to_email(email) email.message.mailgun_variables = {} email.message.mailgun_variables["webhook_identifier"] = BSON::ObjectId.new.to_s email end
[ "def", "add_webhook_identifier_to_email", "(", "email", ")", "email", ".", "message", ".", "mailgun_variables", "=", "{", "}", "email", ".", "message", ".", "mailgun_variables", "[", "\"webhook_identifier\"", "]", "=", "BSON", "::", "ObjectId", ".", "new", ".", "to_s", "email", "end" ]
returns the email after adding a webhook identifier variable.
[ "returns", "the", "email", "after", "adding", "a", "webhook", "identifier", "variable", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/lib/auth/mailgun.rb#L4-L8
train
postmodern/deployml
lib/deployml/shell.rb
DeploYML.Shell.ruby
def ruby(program,*arguments) command = [program, *arguments] # assume that `.rb` scripts do not have a `#!/usr/bin/env ruby` command.unshift('ruby') if program[-3,3] == '.rb' # if the environment uses bundler, run all ruby commands via `bundle exec` if (@environment && @environment.bundler) command.unshift('bundle','exec') end run(*command) end
ruby
def ruby(program,*arguments) command = [program, *arguments] # assume that `.rb` scripts do not have a `#!/usr/bin/env ruby` command.unshift('ruby') if program[-3,3] == '.rb' # if the environment uses bundler, run all ruby commands via `bundle exec` if (@environment && @environment.bundler) command.unshift('bundle','exec') end run(*command) end
[ "def", "ruby", "(", "program", ",", "*", "arguments", ")", "command", "=", "[", "program", ",", "*", "arguments", "]", "command", ".", "unshift", "(", "'ruby'", ")", "if", "program", "[", "-", "3", ",", "3", "]", "==", "'.rb'", "if", "(", "@environment", "&&", "@environment", ".", "bundler", ")", "command", ".", "unshift", "(", "'bundle'", ",", "'exec'", ")", "end", "run", "(", "*", "command", ")", "end" ]
Executes a Ruby program. @param [Symbol, String] program Name of the Ruby program to run. @param [Array<String>] arguments Additional arguments for the Ruby program. @since 0.5.2
[ "Executes", "a", "Ruby", "program", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/shell.rb#L80-L92
train
postmodern/deployml
lib/deployml/shell.rb
DeploYML.Shell.shellescape
def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end
ruby
def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end
[ "def", "shellescape", "(", "str", ")", "return", "\"''\"", "if", "str", ".", "empty?", "str", "=", "str", ".", "dup", "str", ".", "gsub!", "(", "/", "\\-", "\\/", "\\n", "/n", ",", "\"\\\\\\\\\\\\1\"", ")", "str", ".", "gsub!", "(", "/", "\\n", "/", ",", "\"'\\n'\"", ")", "return", "str", "end" ]
Escapes a string so that it can be safely used in a Bourne shell command line. Note that a resulted string should be used unquoted and is not intended for use in double quotes nor in single quotes. @param [String] str The string to escape. @return [String] The shell-escaped string. @example open("| grep #{Shellwords.escape(pattern)} file") { |pipe| # ... } @note Vendored from `shellwords.rb` line 72 from Ruby 1.9.2.
[ "Escapes", "a", "string", "so", "that", "it", "can", "be", "safely", "used", "in", "a", "Bourne", "shell", "command", "line", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/shell.rb#L141-L156
train
postmodern/deployml
lib/deployml/shell.rb
DeploYML.Shell.rake_task
def rake_task(name,*arguments) name = name.to_s unless arguments.empty? name += ('[' + arguments.join(',') + ']') end return name end
ruby
def rake_task(name,*arguments) name = name.to_s unless arguments.empty? name += ('[' + arguments.join(',') + ']') end return name end
[ "def", "rake_task", "(", "name", ",", "*", "arguments", ")", "name", "=", "name", ".", "to_s", "unless", "arguments", ".", "empty?", "name", "+=", "(", "'['", "+", "arguments", ".", "join", "(", "','", ")", "+", "']'", ")", "end", "return", "name", "end" ]
Builds a `rake` task name. @param [String, Symbol] name The name of the `rake` task. @param [Array] arguments Additional arguments to pass to the `rake` task. @return [String] The `rake` task name to be called.
[ "Builds", "a", "rake", "task", "name", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/shell.rb#L170-L178
train
sawaken/tsparser
lib/binary.rb
TSparser.Binary.read_byte_as_integer
def read_byte_as_integer(bytelen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end if self.length - bit_pointer/8 < bytelen raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte) " + "is shorter than specified byte length(#{bytelen}byte).") end response = 0 bytelen.times do |i| response = response << 8 response += to_i(bit_pointer/8 + i) end bit_pointer_inc(bytelen * 8) return response end
ruby
def read_byte_as_integer(bytelen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end if self.length - bit_pointer/8 < bytelen raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte) " + "is shorter than specified byte length(#{bytelen}byte).") end response = 0 bytelen.times do |i| response = response << 8 response += to_i(bit_pointer/8 + i) end bit_pointer_inc(bytelen * 8) return response end
[ "def", "read_byte_as_integer", "(", "bytelen", ")", "unless", "bit_pointer", "%", "8", "==", "0", "raise", "BinaryException", ".", "new", "(", "\"Bit pointer must be pointing start of byte. \"", "+", "\"But now pointing #{bit_pointer}.\"", ")", "end", "if", "self", ".", "length", "-", "bit_pointer", "/", "8", "<", "bytelen", "raise", "BinaryException", ".", "new", "(", "\"Rest of self length(#{self.length - bit_pointer/8}byte) \"", "+", "\"is shorter than specified byte length(#{bytelen}byte).\"", ")", "end", "response", "=", "0", "bytelen", ".", "times", "do", "|", "i", "|", "response", "=", "response", "<<", "8", "response", "+=", "to_i", "(", "bit_pointer", "/", "8", "+", "i", ")", "end", "bit_pointer_inc", "(", "bytelen", "*", "8", ")", "return", "response", "end" ]
Read specified length of bytes and return as Integer instance. Bit pointer proceed for that length.
[ "Read", "specified", "length", "of", "bytes", "and", "return", "as", "Integer", "instance", ".", "Bit", "pointer", "proceed", "for", "that", "length", "." ]
069500619eb12528782761356c75e444c328c4e1
https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/binary.rb#L119-L135
train
sawaken/tsparser
lib/binary.rb
TSparser.Binary.read_one_bit
def read_one_bit unless self.length * 8 - bit_pointer > 0 raise BinaryException.new("Readable buffer doesn't exist" + "(#{self.length * 8 - bit_pointer}bit exists).") end response = to_i(bit_pointer/8)[7 - bit_pointer%8] bit_pointer_inc(1) return response end
ruby
def read_one_bit unless self.length * 8 - bit_pointer > 0 raise BinaryException.new("Readable buffer doesn't exist" + "(#{self.length * 8 - bit_pointer}bit exists).") end response = to_i(bit_pointer/8)[7 - bit_pointer%8] bit_pointer_inc(1) return response end
[ "def", "read_one_bit", "unless", "self", ".", "length", "*", "8", "-", "bit_pointer", ">", "0", "raise", "BinaryException", ".", "new", "(", "\"Readable buffer doesn't exist\"", "+", "\"(#{self.length * 8 - bit_pointer}bit exists).\"", ")", "end", "response", "=", "to_i", "(", "bit_pointer", "/", "8", ")", "[", "7", "-", "bit_pointer", "%", "8", "]", "bit_pointer_inc", "(", "1", ")", "return", "response", "end" ]
Read one bit and return as 0 or 1. Bit pointer proceed for one.
[ "Read", "one", "bit", "and", "return", "as", "0", "or", "1", ".", "Bit", "pointer", "proceed", "for", "one", "." ]
069500619eb12528782761356c75e444c328c4e1
https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/binary.rb#L139-L147
train
sawaken/tsparser
lib/binary.rb
TSparser.Binary.read_bit_as_binary
def read_bit_as_binary(bitlen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end unless bitlen % 8 == 0 raise BinaryException.new("Arg must be integer of multiple of 8. " + "But you specified #{bitlen}.") end if self.length - bit_pointer/8 < bitlen/8 raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte)" + " is shorter than specified byte length(#{bitlen/8}byte).") end response = self[bit_pointer/8, bitlen/8] bit_pointer_inc(bitlen) return response end
ruby
def read_bit_as_binary(bitlen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end unless bitlen % 8 == 0 raise BinaryException.new("Arg must be integer of multiple of 8. " + "But you specified #{bitlen}.") end if self.length - bit_pointer/8 < bitlen/8 raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte)" + " is shorter than specified byte length(#{bitlen/8}byte).") end response = self[bit_pointer/8, bitlen/8] bit_pointer_inc(bitlen) return response end
[ "def", "read_bit_as_binary", "(", "bitlen", ")", "unless", "bit_pointer", "%", "8", "==", "0", "raise", "BinaryException", ".", "new", "(", "\"Bit pointer must be pointing start of byte. \"", "+", "\"But now pointing #{bit_pointer}.\"", ")", "end", "unless", "bitlen", "%", "8", "==", "0", "raise", "BinaryException", ".", "new", "(", "\"Arg must be integer of multiple of 8. \"", "+", "\"But you specified #{bitlen}.\"", ")", "end", "if", "self", ".", "length", "-", "bit_pointer", "/", "8", "<", "bitlen", "/", "8", "raise", "BinaryException", ".", "new", "(", "\"Rest of self length(#{self.length - bit_pointer/8}byte)\"", "+", "\" is shorter than specified byte length(#{bitlen/8}byte).\"", ")", "end", "response", "=", "self", "[", "bit_pointer", "/", "8", ",", "bitlen", "/", "8", "]", "bit_pointer_inc", "(", "bitlen", ")", "return", "response", "end" ]
Read specified length of bits and return as Binary instance. Bit pointer proceed for that length. *Warning*: "bitlen" must be integer of multiple of 8, and bit pointer must be pointing start of byte.
[ "Read", "specified", "length", "of", "bits", "and", "return", "as", "Binary", "instance", ".", "Bit", "pointer", "proceed", "for", "that", "length", "." ]
069500619eb12528782761356c75e444c328c4e1
https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/binary.rb#L154-L170
train
webzakimbo/bcome-kontrol
lib/objects/registry/command/external.rb
Bcome::Registry::Command.External.execute
def execute(node, arguments) full_command = construct_full_command(node, arguments) begin puts "\n(external) > #{full_command}".bc_blue + "\n\n" system(full_command) rescue Interrupt puts "\nExiting gracefully from interrupt\n".warning end end
ruby
def execute(node, arguments) full_command = construct_full_command(node, arguments) begin puts "\n(external) > #{full_command}".bc_blue + "\n\n" system(full_command) rescue Interrupt puts "\nExiting gracefully from interrupt\n".warning end end
[ "def", "execute", "(", "node", ",", "arguments", ")", "full_command", "=", "construct_full_command", "(", "node", ",", "arguments", ")", "begin", "puts", "\"\\n(external) > #{full_command}\"", ".", "bc_blue", "+", "\"\\n\\n\"", "system", "(", "full_command", ")", "rescue", "Interrupt", "puts", "\"\\nExiting gracefully from interrupt\\n\"", ".", "warning", "end", "end" ]
In which the bcome context is passed to an external call
[ "In", "which", "the", "bcome", "context", "is", "passed", "to", "an", "external", "call" ]
59129cc7c8bb6c39e457abed783aa23c1d60cd05
https://github.com/webzakimbo/bcome-kontrol/blob/59129cc7c8bb6c39e457abed783aa23c1d60cd05/lib/objects/registry/command/external.rb#L5-L13
train
kontena/opto
lib/opto/group.rb
Opto.Group.option
def option(option_name) if option_name.to_s.include?('.') parts = option_name.to_s.split('.') var_name = parts.pop group = parts.inject(self) do |base, part| grp = base.option(part).value if grp.nil? raise NameError, "No such group: #{base.name}.#{part}" elsif grp.kind_of?(Opto::Group) grp else raise TypeError, "Is not a group: #{base.name}.#{part}" end end else group = self var_name = option_name end group.options.find { |opt| opt.name == var_name } end
ruby
def option(option_name) if option_name.to_s.include?('.') parts = option_name.to_s.split('.') var_name = parts.pop group = parts.inject(self) do |base, part| grp = base.option(part).value if grp.nil? raise NameError, "No such group: #{base.name}.#{part}" elsif grp.kind_of?(Opto::Group) grp else raise TypeError, "Is not a group: #{base.name}.#{part}" end end else group = self var_name = option_name end group.options.find { |opt| opt.name == var_name } end
[ "def", "option", "(", "option_name", ")", "if", "option_name", ".", "to_s", ".", "include?", "(", "'.'", ")", "parts", "=", "option_name", ".", "to_s", ".", "split", "(", "'.'", ")", "var_name", "=", "parts", ".", "pop", "group", "=", "parts", ".", "inject", "(", "self", ")", "do", "|", "base", ",", "part", "|", "grp", "=", "base", ".", "option", "(", "part", ")", ".", "value", "if", "grp", ".", "nil?", "raise", "NameError", ",", "\"No such group: #{base.name}.#{part}\"", "elsif", "grp", ".", "kind_of?", "(", "Opto", "::", "Group", ")", "grp", "else", "raise", "TypeError", ",", "\"Is not a group: #{base.name}.#{part}\"", "end", "end", "else", "group", "=", "self", "var_name", "=", "option_name", "end", "group", ".", "options", ".", "find", "{", "|", "opt", "|", "opt", ".", "name", "==", "var_name", "}", "end" ]
Find a member by name @param [String] option_name @return [Opto::Option]
[ "Find", "a", "member", "by", "name" ]
7be243226fd2dc6beca61f49379894115396a424
https://github.com/kontena/opto/blob/7be243226fd2dc6beca61f49379894115396a424/lib/opto/group.rb#L110-L130
train
opengovernment/govkit
lib/gov_kit/acts_as_noteworthy.rb
GovKit::ActsAsNoteworthy.ActMethods.acts_as_noteworthy
def acts_as_noteworthy(options={}) class_inheritable_accessor :options self.options = options unless included_modules.include? InstanceMethods instance_eval do has_many :mentions, :as => :owner, :order => 'date desc' with_options :as => :owner, :class_name => "Mention" do |c| c.has_many :google_news_mentions, :conditions => {:search_source => "Google News"}, :order => 'date desc' c.has_many :google_blog_mentions, :conditions => {:search_source => "Google Blogs"}, :order => 'date desc' # c.has_many :technorati_mentions, :conditions => {:search_source => "Technorati"}, :order => 'date desc' c.has_many :bing_mentions, :conditions => {:search_source => "Bing"}, :order => 'date desc' end end extend ClassMethods include InstanceMethods end end
ruby
def acts_as_noteworthy(options={}) class_inheritable_accessor :options self.options = options unless included_modules.include? InstanceMethods instance_eval do has_many :mentions, :as => :owner, :order => 'date desc' with_options :as => :owner, :class_name => "Mention" do |c| c.has_many :google_news_mentions, :conditions => {:search_source => "Google News"}, :order => 'date desc' c.has_many :google_blog_mentions, :conditions => {:search_source => "Google Blogs"}, :order => 'date desc' # c.has_many :technorati_mentions, :conditions => {:search_source => "Technorati"}, :order => 'date desc' c.has_many :bing_mentions, :conditions => {:search_source => "Bing"}, :order => 'date desc' end end extend ClassMethods include InstanceMethods end end
[ "def", "acts_as_noteworthy", "(", "options", "=", "{", "}", ")", "class_inheritable_accessor", ":options", "self", ".", "options", "=", "options", "unless", "included_modules", ".", "include?", "InstanceMethods", "instance_eval", "do", "has_many", ":mentions", ",", ":as", "=>", ":owner", ",", ":order", "=>", "'date desc'", "with_options", ":as", "=>", ":owner", ",", ":class_name", "=>", "\"Mention\"", "do", "|", "c", "|", "c", ".", "has_many", ":google_news_mentions", ",", ":conditions", "=>", "{", ":search_source", "=>", "\"Google News\"", "}", ",", ":order", "=>", "'date desc'", "c", ".", "has_many", ":google_blog_mentions", ",", ":conditions", "=>", "{", ":search_source", "=>", "\"Google Blogs\"", "}", ",", ":order", "=>", "'date desc'", "c", ".", "has_many", ":bing_mentions", ",", ":conditions", "=>", "{", ":search_source", "=>", "\"Bing\"", "}", ",", ":order", "=>", "'date desc'", "end", "end", "extend", "ClassMethods", "include", "InstanceMethods", "end", "end" ]
Sets up the relationship between the model and the mention model @param [Hash] opts a hash of options to be used by the relationship
[ "Sets", "up", "the", "relationship", "between", "the", "model", "and", "the", "mention", "model" ]
6e1864ef173109dbb1cfadedb19e69849f8ed226
https://github.com/opengovernment/govkit/blob/6e1864ef173109dbb1cfadedb19e69849f8ed226/lib/gov_kit/acts_as_noteworthy.rb#L12-L31
train
opengovernment/govkit
lib/gov_kit/acts_as_noteworthy.rb
GovKit::ActsAsNoteworthy.InstanceMethods.raw_mentions
def raw_mentions opts = self.options.clone attributes = opts.delete(:with) if opts[:geo] opts[:geo] = self.instance_eval("#{opts[:geo]}") end query = [] attributes.each do |attr| query << self.instance_eval("#{attr}") end { :google_news => GovKit::SearchEngines::GoogleNews.search(query, opts), :google_blogs => GovKit::SearchEngines::GoogleBlog.search(query, opts), # :technorati => GovKit::SearchEngines::Technorati.search(query), :bing => GovKit::SearchEngines::Bing.search(query, opts) } end
ruby
def raw_mentions opts = self.options.clone attributes = opts.delete(:with) if opts[:geo] opts[:geo] = self.instance_eval("#{opts[:geo]}") end query = [] attributes.each do |attr| query << self.instance_eval("#{attr}") end { :google_news => GovKit::SearchEngines::GoogleNews.search(query, opts), :google_blogs => GovKit::SearchEngines::GoogleBlog.search(query, opts), # :technorati => GovKit::SearchEngines::Technorati.search(query), :bing => GovKit::SearchEngines::Bing.search(query, opts) } end
[ "def", "raw_mentions", "opts", "=", "self", ".", "options", ".", "clone", "attributes", "=", "opts", ".", "delete", "(", ":with", ")", "if", "opts", "[", ":geo", "]", "opts", "[", ":geo", "]", "=", "self", ".", "instance_eval", "(", "\"#{opts[:geo]}\"", ")", "end", "query", "=", "[", "]", "attributes", ".", "each", "do", "|", "attr", "|", "query", "<<", "self", ".", "instance_eval", "(", "\"#{attr}\"", ")", "end", "{", ":google_news", "=>", "GovKit", "::", "SearchEngines", "::", "GoogleNews", ".", "search", "(", "query", ",", "opts", ")", ",", ":google_blogs", "=>", "GovKit", "::", "SearchEngines", "::", "GoogleBlog", ".", "search", "(", "query", ",", "opts", ")", ",", ":bing", "=>", "GovKit", "::", "SearchEngines", "::", "Bing", ".", "search", "(", "query", ",", "opts", ")", "}", "end" ]
Generates the raw mentions to be loaded into the Mention objects @return [Hash] a hash of all the mentions found of the object in question.
[ "Generates", "the", "raw", "mentions", "to", "be", "loaded", "into", "the", "Mention", "objects" ]
6e1864ef173109dbb1cfadedb19e69849f8ed226
https://github.com/opengovernment/govkit/blob/6e1864ef173109dbb1cfadedb19e69849f8ed226/lib/gov_kit/acts_as_noteworthy.rb#L42-L61
train
Birdie0/qna_maker
lib/qna_maker/endpoints/publish_kb.rb
QnAMaker.Client.publish_kb
def publish_kb response = @http.put( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 409 raise ConflictError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
def publish_kb response = @http.put( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 409 raise ConflictError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
[ "def", "publish_kb", "response", "=", "@http", ".", "put", "(", "\"#{BASE_URL}/#{@knowledgebase_id}\"", ")", "case", "response", ".", "code", "when", "204", "nil", "when", "400", "raise", "BadArgumentError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "401", "raise", "UnauthorizedError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "403", "raise", "ForbiddenError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "404", "raise", "NotFoundError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "409", "raise", "ConflictError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "else", "raise", "UnknownError", ",", "\"Oh no! (#{response.code})\"", "end", "end" ]
Publish all unpublished in the knowledgebase to the prod endpoint @return [nil] on success
[ "Publish", "all", "unpublished", "in", "the", "knowledgebase", "to", "the", "prod", "endpoint" ]
5ac204ede100355352438b8ff4fe30ad84d9257b
https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/publish_kb.rb#L8-L29
train
cbot/push0r
lib/push0r/APNS/ApnsPushMessage.rb
Push0r.ApnsPushMessage.simple
def simple(alert_text = nil, sound = nil, badge = nil, category = nil) new_payload = {aps: {}} if alert_text new_payload[:aps][:alert] = alert_text end if sound new_payload[:aps][:sound] = sound end if badge new_payload[:aps][:badge] = badge end if category new_payload[:aps][:category] = category end @payload.merge!(new_payload) return self end
ruby
def simple(alert_text = nil, sound = nil, badge = nil, category = nil) new_payload = {aps: {}} if alert_text new_payload[:aps][:alert] = alert_text end if sound new_payload[:aps][:sound] = sound end if badge new_payload[:aps][:badge] = badge end if category new_payload[:aps][:category] = category end @payload.merge!(new_payload) return self end
[ "def", "simple", "(", "alert_text", "=", "nil", ",", "sound", "=", "nil", ",", "badge", "=", "nil", ",", "category", "=", "nil", ")", "new_payload", "=", "{", "aps", ":", "{", "}", "}", "if", "alert_text", "new_payload", "[", ":aps", "]", "[", ":alert", "]", "=", "alert_text", "end", "if", "sound", "new_payload", "[", ":aps", "]", "[", ":sound", "]", "=", "sound", "end", "if", "badge", "new_payload", "[", ":aps", "]", "[", ":badge", "]", "=", "badge", "end", "if", "category", "new_payload", "[", ":aps", "]", "[", ":category", "]", "=", "category", "end", "@payload", ".", "merge!", "(", "new_payload", ")", "return", "self", "end" ]
Returns a new ApnsPushMessage instance that encapsulates a single push notification to be sent to a single user. @param receiver_token [String] the apns push token (aka device token) to push the notification to @param environment [Fixnum] the environment to use when sending this push message. Defaults to ApnsEnvironment::PRODUCTION. @param identifier [Fixnum] a unique identifier to identify this push message during error handling. If nil, a random identifier is automatically generated. @param time_to_live [Fixnum] The time to live in seconds for this push messages. If nil, the time to live is set to zero seconds. Convenience method to attach common data (that is an alert, a sound or a badge value) to this message's payload. @param alert_text [String] the alert text to be displayed @param sound [String] the sound to be played @param badge [Fixnum] the badge value to be displayed @param category [String] the category this message belongs to (see UIUserNotificationCategory in apple's documentation)
[ "Returns", "a", "new", "ApnsPushMessage", "instance", "that", "encapsulates", "a", "single", "push", "notification", "to", "be", "sent", "to", "a", "single", "user", "." ]
07eb7bece1f251608529dea0d7a93af1444ffeb6
https://github.com/cbot/push0r/blob/07eb7bece1f251608529dea0d7a93af1444ffeb6/lib/push0r/APNS/ApnsPushMessage.rb#L24-L42
train
ideonetwork/lato-core
lib/lato_core/interfaces/cells.rb
LatoCore.Interface::Cells.core__widgets_index
def core__widgets_index(records, search: nil, pagination: 50) response = { records: records, total: records.length, per_page: pagination, search: '', search_key: search, sort: '', sort_dir: 'ASC', pagination: 1, } # manage search if search && params[:widget_index] && params[:widget_index][:search] && !params[:widget_index][:search].blank? search_array = search.is_a?(Array) ? search : [search] query1 = '' query2 = [] search_array.each do |s| query1 += "#{s} like ? OR " query2.push("%#{params[:widget_index][:search]}%") end query1 = query1[0...-4] query = [query1] + query2 response[:records] = response[:records].where(query) response[:total] = response[:records].length response[:search] = params[:widget_index][:search] end # manage sort if params[:widget_index] && !params[:widget_index][:sort].blank? && !params[:widget_index][:sort_dir].blank? response[:sort] = params[:widget_index][:sort] response[:sort_dir] = params[:widget_index][:sort_dir] response[:records] = response[:records].order("#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}") end # manage pagination if pagination if params[:widget_index] && params[:widget_index][:pagination] response[:pagination] = params[:widget_index][:pagination].to_i end response[:records] = core__paginate_array(response[:records], pagination, response[:pagination]) end # return response response end
ruby
def core__widgets_index(records, search: nil, pagination: 50) response = { records: records, total: records.length, per_page: pagination, search: '', search_key: search, sort: '', sort_dir: 'ASC', pagination: 1, } # manage search if search && params[:widget_index] && params[:widget_index][:search] && !params[:widget_index][:search].blank? search_array = search.is_a?(Array) ? search : [search] query1 = '' query2 = [] search_array.each do |s| query1 += "#{s} like ? OR " query2.push("%#{params[:widget_index][:search]}%") end query1 = query1[0...-4] query = [query1] + query2 response[:records] = response[:records].where(query) response[:total] = response[:records].length response[:search] = params[:widget_index][:search] end # manage sort if params[:widget_index] && !params[:widget_index][:sort].blank? && !params[:widget_index][:sort_dir].blank? response[:sort] = params[:widget_index][:sort] response[:sort_dir] = params[:widget_index][:sort_dir] response[:records] = response[:records].order("#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}") end # manage pagination if pagination if params[:widget_index] && params[:widget_index][:pagination] response[:pagination] = params[:widget_index][:pagination].to_i end response[:records] = core__paginate_array(response[:records], pagination, response[:pagination]) end # return response response end
[ "def", "core__widgets_index", "(", "records", ",", "search", ":", "nil", ",", "pagination", ":", "50", ")", "response", "=", "{", "records", ":", "records", ",", "total", ":", "records", ".", "length", ",", "per_page", ":", "pagination", ",", "search", ":", "''", ",", "search_key", ":", "search", ",", "sort", ":", "''", ",", "sort_dir", ":", "'ASC'", ",", "pagination", ":", "1", ",", "}", "if", "search", "&&", "params", "[", ":widget_index", "]", "&&", "params", "[", ":widget_index", "]", "[", ":search", "]", "&&", "!", "params", "[", ":widget_index", "]", "[", ":search", "]", ".", "blank?", "search_array", "=", "search", ".", "is_a?", "(", "Array", ")", "?", "search", ":", "[", "search", "]", "query1", "=", "''", "query2", "=", "[", "]", "search_array", ".", "each", "do", "|", "s", "|", "query1", "+=", "\"#{s} like ? OR \"", "query2", ".", "push", "(", "\"%#{params[:widget_index][:search]}%\"", ")", "end", "query1", "=", "query1", "[", "0", "...", "-", "4", "]", "query", "=", "[", "query1", "]", "+", "query2", "response", "[", ":records", "]", "=", "response", "[", ":records", "]", ".", "where", "(", "query", ")", "response", "[", ":total", "]", "=", "response", "[", ":records", "]", ".", "length", "response", "[", ":search", "]", "=", "params", "[", ":widget_index", "]", "[", ":search", "]", "end", "if", "params", "[", ":widget_index", "]", "&&", "!", "params", "[", ":widget_index", "]", "[", ":sort", "]", ".", "blank?", "&&", "!", "params", "[", ":widget_index", "]", "[", ":sort_dir", "]", ".", "blank?", "response", "[", ":sort", "]", "=", "params", "[", ":widget_index", "]", "[", ":sort", "]", "response", "[", ":sort_dir", "]", "=", "params", "[", ":widget_index", "]", "[", ":sort_dir", "]", "response", "[", ":records", "]", "=", "response", "[", ":records", "]", ".", "order", "(", "\"#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}\"", ")", "end", "if", "pagination", "if", "params", "[", ":widget_index", "]", "&&", "params", "[", ":widget_index", "]", "[", ":pagination", "]", "response", "[", ":pagination", "]", "=", "params", "[", ":widget_index", "]", "[", ":pagination", "]", ".", "to_i", "end", "response", "[", ":records", "]", "=", "core__paginate_array", "(", "response", "[", ":records", "]", ",", "pagination", ",", "response", "[", ":pagination", "]", ")", "end", "response", "end" ]
This function manage the widget index from front end.
[ "This", "function", "manage", "the", "widget", "index", "from", "front", "end", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/cells.rb#L14-L56
train
thinkerbot/configurable
lib/configurable/class_methods.rb
Configurable.ClassMethods.remove_config
def remove_config(key, options={}) unless config_registry.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = config_registry.delete(key) reset_configs remove_method(config.reader) if options[:reader] remove_method(config.writer) if options[:writer] config end
ruby
def remove_config(key, options={}) unless config_registry.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = config_registry.delete(key) reset_configs remove_method(config.reader) if options[:reader] remove_method(config.writer) if options[:writer] config end
[ "def", "remove_config", "(", "key", ",", "options", "=", "{", "}", ")", "unless", "config_registry", ".", "has_key?", "(", "key", ")", "raise", "NameError", ".", "new", "(", "\"#{key.inspect} is not a config on #{self}\"", ")", "end", "options", "=", "{", ":reader", "=>", "true", ",", ":writer", "=>", "true", "}", ".", "merge", "(", "options", ")", "config", "=", "config_registry", ".", "delete", "(", "key", ")", "reset_configs", "remove_method", "(", "config", ".", "reader", ")", "if", "options", "[", ":reader", "]", "remove_method", "(", "config", ".", "writer", ")", "if", "options", "[", ":writer", "]", "config", "end" ]
Removes a config much like remove_method removes a method. The reader and writer for the config are likewise removed. Nested configs can be removed using this method. Setting :reader or :writer to false in the options prevents those methods from being removed.
[ "Removes", "a", "config", "much", "like", "remove_method", "removes", "a", "method", ".", "The", "reader", "and", "writer", "for", "the", "config", "are", "likewise", "removed", ".", "Nested", "configs", "can", "be", "removed", "using", "this", "method", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L200-L217
train
thinkerbot/configurable
lib/configurable/class_methods.rb
Configurable.ClassMethods.undef_config
def undef_config(key, options={}) unless configs.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = configs[key] config_registry[key] = nil reset_configs undef_method(config.reader) if options[:reader] undef_method(config.writer) if options[:writer] config end
ruby
def undef_config(key, options={}) unless configs.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = configs[key] config_registry[key] = nil reset_configs undef_method(config.reader) if options[:reader] undef_method(config.writer) if options[:writer] config end
[ "def", "undef_config", "(", "key", ",", "options", "=", "{", "}", ")", "unless", "configs", ".", "has_key?", "(", "key", ")", "raise", "NameError", ".", "new", "(", "\"#{key.inspect} is not a config on #{self}\"", ")", "end", "options", "=", "{", ":reader", "=>", "true", ",", ":writer", "=>", "true", "}", ".", "merge", "(", "options", ")", "config", "=", "configs", "[", "key", "]", "config_registry", "[", "key", "]", "=", "nil", "reset_configs", "undef_method", "(", "config", ".", "reader", ")", "if", "options", "[", ":reader", "]", "undef_method", "(", "config", ".", "writer", ")", "if", "options", "[", ":writer", "]", "config", "end" ]
Undefines a config much like undef_method undefines a method. The reader and writer for the config are likewise undefined. Nested configs can be undefined using this method. Setting :reader or :writer to false in the options prevents those methods from being undefined. ==== Implementation Note Configurations are undefined by setting the key to nil in the registry. Deleting the config is not sufficient because the registry needs to convey to self and subclasses to not inherit the config from ancestors. This is unlike remove_config where the config is simply deleted from the config_registry.
[ "Undefines", "a", "config", "much", "like", "undef_method", "undefines", "a", "method", ".", "The", "reader", "and", "writer", "for", "the", "config", "are", "likewise", "undefined", ".", "Nested", "configs", "can", "be", "undefined", "using", "this", "method", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L234-L252
train
thinkerbot/configurable
lib/configurable/class_methods.rb
Configurable.ClassMethods.remove_config_type
def remove_config_type(name) unless config_type_registry.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry.delete(name) reset_config_types config_type end
ruby
def remove_config_type(name) unless config_type_registry.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry.delete(name) reset_config_types config_type end
[ "def", "remove_config_type", "(", "name", ")", "unless", "config_type_registry", ".", "has_key?", "(", "name", ")", "raise", "NameError", ".", "new", "(", "\"#{name.inspect} is not a config_type on #{self}\"", ")", "end", "config_type", "=", "config_type_registry", ".", "delete", "(", "name", ")", "reset_config_types", "config_type", "end" ]
Removes a config_type much like remove_method removes a method.
[ "Removes", "a", "config_type", "much", "like", "remove_method", "removes", "a", "method", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L272-L280
train
thinkerbot/configurable
lib/configurable/class_methods.rb
Configurable.ClassMethods.undef_config_type
def undef_config_type(name) unless config_types.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry[name] config_type_registry[name] = nil reset_config_types config_type end
ruby
def undef_config_type(name) unless config_types.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry[name] config_type_registry[name] = nil reset_config_types config_type end
[ "def", "undef_config_type", "(", "name", ")", "unless", "config_types", ".", "has_key?", "(", "name", ")", "raise", "NameError", ".", "new", "(", "\"#{name.inspect} is not a config_type on #{self}\"", ")", "end", "config_type", "=", "config_type_registry", "[", "name", "]", "config_type_registry", "[", "name", "]", "=", "nil", "reset_config_types", "config_type", "end" ]
Undefines a config_type much like undef_method undefines a method. ==== Implementation Note ConfigClasses are undefined by setting the key to nil in the registry. Deleting the config_type is not sufficient because the registry needs to convey to self and subclasses to not inherit the config_type from ancestors. This is unlike remove_config_type where the config_type is simply deleted from the config_type_registry.
[ "Undefines", "a", "config_type", "much", "like", "undef_method", "undefines", "a", "method", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L293-L302
train
thinkerbot/configurable
lib/configurable/class_methods.rb
Configurable.ClassMethods.check_infinite_nest
def check_infinite_nest(klass) # :nodoc: raise "infinite nest detected" if klass == self klass.configs.each_value do |config| if config.type.kind_of?(NestType) check_infinite_nest(config.type.configurable.class) end end end
ruby
def check_infinite_nest(klass) # :nodoc: raise "infinite nest detected" if klass == self klass.configs.each_value do |config| if config.type.kind_of?(NestType) check_infinite_nest(config.type.configurable.class) end end end
[ "def", "check_infinite_nest", "(", "klass", ")", "raise", "\"infinite nest detected\"", "if", "klass", "==", "self", "klass", ".", "configs", ".", "each_value", "do", "|", "config", "|", "if", "config", ".", "type", ".", "kind_of?", "(", "NestType", ")", "check_infinite_nest", "(", "config", ".", "type", ".", "configurable", ".", "class", ")", "end", "end", "end" ]
helper to recursively check for an infinite nest
[ "helper", "to", "recursively", "check", "for", "an", "infinite", "nest" ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L334-L342
train
lautis/sweet_notifications
lib/sweet_notifications/log_subscriber.rb
SweetNotifications.LogSubscriber.message
def message(event, label, body) @odd = !@odd label_color = @odd ? odd_color : even_color format( ' %s (%.2fms) %s', color(label, label_color, true), event.duration, color(body, nil, !@odd) ) end
ruby
def message(event, label, body) @odd = !@odd label_color = @odd ? odd_color : even_color format( ' %s (%.2fms) %s', color(label, label_color, true), event.duration, color(body, nil, !@odd) ) end
[ "def", "message", "(", "event", ",", "label", ",", "body", ")", "@odd", "=", "!", "@odd", "label_color", "=", "@odd", "?", "odd_color", ":", "even_color", "format", "(", "' %s (%.2fms) %s'", ",", "color", "(", "label", ",", "label_color", ",", "true", ")", ",", "event", ".", "duration", ",", "color", "(", "body", ",", "nil", ",", "!", "@odd", ")", ")", "end" ]
Format a message for logging @param event [ActiveSupport::Notifications::Event] subscribed event @param label [String] label for log messages @param body [String] the rest @return [String] formatted message for logging ==== Examples event :test do |event| message(event, 'Test', 'message body') end # => " Test (0.00ms) message body"
[ "Format", "a", "message", "for", "logging" ]
fcd137a1b474d24e1bc86619d116fc32caba8c19
https://github.com/lautis/sweet_notifications/blob/fcd137a1b474d24e1bc86619d116fc32caba8c19/lib/sweet_notifications/log_subscriber.rb#L28-L38
train
postmodern/deployml
lib/deployml/remote_shell.rb
DeploYML.RemoteShell.join
def join commands = [] @history.each do |command| program = command[0] arguments = command[1..-1].map { |word| shellescape(word.to_s) } commands << [program, *arguments].join(' ') end return commands.join(' && ') end
ruby
def join commands = [] @history.each do |command| program = command[0] arguments = command[1..-1].map { |word| shellescape(word.to_s) } commands << [program, *arguments].join(' ') end return commands.join(' && ') end
[ "def", "join", "commands", "=", "[", "]", "@history", ".", "each", "do", "|", "command", "|", "program", "=", "command", "[", "0", "]", "arguments", "=", "command", "[", "1", "..", "-", "1", "]", ".", "map", "{", "|", "word", "|", "shellescape", "(", "word", ".", "to_s", ")", "}", "commands", "<<", "[", "program", ",", "*", "arguments", "]", ".", "join", "(", "' '", ")", "end", "return", "commands", ".", "join", "(", "' && '", ")", "end" ]
Joins the command history together with ` && `, to form a single command. @return [String] A single command string.
[ "Joins", "the", "command", "history", "together", "with", "&&", "to", "form", "a", "single", "command", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/remote_shell.rb#L99-L110
train
postmodern/deployml
lib/deployml/remote_shell.rb
DeploYML.RemoteShell.ssh_uri
def ssh_uri unless @uri.host raise(InvalidConfig,"URI does not have a host: #{@uri}",caller) end new_uri = @uri.host new_uri = "#{@uri.user}@#{new_uri}" if @uri.user return new_uri end
ruby
def ssh_uri unless @uri.host raise(InvalidConfig,"URI does not have a host: #{@uri}",caller) end new_uri = @uri.host new_uri = "#{@uri.user}@#{new_uri}" if @uri.user return new_uri end
[ "def", "ssh_uri", "unless", "@uri", ".", "host", "raise", "(", "InvalidConfig", ",", "\"URI does not have a host: #{@uri}\"", ",", "caller", ")", "end", "new_uri", "=", "@uri", ".", "host", "new_uri", "=", "\"#{@uri.user}@#{new_uri}\"", "if", "@uri", ".", "user", "return", "new_uri", "end" ]
Converts the URI to one compatible with SSH. @return [String] The SSH compatible URI. @raise [InvalidConfig] The URI of the shell does not have a host component.
[ "Converts", "the", "URI", "to", "one", "compatible", "with", "SSH", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/remote_shell.rb#L121-L130
train
postmodern/deployml
lib/deployml/remote_shell.rb
DeploYML.RemoteShell.ssh
def ssh(*arguments) options = [] # Add the -p option if an alternate destination port is given if @uri.port options += ['-p', @uri.port.to_s] end # append the SSH URI options << ssh_uri # append the additional arguments arguments.each { |arg| options << arg.to_s } return system('ssh',*options) end
ruby
def ssh(*arguments) options = [] # Add the -p option if an alternate destination port is given if @uri.port options += ['-p', @uri.port.to_s] end # append the SSH URI options << ssh_uri # append the additional arguments arguments.each { |arg| options << arg.to_s } return system('ssh',*options) end
[ "def", "ssh", "(", "*", "arguments", ")", "options", "=", "[", "]", "if", "@uri", ".", "port", "options", "+=", "[", "'-p'", ",", "@uri", ".", "port", ".", "to_s", "]", "end", "options", "<<", "ssh_uri", "arguments", ".", "each", "{", "|", "arg", "|", "options", "<<", "arg", ".", "to_s", "}", "return", "system", "(", "'ssh'", ",", "*", "options", ")", "end" ]
Starts a SSH session with the destination server. @param [Array] arguments Additional arguments to pass to SSH.
[ "Starts", "a", "SSH", "session", "with", "the", "destination", "server", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/remote_shell.rb#L138-L153
train
ManageIQ/polisher
lib/polisher/util/conf_helpers.rb
ConfHelpers.ClassMethods.conf_attr
def conf_attr(name, opts = {}) @conf_attrs ||= [] @conf_attrs << name default = opts[:default] accumulate = opts[:accumulate] send(:define_singleton_method, name) do |*args| nvar = "@#{name}".intern current = instance_variable_get(nvar) envk = "POLISHER_#{name.to_s.upcase}" if accumulate instance_variable_set(nvar, []) unless current current = instance_variable_get(nvar) current << default current << ENV[envk] current += args current.uniq! current.compact! current.flatten! instance_variable_set(nvar, current) else instance_variable_set(nvar, default) unless current instance_variable_set(nvar, ENV[envk]) if ENV.key?(envk) instance_variable_set(nvar, args.first) unless args.empty? end instance_variable_get(nvar) end send(:define_method, name) do self.class.send(name) end end
ruby
def conf_attr(name, opts = {}) @conf_attrs ||= [] @conf_attrs << name default = opts[:default] accumulate = opts[:accumulate] send(:define_singleton_method, name) do |*args| nvar = "@#{name}".intern current = instance_variable_get(nvar) envk = "POLISHER_#{name.to_s.upcase}" if accumulate instance_variable_set(nvar, []) unless current current = instance_variable_get(nvar) current << default current << ENV[envk] current += args current.uniq! current.compact! current.flatten! instance_variable_set(nvar, current) else instance_variable_set(nvar, default) unless current instance_variable_set(nvar, ENV[envk]) if ENV.key?(envk) instance_variable_set(nvar, args.first) unless args.empty? end instance_variable_get(nvar) end send(:define_method, name) do self.class.send(name) end end
[ "def", "conf_attr", "(", "name", ",", "opts", "=", "{", "}", ")", "@conf_attrs", "||=", "[", "]", "@conf_attrs", "<<", "name", "default", "=", "opts", "[", ":default", "]", "accumulate", "=", "opts", "[", ":accumulate", "]", "send", "(", ":define_singleton_method", ",", "name", ")", "do", "|", "*", "args", "|", "nvar", "=", "\"@#{name}\"", ".", "intern", "current", "=", "instance_variable_get", "(", "nvar", ")", "envk", "=", "\"POLISHER_#{name.to_s.upcase}\"", "if", "accumulate", "instance_variable_set", "(", "nvar", ",", "[", "]", ")", "unless", "current", "current", "=", "instance_variable_get", "(", "nvar", ")", "current", "<<", "default", "current", "<<", "ENV", "[", "envk", "]", "current", "+=", "args", "current", ".", "uniq!", "current", ".", "compact!", "current", ".", "flatten!", "instance_variable_set", "(", "nvar", ",", "current", ")", "else", "instance_variable_set", "(", "nvar", ",", "default", ")", "unless", "current", "instance_variable_set", "(", "nvar", ",", "ENV", "[", "envk", "]", ")", "if", "ENV", ".", "key?", "(", "envk", ")", "instance_variable_set", "(", "nvar", ",", "args", ".", "first", ")", "unless", "args", ".", "empty?", "end", "instance_variable_get", "(", "nvar", ")", "end", "send", "(", ":define_method", ",", "name", ")", "do", "self", ".", "class", ".", "send", "(", "name", ")", "end", "end" ]
Defines a 'config attribute' or attribute on the class which this is defined in. Accessors to the single shared attribute will be added to the class as well as instances of the class. Specify the default value with the attr name or via an env variable @example class Custom extend ConfHelpers conf_attr :data_dir, :default => '/etc/' end Custom.data_dir # => '/etc/' ENV['POLISHER_DATA_DIR'] = '/usr/' Custom.data_dir # => '/usr/' Custom.data_dir == Custom.new.data_dir # => true
[ "Defines", "a", "config", "attribute", "or", "attribute", "on", "the", "class", "which", "this", "is", "defined", "in", ".", "Accessors", "to", "the", "single", "shared", "attribute", "will", "be", "added", "to", "the", "class", "as", "well", "as", "instances", "of", "the", "class", ".", "Specify", "the", "default", "value", "with", "the", "attr", "name", "or", "via", "an", "env", "variable" ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/util/conf_helpers.rb#L30-L63
train
kjvarga/arid_cache
lib/arid_cache/helpers.rb
AridCache.Helpers.lookup
def lookup(object, key, opts, &block) if !block.nil? define(object, key, opts, &block) elsif key =~ /(.*)_count$/ if AridCache.store.has?(object, $1) method_for_cached(object, $1, :fetch_count, key) elsif object.respond_to?(key) define(object, key, opts, :fetch_count) elsif object.respond_to?($1) define(object, $1, opts, :fetch_count, key) else raise ArgumentError.new("#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.") end elsif AridCache.store.has?(object, key) method_for_cached(object, key, :fetch) elsif object.respond_to?(key) define(object, key, opts, &block) else raise ArgumentError.new("#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.") end object.send("cached_#{key}", opts) end
ruby
def lookup(object, key, opts, &block) if !block.nil? define(object, key, opts, &block) elsif key =~ /(.*)_count$/ if AridCache.store.has?(object, $1) method_for_cached(object, $1, :fetch_count, key) elsif object.respond_to?(key) define(object, key, opts, :fetch_count) elsif object.respond_to?($1) define(object, $1, opts, :fetch_count, key) else raise ArgumentError.new("#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.") end elsif AridCache.store.has?(object, key) method_for_cached(object, key, :fetch) elsif object.respond_to?(key) define(object, key, opts, &block) else raise ArgumentError.new("#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.") end object.send("cached_#{key}", opts) end
[ "def", "lookup", "(", "object", ",", "key", ",", "opts", ",", "&", "block", ")", "if", "!", "block", ".", "nil?", "define", "(", "object", ",", "key", ",", "opts", ",", "&", "block", ")", "elsif", "key", "=~", "/", "/", "if", "AridCache", ".", "store", ".", "has?", "(", "object", ",", "$1", ")", "method_for_cached", "(", "object", ",", "$1", ",", ":fetch_count", ",", "key", ")", "elsif", "object", ".", "respond_to?", "(", "key", ")", "define", "(", "object", ",", "key", ",", "opts", ",", ":fetch_count", ")", "elsif", "object", ".", "respond_to?", "(", "$1", ")", "define", "(", "object", ",", "$1", ",", "opts", ",", ":fetch_count", ",", "key", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.\"", ")", "end", "elsif", "AridCache", ".", "store", ".", "has?", "(", "object", ",", "key", ")", "method_for_cached", "(", "object", ",", "key", ",", ":fetch", ")", "elsif", "object", ".", "respond_to?", "(", "key", ")", "define", "(", "object", ",", "key", ",", "opts", ",", "&", "block", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.\"", ")", "end", "object", ".", "send", "(", "\"cached_#{key}\"", ",", "opts", ")", "end" ]
Lookup something from the cache. If no block is provided, create one dynamically. If a block is provided, it is only used the first time it is encountered. This allows you to dynamically define your caches while still returning the results of your query. @return a WillPaginate::Collection if the options include :page, a Fixnum count if the request is for a count or the results of the ActiveRecord query otherwise.
[ "Lookup", "something", "from", "the", "cache", "." ]
8a1e21b970aae37a3206a4ee08efa6f1002fc9e0
https://github.com/kjvarga/arid_cache/blob/8a1e21b970aae37a3206a4ee08efa6f1002fc9e0/lib/arid_cache/helpers.rb#L14-L35
train
kjvarga/arid_cache
lib/arid_cache/helpers.rb
AridCache.Helpers.define
def define(object, key, opts, fetch_method=:fetch, method_name=nil, &block) # FIXME: Pass default options to store.add # Pass nil in for now until we get the cache_ calls working. # This means that the first time you define a dynamic cache # (by passing in a block), the options you used are not # stored in the blueprint and applied to each subsequent call. # # Otherwise we have a situation where a :limit passed in to the # first call persists when no options are passed in on subsequent calls, # but if a different :limit is passed in that limit is applied. # # I think in this scenario one would expect no limit to be applied # if no options are passed in. # # When the cache_ methods are supported, those options should be # remembered and applied to the collection however. blueprint = AridCache.store.add_object_cache_configuration(object, key, nil, block) method_for_cached(object, key, fetch_method, method_name) blueprint end
ruby
def define(object, key, opts, fetch_method=:fetch, method_name=nil, &block) # FIXME: Pass default options to store.add # Pass nil in for now until we get the cache_ calls working. # This means that the first time you define a dynamic cache # (by passing in a block), the options you used are not # stored in the blueprint and applied to each subsequent call. # # Otherwise we have a situation where a :limit passed in to the # first call persists when no options are passed in on subsequent calls, # but if a different :limit is passed in that limit is applied. # # I think in this scenario one would expect no limit to be applied # if no options are passed in. # # When the cache_ methods are supported, those options should be # remembered and applied to the collection however. blueprint = AridCache.store.add_object_cache_configuration(object, key, nil, block) method_for_cached(object, key, fetch_method, method_name) blueprint end
[ "def", "define", "(", "object", ",", "key", ",", "opts", ",", "fetch_method", "=", ":fetch", ",", "method_name", "=", "nil", ",", "&", "block", ")", "blueprint", "=", "AridCache", ".", "store", ".", "add_object_cache_configuration", "(", "object", ",", "key", ",", "nil", ",", "block", ")", "method_for_cached", "(", "object", ",", "key", ",", "fetch_method", ",", "method_name", ")", "blueprint", "end" ]
Store the options and optional block for a call to the cache. If no block is provided, create one dynamically. @return an AridCache::Store::Blueprint.
[ "Store", "the", "options", "and", "optional", "block", "for", "a", "call", "to", "the", "cache", "." ]
8a1e21b970aae37a3206a4ee08efa6f1002fc9e0
https://github.com/kjvarga/arid_cache/blob/8a1e21b970aae37a3206a4ee08efa6f1002fc9e0/lib/arid_cache/helpers.rb#L42-L62
train
kjvarga/arid_cache
lib/arid_cache/helpers.rb
AridCache.Helpers.class_name
def class_name(object, *modifiers) name = object.is_a?(Class) ? object.name : object.class.name name = 'AnonymousClass' if name.nil? while modifier = modifiers.shift case modifier when :downcase name = name.downcase when :pluralize name = AridCache::Inflector.pluralize(name) else raise ArgumentError.new("Unsupported modifier #{modifier.inspect}") end end name end
ruby
def class_name(object, *modifiers) name = object.is_a?(Class) ? object.name : object.class.name name = 'AnonymousClass' if name.nil? while modifier = modifiers.shift case modifier when :downcase name = name.downcase when :pluralize name = AridCache::Inflector.pluralize(name) else raise ArgumentError.new("Unsupported modifier #{modifier.inspect}") end end name end
[ "def", "class_name", "(", "object", ",", "*", "modifiers", ")", "name", "=", "object", ".", "is_a?", "(", "Class", ")", "?", "object", ".", "name", ":", "object", ".", "class", ".", "name", "name", "=", "'AnonymousClass'", "if", "name", ".", "nil?", "while", "modifier", "=", "modifiers", ".", "shift", "case", "modifier", "when", ":downcase", "name", "=", "name", ".", "downcase", "when", ":pluralize", "name", "=", "AridCache", "::", "Inflector", ".", "pluralize", "(", "name", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Unsupported modifier #{modifier.inspect}\"", ")", "end", "end", "name", "end" ]
Return the object's class name. == Arguments * +object+ - an instance or class. If it's an anonymous class, the name is nil so we return 'anonymous_class' and 'anonymous_instance'. * +modifiers+ - one or more symbols indicating the order and type of modification to perform on the result. Choose from: :downcase (return lowercase name), :pluralize (pluralize the name)
[ "Return", "the", "object", "s", "class", "name", "." ]
8a1e21b970aae37a3206a4ee08efa6f1002fc9e0
https://github.com/kjvarga/arid_cache/blob/8a1e21b970aae37a3206a4ee08efa6f1002fc9e0/lib/arid_cache/helpers.rb#L78-L92
train
teknobingo/trust
lib/trust/permissions.rb
Trust.Permissions.authorized?
def authorized? trace 'authorized?', 0, "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}" if params_handler = (user && (permission_by_role || permission_by_member_role)) params_handler = params_handler_default(params_handler) end params_handler end
ruby
def authorized? trace 'authorized?', 0, "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}" if params_handler = (user && (permission_by_role || permission_by_member_role)) params_handler = params_handler_default(params_handler) end params_handler end
[ "def", "authorized?", "trace", "'authorized?'", ",", "0", ",", "\"@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}\"", "if", "params_handler", "=", "(", "user", "&&", "(", "permission_by_role", "||", "permission_by_member_role", ")", ")", "params_handler", "=", "params_handler_default", "(", "params_handler", ")", "end", "params_handler", "end" ]
Initializes the permission object calling the +authorized?+ method on the instance later will test for the authorization. == Parameters: +user+ - user object, must respond to role_symbols +action+ - action, such as :create, :show, etc. Should not be an alias +klass+ - the class of the subject. +subject+ - the subject tested for authorization +parent+ - the parent object, normally declared through belongs_to See {Trust::Authorization} for more details Returns params_handler if the user is authorized to perform the action The handler contains information used by the resource on retrieing parametes later
[ "Initializes", "the", "permission", "object" ]
715c5395536c7b312bc166f09f64a1c0d48bee23
https://github.com/teknobingo/trust/blob/715c5395536c7b312bc166f09f64a1c0d48bee23/lib/trust/permissions.rb#L155-L161
train
teknobingo/trust
lib/trust/permissions.rb
Trust.Permissions.permission_by_member_role
def permission_by_member_role m = members_role trace 'authorize_by_member_role?', 0, "#{user.try(:name)}:#{m}" p = member_permissions[m] trace 'authorize_by_role?', 1, "permissions: #{p.inspect}" p && authorization(p) end
ruby
def permission_by_member_role m = members_role trace 'authorize_by_member_role?', 0, "#{user.try(:name)}:#{m}" p = member_permissions[m] trace 'authorize_by_role?', 1, "permissions: #{p.inspect}" p && authorization(p) end
[ "def", "permission_by_member_role", "m", "=", "members_role", "trace", "'authorize_by_member_role?'", ",", "0", ",", "\"#{user.try(:name)}:#{m}\"", "p", "=", "member_permissions", "[", "m", "]", "trace", "'authorize_by_role?'", ",", "1", ",", "\"permissions: #{p.inspect}\"", "p", "&&", "authorization", "(", "p", ")", "end" ]
Checks is a member is authorized You will need to implement members_role in permissions yourself
[ "Checks", "is", "a", "member", "is", "authorized", "You", "will", "need", "to", "implement", "members_role", "in", "permissions", "yourself" ]
715c5395536c7b312bc166f09f64a1c0d48bee23
https://github.com/teknobingo/trust/blob/715c5395536c7b312bc166f09f64a1c0d48bee23/lib/trust/permissions.rb#L264-L270
train
ManageIQ/polisher
lib/polisher/gem/state.rb
Polisher.GemState.state
def state(args = {}) return :available if koji_state(args) == :available state = distgit_state(args) return :needs_repo if state == :missing_repo return :needs_branch if state == :missing_branch return :needs_spec if state == :missing_spec return :needs_build if state == :available return :needs_update end
ruby
def state(args = {}) return :available if koji_state(args) == :available state = distgit_state(args) return :needs_repo if state == :missing_repo return :needs_branch if state == :missing_branch return :needs_spec if state == :missing_spec return :needs_build if state == :available return :needs_update end
[ "def", "state", "(", "args", "=", "{", "}", ")", "return", ":available", "if", "koji_state", "(", "args", ")", "==", ":available", "state", "=", "distgit_state", "(", "args", ")", "return", ":needs_repo", "if", "state", "==", ":missing_repo", "return", ":needs_branch", "if", "state", "==", ":missing_branch", "return", ":needs_spec", "if", "state", "==", ":missing_spec", "return", ":needs_build", "if", "state", "==", ":available", "return", ":needs_update", "end" ]
Return the 'state' of the gem as inferred by the targets which there are versions for. If optional :check argument is specified, version analysis will be restricted to targets satisfying the specified gem dependency requirements
[ "Return", "the", "state", "of", "the", "gem", "as", "inferred", "by", "the", "targets", "which", "there", "are", "versions", "for", "." ]
8c19023c72573999c9dc53ec2e2a3eef11a9531e
https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/state.rb#L75-L84
train
Merovex/verku
lib/verku/source_list.rb
Verku.SourceList.entries
def entries Dir.entries(source).sort.each_with_object([]) do |entry, buffer| buffer << source.join(entry) if valid_entry?(entry) end end
ruby
def entries Dir.entries(source).sort.each_with_object([]) do |entry, buffer| buffer << source.join(entry) if valid_entry?(entry) end end
[ "def", "entries", "Dir", ".", "entries", "(", "source", ")", ".", "sort", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "entry", ",", "buffer", "|", "buffer", "<<", "source", ".", "join", "(", "entry", ")", "if", "valid_entry?", "(", "entry", ")", "end", "end" ]
Return a list of all recognized files.
[ "Return", "a", "list", "of", "all", "recognized", "files", "." ]
3d247449ec5192d584943c5552f284679a37e3c0
https://github.com/Merovex/verku/blob/3d247449ec5192d584943c5552f284679a37e3c0/lib/verku/source_list.rb#L48-L52
train
Merovex/verku
lib/verku/source_list.rb
Verku.SourceList.valid_directory?
def valid_directory?(entry) File.directory?(source.join(entry)) && !IGNORE_DIR.include?(File.basename(entry)) end
ruby
def valid_directory?(entry) File.directory?(source.join(entry)) && !IGNORE_DIR.include?(File.basename(entry)) end
[ "def", "valid_directory?", "(", "entry", ")", "File", ".", "directory?", "(", "source", ".", "join", "(", "entry", ")", ")", "&&", "!", "IGNORE_DIR", ".", "include?", "(", "File", ".", "basename", "(", "entry", ")", ")", "end" ]
Check if path is a valid directory.
[ "Check", "if", "path", "is", "a", "valid", "directory", "." ]
3d247449ec5192d584943c5552f284679a37e3c0
https://github.com/Merovex/verku/blob/3d247449ec5192d584943c5552f284679a37e3c0/lib/verku/source_list.rb#L62-L64
train
Merovex/verku
lib/verku/source_list.rb
Verku.SourceList.valid_file?
def valid_file?(entry) ext = File.extname(entry).gsub(/\./, "").downcase File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES end
ruby
def valid_file?(entry) ext = File.extname(entry).gsub(/\./, "").downcase File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES end
[ "def", "valid_file?", "(", "entry", ")", "ext", "=", "File", ".", "extname", "(", "entry", ")", ".", "gsub", "(", "/", "\\.", "/", ",", "\"\"", ")", ".", "downcase", "File", ".", "file?", "(", "source", ".", "join", "(", "entry", ")", ")", "&&", "EXTENSIONS", ".", "include?", "(", "ext", ")", "&&", "entry", "!~", "IGNORE_FILES", "end" ]
Check if path is a valid file.
[ "Check", "if", "path", "is", "a", "valid", "file", "." ]
3d247449ec5192d584943c5552f284679a37e3c0
https://github.com/Merovex/verku/blob/3d247449ec5192d584943c5552f284679a37e3c0/lib/verku/source_list.rb#L68-L71
train
andrba/hungryform
lib/hungryform/form.rb
HungryForm.Form.validate
def validate is_valid = true pages.each do |page| # Loop through pages to get all errors is_valid = false if page.invalid? end is_valid end
ruby
def validate is_valid = true pages.each do |page| # Loop through pages to get all errors is_valid = false if page.invalid? end is_valid end
[ "def", "validate", "is_valid", "=", "true", "pages", ".", "each", "do", "|", "page", "|", "is_valid", "=", "false", "if", "page", ".", "invalid?", "end", "is_valid", "end" ]
Entire form validation. Loops through the form pages and validates each page individually.
[ "Entire", "form", "validation", ".", "Loops", "through", "the", "form", "pages", "and", "validates", "each", "page", "individually", "." ]
d9d9dad9d8409323910372372c3c7672bd8bf478
https://github.com/andrba/hungryform/blob/d9d9dad9d8409323910372372c3c7672bd8bf478/lib/hungryform/form.rb#L63-L72
train
andrba/hungryform
lib/hungryform/form.rb
HungryForm.Form.values
def values active_elements = elements.select do |_, el| el.is_a? Elements::Base::ActiveElement end active_elements.each_with_object({}) do |(name, el), o| o[name.to_sym] = el.value end end
ruby
def values active_elements = elements.select do |_, el| el.is_a? Elements::Base::ActiveElement end active_elements.each_with_object({}) do |(name, el), o| o[name.to_sym] = el.value end end
[ "def", "values", "active_elements", "=", "elements", ".", "select", "do", "|", "_", ",", "el", "|", "el", ".", "is_a?", "Elements", "::", "Base", "::", "ActiveElement", "end", "active_elements", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "name", ",", "el", ")", ",", "o", "|", "o", "[", "name", ".", "to_sym", "]", "=", "el", ".", "value", "end", "end" ]
Create a hash of form elements values
[ "Create", "a", "hash", "of", "form", "elements", "values" ]
d9d9dad9d8409323910372372c3c7672bd8bf478
https://github.com/andrba/hungryform/blob/d9d9dad9d8409323910372372c3c7672bd8bf478/lib/hungryform/form.rb#L98-L106
train
razor-x/config_curator
lib/config_curator/cli.rb
ConfigCurator.CLI.install
def install(manifest = 'manifest.yml') unless File.exist? manifest logger.fatal { "Manifest file '#{manifest}' does not exist." } return false end collection.load_manifest manifest result = options[:dryrun] ? collection.install? : collection.install msg = install_message(result, options[:dryrun]) result ? logger.info(msg) : logger.error(msg) result end
ruby
def install(manifest = 'manifest.yml') unless File.exist? manifest logger.fatal { "Manifest file '#{manifest}' does not exist." } return false end collection.load_manifest manifest result = options[:dryrun] ? collection.install? : collection.install msg = install_message(result, options[:dryrun]) result ? logger.info(msg) : logger.error(msg) result end
[ "def", "install", "(", "manifest", "=", "'manifest.yml'", ")", "unless", "File", ".", "exist?", "manifest", "logger", ".", "fatal", "{", "\"Manifest file '#{manifest}' does not exist.\"", "}", "return", "false", "end", "collection", ".", "load_manifest", "manifest", "result", "=", "options", "[", ":dryrun", "]", "?", "collection", ".", "install?", ":", "collection", ".", "install", "msg", "=", "install_message", "(", "result", ",", "options", "[", ":dryrun", "]", ")", "result", "?", "logger", ".", "info", "(", "msg", ")", ":", "logger", ".", "error", "(", "msg", ")", "result", "end" ]
Installs the collection. @param manifest [String] path to the manifest file to use @return [Boolean] value of {Collection#install} or {Collection#install?}
[ "Installs", "the", "collection", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/cli.rb#L20-L32
train
ksylvest/attached
lib/attached.rb
Attached.ClassMethods.number_to_size
def number_to_size(number, options = {}) return if number == 0.0 / 1.0 return if number == 1.0 / 0.0 singular = options[:singular] || 1 base = options[:base] || 1024 units = options[:units] || ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"] exponent = (Math.log(number) / Math.log(base)).floor number /= base ** exponent unit = units[exponent] number == singular ? unit.gsub!(/s$/, '') : unit.gsub!(/$/, 's') "#{number} #{unit}" end
ruby
def number_to_size(number, options = {}) return if number == 0.0 / 1.0 return if number == 1.0 / 0.0 singular = options[:singular] || 1 base = options[:base] || 1024 units = options[:units] || ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"] exponent = (Math.log(number) / Math.log(base)).floor number /= base ** exponent unit = units[exponent] number == singular ? unit.gsub!(/s$/, '') : unit.gsub!(/$/, 's') "#{number} #{unit}" end
[ "def", "number_to_size", "(", "number", ",", "options", "=", "{", "}", ")", "return", "if", "number", "==", "0.0", "/", "1.0", "return", "if", "number", "==", "1.0", "/", "0.0", "singular", "=", "options", "[", ":singular", "]", "||", "1", "base", "=", "options", "[", ":base", "]", "||", "1024", "units", "=", "options", "[", ":units", "]", "||", "[", "\"byte\"", ",", "\"kilobyte\"", ",", "\"megabyte\"", ",", "\"gigabyte\"", ",", "\"terabyte\"", ",", "\"petabyte\"", "]", "exponent", "=", "(", "Math", ".", "log", "(", "number", ")", "/", "Math", ".", "log", "(", "base", ")", ")", ".", "floor", "number", "/=", "base", "**", "exponent", "unit", "=", "units", "[", "exponent", "]", "number", "==", "singular", "?", "unit", ".", "gsub!", "(", "/", "/", ",", "''", ")", ":", "unit", ".", "gsub!", "(", "/", "/", ",", "'s'", ")", "\"#{number} #{unit}\"", "end" ]
Convert a number to a human readable size. Usage: number_to_size(1) # 1 byte number_to_size(2) # 2 bytes number_to_size(1024) # 1 kilobyte number_to_size(2048) # 2 kilobytes
[ "Convert", "a", "number", "to", "a", "human", "readable", "size", "." ]
6ef5681efd94807d334b12d8229b57ac472a6576
https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached.rb#L134-L150
train
BinaryStorms/civic-sip-ruby-sdk
lib/civic_sip_sdk/client.rb
CivicSIPSdk.Client.exchange_code
def exchange_code(jwt_token:) json_body_str = JSON.generate('authToken' => jwt_token) response = HTTParty.post( "#{BASE_URL}/#{@config.env}/#{AUTH_CODE_PATH}", headers: { 'Content-Type' => MIMETYPE_JSON, 'Accept' => MIMETYPE_JSON, 'Content-Length' => json_body_str.size.to_s, 'Authorization' => authorization_header(body: json_body_str) }, body: json_body_str ) unless response.code == 200 raise StandardError.new( "Failed to exchange JWT token. HTTP status: #{response.code}, response body: #{response.body}" ) end res_payload = JSON.parse(response.body) extract_user_data(response: res_payload) end
ruby
def exchange_code(jwt_token:) json_body_str = JSON.generate('authToken' => jwt_token) response = HTTParty.post( "#{BASE_URL}/#{@config.env}/#{AUTH_CODE_PATH}", headers: { 'Content-Type' => MIMETYPE_JSON, 'Accept' => MIMETYPE_JSON, 'Content-Length' => json_body_str.size.to_s, 'Authorization' => authorization_header(body: json_body_str) }, body: json_body_str ) unless response.code == 200 raise StandardError.new( "Failed to exchange JWT token. HTTP status: #{response.code}, response body: #{response.body}" ) end res_payload = JSON.parse(response.body) extract_user_data(response: res_payload) end
[ "def", "exchange_code", "(", "jwt_token", ":", ")", "json_body_str", "=", "JSON", ".", "generate", "(", "'authToken'", "=>", "jwt_token", ")", "response", "=", "HTTParty", ".", "post", "(", "\"#{BASE_URL}/#{@config.env}/#{AUTH_CODE_PATH}\"", ",", "headers", ":", "{", "'Content-Type'", "=>", "MIMETYPE_JSON", ",", "'Accept'", "=>", "MIMETYPE_JSON", ",", "'Content-Length'", "=>", "json_body_str", ".", "size", ".", "to_s", ",", "'Authorization'", "=>", "authorization_header", "(", "body", ":", "json_body_str", ")", "}", ",", "body", ":", "json_body_str", ")", "unless", "response", ".", "code", "==", "200", "raise", "StandardError", ".", "new", "(", "\"Failed to exchange JWT token. HTTP status: #{response.code}, response body: #{response.body}\"", ")", "end", "res_payload", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "extract_user_data", "(", "response", ":", "res_payload", ")", "end" ]
Creates a client @param config [CivicSIPSdk::AppConfig] app_config that sets all the parameters of the client Exchange authorization code in the form of a JWT Token for the user data requested in the scope request. @param jwt_token [String] a JWT token that contains the authorization code @return [CivicSIPSdk::UserData] user data returned from SIP
[ "Creates", "a", "client" ]
330f01409500b30129691e9990da69e57bd6fbf4
https://github.com/BinaryStorms/civic-sip-ruby-sdk/blob/330f01409500b30129691e9990da69e57bd6fbf4/lib/civic_sip_sdk/client.rb#L34-L56
train
kontena/opto
lib/opto/option.rb
Opto.Option.skip?
def skip? return false unless has_group? return true if group.any_true?(skip_if) return true unless group.all_true?(only_if) false end
ruby
def skip? return false unless has_group? return true if group.any_true?(skip_if) return true unless group.all_true?(only_if) false end
[ "def", "skip?", "return", "false", "unless", "has_group?", "return", "true", "if", "group", ".", "any_true?", "(", "skip_if", ")", "return", "true", "unless", "group", ".", "all_true?", "(", "only_if", ")", "false", "end" ]
Returns true if this field should not be processed because of the conditionals @return [Boolean]
[ "Returns", "true", "if", "this", "field", "should", "not", "be", "processed", "because", "of", "the", "conditionals" ]
7be243226fd2dc6beca61f49379894115396a424
https://github.com/kontena/opto/blob/7be243226fd2dc6beca61f49379894115396a424/lib/opto/option.rb#L163-L168
train
kontena/opto
lib/opto/option.rb
Opto.Option.resolvers
def resolvers @resolvers ||= from.merge(default: self).map { |origin, hint| { origin: origin, hint: hint, resolver: ((has_group? && group.resolvers[origin]) || Resolver.for(origin)) } } end
ruby
def resolvers @resolvers ||= from.merge(default: self).map { |origin, hint| { origin: origin, hint: hint, resolver: ((has_group? && group.resolvers[origin]) || Resolver.for(origin)) } } end
[ "def", "resolvers", "@resolvers", "||=", "from", ".", "merge", "(", "default", ":", "self", ")", ".", "map", "{", "|", "origin", ",", "hint", "|", "{", "origin", ":", "origin", ",", "hint", ":", "hint", ",", "resolver", ":", "(", "(", "has_group?", "&&", "group", ".", "resolvers", "[", "origin", "]", ")", "||", "Resolver", ".", "for", "(", "origin", ")", ")", "}", "}", "end" ]
Accessor to defined resolvers for this option. @return [Array<Opto::Resolver>]
[ "Accessor", "to", "defined", "resolvers", "for", "this", "option", "." ]
7be243226fd2dc6beca61f49379894115396a424
https://github.com/kontena/opto/blob/7be243226fd2dc6beca61f49379894115396a424/lib/opto/option.rb#L205-L207
train
hsribei/goalie
lib/goalie.rb
Goalie.CustomErrorPages.rescue_action_locally
def rescue_action_locally(request, exception) # TODO this should probably move to the controller, that is, have # http error codes map directly to controller actions, then let # controller handle different exception classes however it wants rescue_actions = Hash.new('diagnostics') rescue_actions.update({ 'ActionView::MissingTemplate' => 'missing_template', 'ActionController::RoutingError' => 'routing_error', 'AbstractController::ActionNotFound' => 'unknown_action', 'ActionView::Template::Error' => 'template_error' }) error_params = { :request => request, :exception => exception, :application_trace => application_trace(exception), :framework_trace => framework_trace(exception), :full_trace => full_trace(exception) } request.env['goalie.error_params'] = error_params action = rescue_actions[exception.class.name] response = LocalErrorsController.action(action).call(request.env).last render(status_code(exception), response.body) end
ruby
def rescue_action_locally(request, exception) # TODO this should probably move to the controller, that is, have # http error codes map directly to controller actions, then let # controller handle different exception classes however it wants rescue_actions = Hash.new('diagnostics') rescue_actions.update({ 'ActionView::MissingTemplate' => 'missing_template', 'ActionController::RoutingError' => 'routing_error', 'AbstractController::ActionNotFound' => 'unknown_action', 'ActionView::Template::Error' => 'template_error' }) error_params = { :request => request, :exception => exception, :application_trace => application_trace(exception), :framework_trace => framework_trace(exception), :full_trace => full_trace(exception) } request.env['goalie.error_params'] = error_params action = rescue_actions[exception.class.name] response = LocalErrorsController.action(action).call(request.env).last render(status_code(exception), response.body) end
[ "def", "rescue_action_locally", "(", "request", ",", "exception", ")", "rescue_actions", "=", "Hash", ".", "new", "(", "'diagnostics'", ")", "rescue_actions", ".", "update", "(", "{", "'ActionView::MissingTemplate'", "=>", "'missing_template'", ",", "'ActionController::RoutingError'", "=>", "'routing_error'", ",", "'AbstractController::ActionNotFound'", "=>", "'unknown_action'", ",", "'ActionView::Template::Error'", "=>", "'template_error'", "}", ")", "error_params", "=", "{", ":request", "=>", "request", ",", ":exception", "=>", "exception", ",", ":application_trace", "=>", "application_trace", "(", "exception", ")", ",", ":framework_trace", "=>", "framework_trace", "(", "exception", ")", ",", ":full_trace", "=>", "full_trace", "(", "exception", ")", "}", "request", ".", "env", "[", "'goalie.error_params'", "]", "=", "error_params", "action", "=", "rescue_actions", "[", "exception", ".", "class", ".", "name", "]", "response", "=", "LocalErrorsController", ".", "action", "(", "action", ")", ".", "call", "(", "request", ".", "env", ")", ".", "last", "render", "(", "status_code", "(", "exception", ")", ",", "response", ".", "body", ")", "end" ]
Render detailed diagnostics for unhandled exceptions rescued from a controller action.
[ "Render", "detailed", "diagnostics", "for", "unhandled", "exceptions", "rescued", "from", "a", "controller", "action", "." ]
9095585ec1790f6bb423b763dc0bfa7b013139dc
https://github.com/hsribei/goalie/blob/9095585ec1790f6bb423b763dc0bfa7b013139dc/lib/goalie.rb#L79-L101
train
opengovernment/govkit
lib/gov_kit/resource.rb
GovKit.Resource.find_resource_in_modules
def find_resource_in_modules(resource_name, ancestors) if namespace = ancestors.detect { |a| a.constants.include?(resource_name.to_sym) } return namespace.const_get(resource_name) else raise NameError, "Namespace for #{namespace} not found" end end
ruby
def find_resource_in_modules(resource_name, ancestors) if namespace = ancestors.detect { |a| a.constants.include?(resource_name.to_sym) } return namespace.const_get(resource_name) else raise NameError, "Namespace for #{namespace} not found" end end
[ "def", "find_resource_in_modules", "(", "resource_name", ",", "ancestors", ")", "if", "namespace", "=", "ancestors", ".", "detect", "{", "|", "a", "|", "a", ".", "constants", ".", "include?", "(", "resource_name", ".", "to_sym", ")", "}", "return", "namespace", ".", "const_get", "(", "resource_name", ")", "else", "raise", "NameError", ",", "\"Namespace for #{namespace} not found\"", "end", "end" ]
Searches each module in +ancestors+ for members named +resource_name+ Returns the named resource Throws a NameError if none of the resources in the list contains +resource_name+
[ "Searches", "each", "module", "in", "+", "ancestors", "+", "for", "members", "named", "+", "resource_name", "+", "Returns", "the", "named", "resource", "Throws", "a", "NameError", "if", "none", "of", "the", "resources", "in", "the", "list", "contains", "+", "resource_name", "+" ]
6e1864ef173109dbb1cfadedb19e69849f8ed226
https://github.com/opengovernment/govkit/blob/6e1864ef173109dbb1cfadedb19e69849f8ed226/lib/gov_kit/resource.rb#L146-L152
train
opengovernment/govkit
lib/gov_kit/resource.rb
GovKit.Resource.find_or_create_resource_for
def find_or_create_resource_for(name) resource_name = name.to_s.gsub(/^[_\-+]/,'').gsub(/^(\-?\d)/, "n#{$1}").gsub(/(\s|-)/, '').camelize if self.class.parents.size > 1 find_resource_in_modules(resource_name, self.class.parents) else self.class.const_get(resource_name) end rescue NameError if self.class.const_defined?(resource_name) resource = self.class.const_get(resource_name) else resource = self.class.const_set(resource_name, Class.new(GovKit::Resource)) end resource end
ruby
def find_or_create_resource_for(name) resource_name = name.to_s.gsub(/^[_\-+]/,'').gsub(/^(\-?\d)/, "n#{$1}").gsub(/(\s|-)/, '').camelize if self.class.parents.size > 1 find_resource_in_modules(resource_name, self.class.parents) else self.class.const_get(resource_name) end rescue NameError if self.class.const_defined?(resource_name) resource = self.class.const_get(resource_name) else resource = self.class.const_set(resource_name, Class.new(GovKit::Resource)) end resource end
[ "def", "find_or_create_resource_for", "(", "name", ")", "resource_name", "=", "name", ".", "to_s", ".", "gsub", "(", "/", "\\-", "/", ",", "''", ")", ".", "gsub", "(", "/", "\\-", "\\d", "/", ",", "\"n#{$1}\"", ")", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", ".", "camelize", "if", "self", ".", "class", ".", "parents", ".", "size", ">", "1", "find_resource_in_modules", "(", "resource_name", ",", "self", ".", "class", ".", "parents", ")", "else", "self", ".", "class", ".", "const_get", "(", "resource_name", ")", "end", "rescue", "NameError", "if", "self", ".", "class", ".", "const_defined?", "(", "resource_name", ")", "resource", "=", "self", ".", "class", ".", "const_get", "(", "resource_name", ")", "else", "resource", "=", "self", ".", "class", ".", "const_set", "(", "resource_name", ",", "Class", ".", "new", "(", "GovKit", "::", "Resource", ")", ")", "end", "resource", "end" ]
Searches the GovKit module for a resource with the name +name+, cleaned and camelized Returns that resource. If the resource isn't found, it's created.
[ "Searches", "the", "GovKit", "module", "for", "a", "resource", "with", "the", "name", "+", "name", "+", "cleaned", "and", "camelized", "Returns", "that", "resource", ".", "If", "the", "resource", "isn", "t", "found", "it", "s", "created", "." ]
6e1864ef173109dbb1cfadedb19e69849f8ed226
https://github.com/opengovernment/govkit/blob/6e1864ef173109dbb1cfadedb19e69849f8ed226/lib/gov_kit/resource.rb#L158-L172
train
koraktor/rubikon
lib/rubikon/argument_vector.rb
Rubikon.ArgumentVector.command!
def command!(commands) command = nil command_index = 0 each_with_index do |arg, i| break if arg == '--' command = commands[arg.to_sym] unless command.nil? command_index = i delete_at i break end end delete '--' command ||= commands[:__default] return command, command_index end
ruby
def command!(commands) command = nil command_index = 0 each_with_index do |arg, i| break if arg == '--' command = commands[arg.to_sym] unless command.nil? command_index = i delete_at i break end end delete '--' command ||= commands[:__default] return command, command_index end
[ "def", "command!", "(", "commands", ")", "command", "=", "nil", "command_index", "=", "0", "each_with_index", "do", "|", "arg", ",", "i", "|", "break", "if", "arg", "==", "'--'", "command", "=", "commands", "[", "arg", ".", "to_sym", "]", "unless", "command", ".", "nil?", "command_index", "=", "i", "delete_at", "i", "break", "end", "end", "delete", "'--'", "command", "||=", "commands", "[", ":__default", "]", "return", "command", ",", "command_index", "end" ]
Gets the command to use from the list of arguments passed to the application. The first argument matching a command name or alias will cause the corresponding command to be selected. The command and all arguments equal to '--' will be removed from the array. @param [Hash<Symbol, Command>] commands A list of available commands @return [Command] The command found in the argument list @return [Fixnum] The position of the command in the argument list
[ "Gets", "the", "command", "to", "use", "from", "the", "list", "of", "arguments", "passed", "to", "the", "application", ".", "The", "first", "argument", "matching", "a", "command", "name", "or", "alias", "will", "cause", "the", "corresponding", "command", "to", "be", "selected", "." ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/argument_vector.rb#L26-L44
train
koraktor/rubikon
lib/rubikon/argument_vector.rb
Rubikon.ArgumentVector.expand!
def expand! each_with_index do |arg, i| next if !arg.start_with?('-') self[i] = arg.split('=', 2) next if arg.start_with?('--') self[i] = arg[1..-1].split('').uniq.map { |a| '-' + a } end flatten! end
ruby
def expand! each_with_index do |arg, i| next if !arg.start_with?('-') self[i] = arg.split('=', 2) next if arg.start_with?('--') self[i] = arg[1..-1].split('').uniq.map { |a| '-' + a } end flatten! end
[ "def", "expand!", "each_with_index", "do", "|", "arg", ",", "i", "|", "next", "if", "!", "arg", ".", "start_with?", "(", "'-'", ")", "self", "[", "i", "]", "=", "arg", ".", "split", "(", "'='", ",", "2", ")", "next", "if", "arg", ".", "start_with?", "(", "'--'", ")", "self", "[", "i", "]", "=", "arg", "[", "1", "..", "-", "1", "]", ".", "split", "(", "''", ")", ".", "uniq", ".", "map", "{", "|", "a", "|", "'-'", "+", "a", "}", "end", "flatten!", "end" ]
Turns arguments using a special syntax into arguments that are parseable. Single character parameters may be joined together like '-dv'. This method will split them into separate parameters like '-d -v'. Additionally a parameter argument may be attached to the parameter itself using '=' like '--path=/tmp'. This method will also split them into '--path /tmp'.
[ "Turns", "arguments", "using", "a", "special", "syntax", "into", "arguments", "that", "are", "parseable", "." ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/argument_vector.rb#L54-L62
train
koraktor/rubikon
lib/rubikon/argument_vector.rb
Rubikon.ArgumentVector.params!
def params!(params, pos = 0) active_params = [] to_delete = [] each_with_index do |arg, i| next if i < pos || arg.nil? || !arg.start_with?('-') param = params[(arg.start_with?('--') ? arg[2..-1] : arg[1..1]).to_sym] unless param.nil? to_delete << i scoped_args! param, i + 1 if param.is_a? Option active_params << param end end to_delete.reverse.each { |i| delete_at i } active_params end
ruby
def params!(params, pos = 0) active_params = [] to_delete = [] each_with_index do |arg, i| next if i < pos || arg.nil? || !arg.start_with?('-') param = params[(arg.start_with?('--') ? arg[2..-1] : arg[1..1]).to_sym] unless param.nil? to_delete << i scoped_args! param, i + 1 if param.is_a? Option active_params << param end end to_delete.reverse.each { |i| delete_at i } active_params end
[ "def", "params!", "(", "params", ",", "pos", "=", "0", ")", "active_params", "=", "[", "]", "to_delete", "=", "[", "]", "each_with_index", "do", "|", "arg", ",", "i", "|", "next", "if", "i", "<", "pos", "||", "arg", ".", "nil?", "||", "!", "arg", ".", "start_with?", "(", "'-'", ")", "param", "=", "params", "[", "(", "arg", ".", "start_with?", "(", "'--'", ")", "?", "arg", "[", "2", "..", "-", "1", "]", ":", "arg", "[", "1", "..", "1", "]", ")", ".", "to_sym", "]", "unless", "param", ".", "nil?", "to_delete", "<<", "i", "scoped_args!", "param", ",", "i", "+", "1", "if", "param", ".", "is_a?", "Option", "active_params", "<<", "param", "end", "end", "to_delete", ".", "reverse", ".", "each", "{", "|", "i", "|", "delete_at", "i", "}", "active_params", "end" ]
Selects active parameters from a list of available parameters For every option found in the argument list {#scoped_args!} is called to find the arguments for that option. All parameters found will be removed from the array. @param [Hash<Symbol, Parameter>] params A list of available parameters @param [Fixnum] pos The position of the first argument that should be checked. All arguments ahead of that position will be skipped. @return [Array<Parameter>] Parameters called from the given argument list @see #scoped_args
[ "Selects", "active", "parameters", "from", "a", "list", "of", "available", "parameters" ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/argument_vector.rb#L76-L93
train
koraktor/rubikon
lib/rubikon/argument_vector.rb
Rubikon.ArgumentVector.scoped_args!
def scoped_args!(has_args, pos = 0) to_delete = [] each_with_index do |arg, i| next if i < pos break if arg.start_with?('-') || !has_args.send(:more_args?) to_delete << i has_args.send(:<<, arg) end to_delete.reverse.each { |i| delete_at i } end
ruby
def scoped_args!(has_args, pos = 0) to_delete = [] each_with_index do |arg, i| next if i < pos break if arg.start_with?('-') || !has_args.send(:more_args?) to_delete << i has_args.send(:<<, arg) end to_delete.reverse.each { |i| delete_at i } end
[ "def", "scoped_args!", "(", "has_args", ",", "pos", "=", "0", ")", "to_delete", "=", "[", "]", "each_with_index", "do", "|", "arg", ",", "i", "|", "next", "if", "i", "<", "pos", "break", "if", "arg", ".", "start_with?", "(", "'-'", ")", "||", "!", "has_args", ".", "send", "(", ":more_args?", ")", "to_delete", "<<", "i", "has_args", ".", "send", "(", ":<<", ",", "arg", ")", "end", "to_delete", ".", "reverse", ".", "each", "{", "|", "i", "|", "delete_at", "i", "}", "end" ]
Gets all arguments passed to a specific scope, i.e. a command or an option. All arguments in the scope will be removed from the array. @param [HasArguments] has_args @param [Fixnum] pos The position of the first argument that should be checked. All arguments ahead of that position will be skipped.
[ "Gets", "all", "arguments", "passed", "to", "a", "specific", "scope", "i", ".", "e", ".", "a", "command", "or", "an", "option", "." ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/argument_vector.rb#L103-L115
train
chikamichi/amb
lib/amb/amb.rb
Amb.ClassMethods.solve
def solve(failure_message = "No solution.") amb = self.new yield(amb) rescue Amb::ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb.report(failure_message) end
ruby
def solve(failure_message = "No solution.") amb = self.new yield(amb) rescue Amb::ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb.report(failure_message) end
[ "def", "solve", "(", "failure_message", "=", "\"No solution.\"", ")", "amb", "=", "self", ".", "new", "yield", "(", "amb", ")", "rescue", "Amb", "::", "ExhaustedError", "=>", "ex", "puts", "puts", "\"#{amb.branches_count} branches explored.\"", "if", "$DEBUG", "amb", ".", "report", "(", "failure_message", ")", "end" ]
Class convenience method to search for the first solution to the constraints.
[ "Class", "convenience", "method", "to", "search", "for", "the", "first", "solution", "to", "the", "constraints", "." ]
427f7056ee54406603b30f309e815af637800133
https://github.com/chikamichi/amb/blob/427f7056ee54406603b30f309e815af637800133/lib/amb/amb.rb#L152-L159
train
chikamichi/amb
lib/amb/amb.rb
Amb.ClassMethods.solve_all
def solve_all(failure_message = "No more solutions.") amb = self.new yield(amb) amb.failure rescue Amb::ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb.report(failure_message) end
ruby
def solve_all(failure_message = "No more solutions.") amb = self.new yield(amb) amb.failure rescue Amb::ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb.report(failure_message) end
[ "def", "solve_all", "(", "failure_message", "=", "\"No more solutions.\"", ")", "amb", "=", "self", ".", "new", "yield", "(", "amb", ")", "amb", ".", "failure", "rescue", "Amb", "::", "ExhaustedError", "=>", "ex", "puts", "puts", "\"#{amb.branches_count} branches explored.\"", "if", "$DEBUG", "amb", ".", "report", "(", "failure_message", ")", "end" ]
Class convenience method to search for all the solutions to the constraints.
[ "Class", "convenience", "method", "to", "search", "for", "all", "the", "solutions", "to", "the", "constraints", "." ]
427f7056ee54406603b30f309e815af637800133
https://github.com/chikamichi/amb/blob/427f7056ee54406603b30f309e815af637800133/lib/amb/amb.rb#L164-L172
train
scepticulous/crypto-toolbox
lib/crypto-toolbox/analyzers/ecb_string_appender.rb
Analyzers.EcbStringAppender.calculate_block_size
def calculate_block_size char_amount = 1 base_length = @oracle.encipher(DUMMY * char_amount).length result = nil (1..MAX_KNOWN_BLOCK_LENGTH).each do |length| new_length = @oracle.encipher(DUMMY * char_amount).length if new_length > base_length result = new_length - base_length break end char_amount += 1 end result end
ruby
def calculate_block_size char_amount = 1 base_length = @oracle.encipher(DUMMY * char_amount).length result = nil (1..MAX_KNOWN_BLOCK_LENGTH).each do |length| new_length = @oracle.encipher(DUMMY * char_amount).length if new_length > base_length result = new_length - base_length break end char_amount += 1 end result end
[ "def", "calculate_block_size", "char_amount", "=", "1", "base_length", "=", "@oracle", ".", "encipher", "(", "DUMMY", "*", "char_amount", ")", ".", "length", "result", "=", "nil", "(", "1", "..", "MAX_KNOWN_BLOCK_LENGTH", ")", ".", "each", "do", "|", "length", "|", "new_length", "=", "@oracle", ".", "encipher", "(", "DUMMY", "*", "char_amount", ")", ".", "length", "if", "new_length", ">", "base_length", "result", "=", "new_length", "-", "base_length", "break", "end", "char_amount", "+=", "1", "end", "result", "end" ]
calculate the block size by detecting the growth of the resulting ciphertext by sending messages which length increases by one until a change occurs
[ "calculate", "the", "block", "size", "by", "detecting", "the", "growth", "of", "the", "resulting", "ciphertext", "by", "sending", "messages", "which", "length", "increases", "by", "one", "until", "a", "change", "occurs" ]
cdbe371109e497db2c2af5c1fe0f359612f44816
https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/analyzers/ecb_string_appender.rb#L118-L131
train
ArchimediaZerogroup/KonoUtils
lib/kono_utils/encoder.rb
KonoUtils.Encoder.string_encoder
def string_encoder return string if string.valid_encoding? str = string Encoding.list.each do |e| begin str.force_encoding(e.name) tmp_string = str.encode('UTF-8') return tmp_string if tmp_string.valid_encoding? rescue Rails.logger.debug { "Rescue -> #{e.name}" } if defined?(::Rails) end end impossible_encoding string end
ruby
def string_encoder return string if string.valid_encoding? str = string Encoding.list.each do |e| begin str.force_encoding(e.name) tmp_string = str.encode('UTF-8') return tmp_string if tmp_string.valid_encoding? rescue Rails.logger.debug { "Rescue -> #{e.name}" } if defined?(::Rails) end end impossible_encoding string end
[ "def", "string_encoder", "return", "string", "if", "string", ".", "valid_encoding?", "str", "=", "string", "Encoding", ".", "list", ".", "each", "do", "|", "e", "|", "begin", "str", ".", "force_encoding", "(", "e", ".", "name", ")", "tmp_string", "=", "str", ".", "encode", "(", "'UTF-8'", ")", "return", "tmp_string", "if", "tmp_string", ".", "valid_encoding?", "rescue", "Rails", ".", "logger", ".", "debug", "{", "\"Rescue -> #{e.name}\"", "}", "if", "defined?", "(", "::", "Rails", ")", "end", "end", "impossible_encoding", "string", "end" ]
Funzione di encoding semplice
[ "Funzione", "di", "encoding", "semplice" ]
a255a30b65e4e0f01cd6236d991da4fd13c64fc6
https://github.com/ArchimediaZerogroup/KonoUtils/blob/a255a30b65e4e0f01cd6236d991da4fd13c64fc6/lib/kono_utils/encoder.rb#L24-L40
train
cbot/push0r
lib/push0r/APNS/ApnsService.rb
Push0r.ApnsService.get_feedback
def get_feedback tokens = [] begin setup_ssl(true) rescue SocketError => e puts "Error: #{e}" return tokens end if IO.select([@ssl], nil, nil, 1) while (line = @ssl.read(38)) f = line.unpack('N1n1H64') time = Time.at(f[0]) token = f[2].scan(/.{8}/).join(' ') tokens << token end end close_ssl return tokens end
ruby
def get_feedback tokens = [] begin setup_ssl(true) rescue SocketError => e puts "Error: #{e}" return tokens end if IO.select([@ssl], nil, nil, 1) while (line = @ssl.read(38)) f = line.unpack('N1n1H64') time = Time.at(f[0]) token = f[2].scan(/.{8}/).join(' ') tokens << token end end close_ssl return tokens end
[ "def", "get_feedback", "tokens", "=", "[", "]", "begin", "setup_ssl", "(", "true", ")", "rescue", "SocketError", "=>", "e", "puts", "\"Error: #{e}\"", "return", "tokens", "end", "if", "IO", ".", "select", "(", "[", "@ssl", "]", ",", "nil", ",", "nil", ",", "1", ")", "while", "(", "line", "=", "@ssl", ".", "read", "(", "38", ")", ")", "f", "=", "line", ".", "unpack", "(", "'N1n1H64'", ")", "time", "=", "Time", ".", "at", "(", "f", "[", "0", "]", ")", "token", "=", "f", "[", "2", "]", ".", "scan", "(", "/", "/", ")", ".", "join", "(", "' '", ")", "tokens", "<<", "token", "end", "end", "close_ssl", "return", "tokens", "end" ]
Calls the APNS feedback service and returns an array of expired push tokens @return [Array<String>] an array of expired push tokens
[ "Calls", "the", "APNS", "feedback", "service", "and", "returns", "an", "array", "of", "expired", "push", "tokens" ]
07eb7bece1f251608529dea0d7a93af1444ffeb6
https://github.com/cbot/push0r/blob/07eb7bece1f251608529dea0d7a93af1444ffeb6/lib/push0r/APNS/ApnsService.rb#L83-L105
train
ideonetwork/lato-core
app/cells/lato_core/elements/pagination/cell.rb
LatoCore.Elements::Pagination::Cell.generate_page_link
def generate_page_link page_number url = core__add_param_to_url(@args[:url], @args[:param], page_number) if @args[:extra_params] @args[:extra_params].each do |key, value| url = core__add_param_to_url(url, key, value) end end url end
ruby
def generate_page_link page_number url = core__add_param_to_url(@args[:url], @args[:param], page_number) if @args[:extra_params] @args[:extra_params].each do |key, value| url = core__add_param_to_url(url, key, value) end end url end
[ "def", "generate_page_link", "page_number", "url", "=", "core__add_param_to_url", "(", "@args", "[", ":url", "]", ",", "@args", "[", ":param", "]", ",", "page_number", ")", "if", "@args", "[", ":extra_params", "]", "@args", "[", ":extra_params", "]", ".", "each", "do", "|", "key", ",", "value", "|", "url", "=", "core__add_param_to_url", "(", "url", ",", "key", ",", "value", ")", "end", "end", "url", "end" ]
This function generate the link to go to a specific page number
[ "This", "function", "generate", "the", "link", "to", "go", "to", "a", "specific", "page", "number" ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/elements/pagination/cell.rb#L56-L64
train
JulianNicholls/gosu_enhanced-gem
lib/gosu_enhanced/size.rb
GosuEnhanced.Size.inflate!
def inflate!(by_w, by_h = nil) return inflate_by_size(by_w) if by_w.respond_to? :width validate(by_w, by_h) @width += by_w @height += by_h self end
ruby
def inflate!(by_w, by_h = nil) return inflate_by_size(by_w) if by_w.respond_to? :width validate(by_w, by_h) @width += by_w @height += by_h self end
[ "def", "inflate!", "(", "by_w", ",", "by_h", "=", "nil", ")", "return", "inflate_by_size", "(", "by_w", ")", "if", "by_w", ".", "respond_to?", ":width", "validate", "(", "by_w", ",", "by_h", ")", "@width", "+=", "by_w", "@height", "+=", "by_h", "self", "end" ]
INcrease the dimensions of the current Size in the width direction by +by_w+ and in the height direction by +by_h+. by_w and by_h can be a Fixnum, or another Size.
[ "INcrease", "the", "dimensions", "of", "the", "current", "Size", "in", "the", "width", "direction", "by", "+", "by_w", "+", "and", "in", "the", "height", "direction", "by", "+", "by_h", "+", "." ]
07b5258458c4c3c315f697c8d5da839a93eb2c67
https://github.com/JulianNicholls/gosu_enhanced-gem/blob/07b5258458c4c3c315f697c8d5da839a93eb2c67/lib/gosu_enhanced/size.rb#L46-L55
train
JulianNicholls/gosu_enhanced-gem
lib/gosu_enhanced/size.rb
GosuEnhanced.Size.deflate!
def deflate!(by_w, by_h = nil) if by_w.respond_to? :width inflate!(-by_w.width, -by_w.height) else inflate!(-by_w, -by_h) end end
ruby
def deflate!(by_w, by_h = nil) if by_w.respond_to? :width inflate!(-by_w.width, -by_w.height) else inflate!(-by_w, -by_h) end end
[ "def", "deflate!", "(", "by_w", ",", "by_h", "=", "nil", ")", "if", "by_w", ".", "respond_to?", ":width", "inflate!", "(", "-", "by_w", ".", "width", ",", "-", "by_w", ".", "height", ")", "else", "inflate!", "(", "-", "by_w", ",", "-", "by_h", ")", "end", "end" ]
DEcrease the dimensions of the current Size in the width direction by +by_w+ and in the height direction by +by_h+. by_w and by_h can be a Fixnum, or another Size.
[ "DEcrease", "the", "dimensions", "of", "the", "current", "Size", "in", "the", "width", "direction", "by", "+", "by_w", "+", "and", "in", "the", "height", "direction", "by", "+", "by_h", "+", "." ]
07b5258458c4c3c315f697c8d5da839a93eb2c67
https://github.com/JulianNicholls/gosu_enhanced-gem/blob/07b5258458c4c3c315f697c8d5da839a93eb2c67/lib/gosu_enhanced/size.rb#L62-L68
train
JulianNicholls/gosu_enhanced-gem
lib/gosu_enhanced/size.rb
GosuEnhanced.Size.inflate_by_size
def inflate_by_size(sz) width = sz.width height = sz.height validate(width, height) @width += width @height += height self end
ruby
def inflate_by_size(sz) width = sz.width height = sz.height validate(width, height) @width += width @height += height self end
[ "def", "inflate_by_size", "(", "sz", ")", "width", "=", "sz", ".", "width", "height", "=", "sz", ".", "height", "validate", "(", "width", ",", "height", ")", "@width", "+=", "width", "@height", "+=", "height", "self", "end" ]
Change the dimensions using the dimensions of another Size.
[ "Change", "the", "dimensions", "using", "the", "dimensions", "of", "another", "Size", "." ]
07b5258458c4c3c315f697c8d5da839a93eb2c67
https://github.com/JulianNicholls/gosu_enhanced-gem/blob/07b5258458c4c3c315f697c8d5da839a93eb2c67/lib/gosu_enhanced/size.rb#L93-L102
train
ideonetwork/lato-core
lib/lato_core/interfaces/application.rb
LatoCore.Interface::Application.core__get_application_gems
def core__get_application_gems gems = {} Bundler.load.specs.each do |spec| gems[spec.name] = spec.version end gems end
ruby
def core__get_application_gems gems = {} Bundler.load.specs.each do |spec| gems[spec.name] = spec.version end gems end
[ "def", "core__get_application_gems", "gems", "=", "{", "}", "Bundler", ".", "load", ".", "specs", ".", "each", "do", "|", "spec", "|", "gems", "[", "spec", ".", "name", "]", "=", "spec", ".", "version", "end", "gems", "end" ]
This function return the list of gems used by the application.
[ "This", "function", "return", "the", "list", "of", "gems", "used", "by", "the", "application", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/application.rb#L13-L19
train
ideonetwork/lato-core
lib/lato_core/interfaces/application.rb
LatoCore.Interface::Application.core__get_application_logo_sidebar_path
def core__get_application_logo_sidebar_path dir = "#{core__get_application_root_path}/app/assets/images/lato/" if File.exist?("#{dir}/logo_sidebar.svg") return 'lato/logo_sidebar.svg' elsif File.exist?("#{dir}/logo_sidebar.png") return 'lato/logo_sidebar.png' elsif File.exist?("#{dir}/logo_sidebar.jpg") return 'lato/logo_sidebar.jpg' elsif File.exist?("#{dir}/logo_sidebar.gif") return 'lato/logo_sidebar.gif' end core__get_application_logo_path end
ruby
def core__get_application_logo_sidebar_path dir = "#{core__get_application_root_path}/app/assets/images/lato/" if File.exist?("#{dir}/logo_sidebar.svg") return 'lato/logo_sidebar.svg' elsif File.exist?("#{dir}/logo_sidebar.png") return 'lato/logo_sidebar.png' elsif File.exist?("#{dir}/logo_sidebar.jpg") return 'lato/logo_sidebar.jpg' elsif File.exist?("#{dir}/logo_sidebar.gif") return 'lato/logo_sidebar.gif' end core__get_application_logo_path end
[ "def", "core__get_application_logo_sidebar_path", "dir", "=", "\"#{core__get_application_root_path}/app/assets/images/lato/\"", "if", "File", ".", "exist?", "(", "\"#{dir}/logo_sidebar.svg\"", ")", "return", "'lato/logo_sidebar.svg'", "elsif", "File", ".", "exist?", "(", "\"#{dir}/logo_sidebar.png\"", ")", "return", "'lato/logo_sidebar.png'", "elsif", "File", ".", "exist?", "(", "\"#{dir}/logo_sidebar.jpg\"", ")", "return", "'lato/logo_sidebar.jpg'", "elsif", "File", ".", "exist?", "(", "\"#{dir}/logo_sidebar.gif\"", ")", "return", "'lato/logo_sidebar.gif'", "end", "core__get_application_logo_path", "end" ]
This function return the path of the application logo for the sidebar.
[ "This", "function", "return", "the", "path", "of", "the", "application", "logo", "for", "the", "sidebar", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/application.rb#L27-L39
train
koraktor/rubikon
lib/rubikon/command.rb
Rubikon.Command.help
def help(show_usage = true) help = '' if show_usage help << " #{name}" if name != :__default @params.values.uniq.sort_by {|a| a.name.to_s }.each do |param| help << ' [' ([param.name] + param.aliases).each_with_index do |name, index| name = name.to_s help << '|' if index > 0 help << '-' if name.size > 1 help << "-#{name}" end help << ' ...' if param.is_a?(Option) help << ']' end end help << "\n\n#{description}" unless description.nil? help_flags = {} help_options = {} params.each_value do |param| if param.is_a? Flag help_flags[param.name.to_s] = param else help_options[param.name.to_s] = param end end param_name = lambda { |name| "#{name.size > 1 ? '-' : ' '}-#{name}" } unless help_flags.empty? && help_options.empty? max_param_length = (help_flags.keys + help_options.keys). max_by { |a| a.size }.size + 2 end unless help_flags.empty? help << "\n\nFlags:" help_flags.sort_by { |name, param| name }.each do |name, param| help << "\n #{param_name.call(name).ljust(max_param_length)}" help << " #{param.description}" unless param.description.nil? end end unless help_options.empty? help << "\n\nOptions:\n" help_options.sort_by { |name, param| name }.each do |name, param| help << " #{param_name.call(name).ljust(max_param_length)} ..." help << " #{param.description}" unless param.description.nil? help << "\n" end end help end
ruby
def help(show_usage = true) help = '' if show_usage help << " #{name}" if name != :__default @params.values.uniq.sort_by {|a| a.name.to_s }.each do |param| help << ' [' ([param.name] + param.aliases).each_with_index do |name, index| name = name.to_s help << '|' if index > 0 help << '-' if name.size > 1 help << "-#{name}" end help << ' ...' if param.is_a?(Option) help << ']' end end help << "\n\n#{description}" unless description.nil? help_flags = {} help_options = {} params.each_value do |param| if param.is_a? Flag help_flags[param.name.to_s] = param else help_options[param.name.to_s] = param end end param_name = lambda { |name| "#{name.size > 1 ? '-' : ' '}-#{name}" } unless help_flags.empty? && help_options.empty? max_param_length = (help_flags.keys + help_options.keys). max_by { |a| a.size }.size + 2 end unless help_flags.empty? help << "\n\nFlags:" help_flags.sort_by { |name, param| name }.each do |name, param| help << "\n #{param_name.call(name).ljust(max_param_length)}" help << " #{param.description}" unless param.description.nil? end end unless help_options.empty? help << "\n\nOptions:\n" help_options.sort_by { |name, param| name }.each do |name, param| help << " #{param_name.call(name).ljust(max_param_length)} ..." help << " #{param.description}" unless param.description.nil? help << "\n" end end help end
[ "def", "help", "(", "show_usage", "=", "true", ")", "help", "=", "''", "if", "show_usage", "help", "<<", "\" #{name}\"", "if", "name", "!=", ":__default", "@params", ".", "values", ".", "uniq", ".", "sort_by", "{", "|", "a", "|", "a", ".", "name", ".", "to_s", "}", ".", "each", "do", "|", "param", "|", "help", "<<", "' ['", "(", "[", "param", ".", "name", "]", "+", "param", ".", "aliases", ")", ".", "each_with_index", "do", "|", "name", ",", "index", "|", "name", "=", "name", ".", "to_s", "help", "<<", "'|'", "if", "index", ">", "0", "help", "<<", "'-'", "if", "name", ".", "size", ">", "1", "help", "<<", "\"-#{name}\"", "end", "help", "<<", "' ...'", "if", "param", ".", "is_a?", "(", "Option", ")", "help", "<<", "']'", "end", "end", "help", "<<", "\"\\n\\n#{description}\"", "unless", "description", ".", "nil?", "help_flags", "=", "{", "}", "help_options", "=", "{", "}", "params", ".", "each_value", "do", "|", "param", "|", "if", "param", ".", "is_a?", "Flag", "help_flags", "[", "param", ".", "name", ".", "to_s", "]", "=", "param", "else", "help_options", "[", "param", ".", "name", ".", "to_s", "]", "=", "param", "end", "end", "param_name", "=", "lambda", "{", "|", "name", "|", "\"#{name.size > 1 ? '-' : ' '}-#{name}\"", "}", "unless", "help_flags", ".", "empty?", "&&", "help_options", ".", "empty?", "max_param_length", "=", "(", "help_flags", ".", "keys", "+", "help_options", ".", "keys", ")", ".", "max_by", "{", "|", "a", "|", "a", ".", "size", "}", ".", "size", "+", "2", "end", "unless", "help_flags", ".", "empty?", "help", "<<", "\"\\n\\nFlags:\"", "help_flags", ".", "sort_by", "{", "|", "name", ",", "param", "|", "name", "}", ".", "each", "do", "|", "name", ",", "param", "|", "help", "<<", "\"\\n #{param_name.call(name).ljust(max_param_length)}\"", "help", "<<", "\" #{param.description}\"", "unless", "param", ".", "description", ".", "nil?", "end", "end", "unless", "help_options", ".", "empty?", "help", "<<", "\"\\n\\nOptions:\\n\"", "help_options", ".", "sort_by", "{", "|", "name", ",", "param", "|", "name", "}", ".", "each", "do", "|", "name", ",", "param", "|", "help", "<<", "\" #{param_name.call(name).ljust(max_param_length)} ...\"", "help", "<<", "\" #{param.description}\"", "unless", "param", ".", "description", ".", "nil?", "help", "<<", "\"\\n\"", "end", "end", "help", "end" ]
Create a new application command with the given name with a reference to the app it belongs to @param [Application::Base] app The application this command belongs to @param [Symbol, #to_sym] name The name of this command, used in application arguments @param options (see HasArguments#initialize) @param [Proc] block The code block which should be executed by this command @raise [ArgumentError] if the given application object isn't a Rubikon application @raise [BlockMissingError] if no command code block is given and a command file does not exist Generate help for this command @param [Boolean] show_usage If +true+, the returned String will also include usage information @return [String] The contents of the help screen for this command @since 0.6.0
[ "Create", "a", "new", "application", "command", "with", "the", "given", "name", "with", "a", "reference", "to", "the", "app", "it", "belongs", "to" ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/command.rb#L64-L119
train
koraktor/rubikon
lib/rubikon/command.rb
Rubikon.Command.add_param
def add_param(parameter) if parameter.is_a? Hash parameter.each do |alias_name, name| alias_name = alias_name.to_sym name = name.to_sym parameter = @params[name] if parameter.nil? @params[alias_name] = name else parameter.aliases << alias_name @params[alias_name] = parameter end end else raise ArgumentError unless parameter.is_a? Parameter @params.each do |name, param| if param == parameter.name parameter.aliases << name @params[name] = parameter end end @params[parameter.name] = parameter end end
ruby
def add_param(parameter) if parameter.is_a? Hash parameter.each do |alias_name, name| alias_name = alias_name.to_sym name = name.to_sym parameter = @params[name] if parameter.nil? @params[alias_name] = name else parameter.aliases << alias_name @params[alias_name] = parameter end end else raise ArgumentError unless parameter.is_a? Parameter @params.each do |name, param| if param == parameter.name parameter.aliases << name @params[name] = parameter end end @params[parameter.name] = parameter end end
[ "def", "add_param", "(", "parameter", ")", "if", "parameter", ".", "is_a?", "Hash", "parameter", ".", "each", "do", "|", "alias_name", ",", "name", "|", "alias_name", "=", "alias_name", ".", "to_sym", "name", "=", "name", ".", "to_sym", "parameter", "=", "@params", "[", "name", "]", "if", "parameter", ".", "nil?", "@params", "[", "alias_name", "]", "=", "name", "else", "parameter", ".", "aliases", "<<", "alias_name", "@params", "[", "alias_name", "]", "=", "parameter", "end", "end", "else", "raise", "ArgumentError", "unless", "parameter", ".", "is_a?", "Parameter", "@params", ".", "each", "do", "|", "name", ",", "param", "|", "if", "param", "==", "parameter", ".", "name", "parameter", ".", "aliases", "<<", "name", "@params", "[", "name", "]", "=", "parameter", "end", "end", "@params", "[", "parameter", ".", "name", "]", "=", "parameter", "end", "end" ]
Add a new parameter for this command @param [Parameter, Hash] parameter The parameter to add to this command. This might also be a Hash where every key will be an alias to the corresponding value, e.g. <tt>{ :alias => :parameter }</tt>. @see Parameter
[ "Add", "a", "new", "parameter", "for", "this", "command" ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/command.rb#L140-L163
train
koraktor/rubikon
lib/rubikon/command.rb
Rubikon.Command.method_missing
def method_missing(name, *args, &block) if args.empty? && !block_given? if @params.key?(name) return @params[name] else active_params.each do |param| return param.send(name) if param.respond_to_missing?(name) end end end super end
ruby
def method_missing(name, *args, &block) if args.empty? && !block_given? if @params.key?(name) return @params[name] else active_params.each do |param| return param.send(name) if param.respond_to_missing?(name) end end end super end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "args", ".", "empty?", "&&", "!", "block_given?", "if", "@params", ".", "key?", "(", "name", ")", "return", "@params", "[", "name", "]", "else", "active_params", ".", "each", "do", "|", "param", "|", "return", "param", ".", "send", "(", "name", ")", "if", "param", ".", "respond_to_missing?", "(", "name", ")", "end", "end", "end", "super", "end" ]
If a parameter with the specified method name exists, a call to that method will return the value of the parameter. @param (see ClassMethods#method_missing) @example option :user, [:who] command :hello, [:mood] do puts "Hello #{user.who}" puts "I feel #{mood}" end
[ "If", "a", "parameter", "with", "the", "specified", "method", "name", "exists", "a", "call", "to", "that", "method", "will", "return", "the", "value", "of", "the", "parameter", "." ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/command.rb#L176-L188
train
koraktor/rubikon
lib/rubikon/command.rb
Rubikon.Command.reset
def reset super @params.values.uniq.each do |param| param.send(:reset) if param.is_a? Parameter end end
ruby
def reset super @params.values.uniq.each do |param| param.send(:reset) if param.is_a? Parameter end end
[ "def", "reset", "super", "@params", ".", "values", ".", "uniq", ".", "each", "do", "|", "param", "|", "param", ".", "send", "(", ":reset", ")", "if", "param", ".", "is_a?", "Parameter", "end", "end" ]
Resets this command to its initial state @see HasArguments#reset @since 0.4.0
[ "Resets", "this", "command", "to", "its", "initial", "state" ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/command.rb#L194-L199
train
koraktor/rubikon
lib/rubikon/command.rb
Rubikon.Command.respond_to_missing?
def respond_to_missing?(name, include_private = false) @params.key?(name) || active_params.any? { |param| param.respond_to_missing?(name) } || super end
ruby
def respond_to_missing?(name, include_private = false) @params.key?(name) || active_params.any? { |param| param.respond_to_missing?(name) } || super end
[ "def", "respond_to_missing?", "(", "name", ",", "include_private", "=", "false", ")", "@params", ".", "key?", "(", "name", ")", "||", "active_params", ".", "any?", "{", "|", "param", "|", "param", ".", "respond_to_missing?", "(", "name", ")", "}", "||", "super", "end" ]
Checks whether a parameter with the given name exists for this command This is used to determine if a method call would successfully return the value of a parameter. @return +true+ if named parameter with the specified name exists @see #method_missing
[ "Checks", "whether", "a", "parameter", "with", "the", "given", "name", "exists", "for", "this", "command" ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/command.rb#L208-L212
train
ksylvest/attached
lib/attached/attatcher.rb
Attached.Attatcher.validations
def validations name = @name @klass.send(:validates_each, name) do |record, attr, value| record.send(name).errors.each do |error| record.errors.add(name, error) end end end
ruby
def validations name = @name @klass.send(:validates_each, name) do |record, attr, value| record.send(name).errors.each do |error| record.errors.add(name, error) end end end
[ "def", "validations", "name", "=", "@name", "@klass", ".", "send", "(", ":validates_each", ",", "name", ")", "do", "|", "record", ",", "attr", ",", "value", "|", "record", ".", "send", "(", "name", ")", ".", "errors", ".", "each", "do", "|", "error", "|", "record", ".", "errors", ".", "add", "(", "name", ",", "error", ")", "end", "end", "end" ]
Forward validations. Usage: attacher.validations
[ "Forward", "validations", "." ]
6ef5681efd94807d334b12d8229b57ac472a6576
https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached/attatcher.rb#L131-L138
train
wordjelly/Auth
config/initializers/omniauth.rb
OmniAuth.Strategy.on_any_path?
def on_any_path?(paths) path_found = false paths.each do |path| path_found = on_path?(path) ? true : path_found end return path_found end
ruby
def on_any_path?(paths) path_found = false paths.each do |path| path_found = on_path?(path) ? true : path_found end return path_found end
[ "def", "on_any_path?", "(", "paths", ")", "path_found", "=", "false", "paths", ".", "each", "do", "|", "path", "|", "path_found", "=", "on_path?", "(", "path", ")", "?", "true", ":", "path_found", "end", "return", "path_found", "end" ]
a modification of the on path method to check if we are on any of the defined request or callback paths. tests each of the provided paths to see if we are on it.
[ "a", "modification", "of", "the", "on", "path", "method", "to", "check", "if", "we", "are", "on", "any", "of", "the", "defined", "request", "or", "callback", "paths", ".", "tests", "each", "of", "the", "provided", "paths", "to", "see", "if", "we", "are", "on", "it", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/config/initializers/omniauth.rb#L11-L17
train
ksylvest/attached
lib/attached/attachment.rb
Attached.Attachment.save
def save self.queue.each do |style, file| path = self.path(style) self.storage.save(file, path) if file and path end self.purge.each do |path| self.storage.destroy(path) end @purge = [] @queue = {} end
ruby
def save self.queue.each do |style, file| path = self.path(style) self.storage.save(file, path) if file and path end self.purge.each do |path| self.storage.destroy(path) end @purge = [] @queue = {} end
[ "def", "save", "self", ".", "queue", ".", "each", "do", "|", "style", ",", "file", "|", "path", "=", "self", ".", "path", "(", "style", ")", "self", ".", "storage", ".", "save", "(", "file", ",", "path", ")", "if", "file", "and", "path", "end", "self", ".", "purge", ".", "each", "do", "|", "path", "|", "self", ".", "storage", ".", "destroy", "(", "path", ")", "end", "@purge", "=", "[", "]", "@queue", "=", "{", "}", "end" ]
Save an attachment. Usage: @object.avatar.save
[ "Save", "an", "attachment", "." ]
6ef5681efd94807d334b12d8229b57ac472a6576
https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached/attachment.rb#L181-L191
train
ksylvest/attached
lib/attached/attachment.rb
Attached.Attachment.destroy
def destroy if attached? self.storage.destroy(self.path) self.styles.each do |style, options| self.storage.destroy(self.path(style)) end end @purge = [] @queue = {} end
ruby
def destroy if attached? self.storage.destroy(self.path) self.styles.each do |style, options| self.storage.destroy(self.path(style)) end end @purge = [] @queue = {} end
[ "def", "destroy", "if", "attached?", "self", ".", "storage", ".", "destroy", "(", "self", ".", "path", ")", "self", ".", "styles", ".", "each", "do", "|", "style", ",", "options", "|", "self", ".", "storage", ".", "destroy", "(", "self", ".", "path", "(", "style", ")", ")", "end", "end", "@purge", "=", "[", "]", "@queue", "=", "{", "}", "end" ]
Destroy an attachment. Usage: @object.avatar.destroy
[ "Destroy", "an", "attachment", "." ]
6ef5681efd94807d334b12d8229b57ac472a6576
https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached/attachment.rb#L199-L208
train
ksylvest/attached
lib/attached/attachment.rb
Attached.Attachment.url
def url(style = self.default) path = self.path(style) host = self.host host = self.aliases[path.hash % self.aliases.count] unless self.aliases.empty? return "#{host}#{path}" end
ruby
def url(style = self.default) path = self.path(style) host = self.host host = self.aliases[path.hash % self.aliases.count] unless self.aliases.empty? return "#{host}#{path}" end
[ "def", "url", "(", "style", "=", "self", ".", "default", ")", "path", "=", "self", ".", "path", "(", "style", ")", "host", "=", "self", ".", "host", "host", "=", "self", ".", "aliases", "[", "path", ".", "hash", "%", "self", ".", "aliases", ".", "count", "]", "unless", "self", ".", "aliases", ".", "empty?", "return", "\"#{host}#{path}\"", "end" ]
Acesss the URL for an attachment. Usage: @object.avatar.url @object.avatar.url(:small) @object.avatar.url(:large)
[ "Acesss", "the", "URL", "for", "an", "attachment", "." ]
6ef5681efd94807d334b12d8229b57ac472a6576
https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached/attachment.rb#L218-L223
train
ksylvest/attached
lib/attached/attachment.rb
Attached.Attachment.path
def path(style = self.default) path = self.attached? ? @path.clone : @missing.clone path.gsub!(/:name/, name.to_s) path.gsub!(/:style/, style.to_s) path.gsub!(/:extension/, extension(style).to_s) path.gsub!(/:identifier/, identifier(style).to_s) return path end
ruby
def path(style = self.default) path = self.attached? ? @path.clone : @missing.clone path.gsub!(/:name/, name.to_s) path.gsub!(/:style/, style.to_s) path.gsub!(/:extension/, extension(style).to_s) path.gsub!(/:identifier/, identifier(style).to_s) return path end
[ "def", "path", "(", "style", "=", "self", ".", "default", ")", "path", "=", "self", ".", "attached?", "?", "@path", ".", "clone", ":", "@missing", ".", "clone", "path", ".", "gsub!", "(", "/", "/", ",", "name", ".", "to_s", ")", "path", ".", "gsub!", "(", "/", "/", ",", "style", ".", "to_s", ")", "path", ".", "gsub!", "(", "/", "/", ",", "extension", "(", "style", ")", ".", "to_s", ")", "path", ".", "gsub!", "(", "/", "/", ",", "identifier", "(", "style", ")", ".", "to_s", ")", "return", "path", "end" ]
Access the path for an attachment. Usage: @object.avatar.url @object.avatar.url(:small) @object.avatar.url(:large)
[ "Access", "the", "path", "for", "an", "attachment", "." ]
6ef5681efd94807d334b12d8229b57ac472a6576
https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached/attachment.rb#L233-L240
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/clients/client_manager.rb
GameOverseer.ClientManager.add
def add(client_id, ip_address) @clients << {client_id: client_id, ip_address: ip_address} GameOverseer::Services.client_connected(client_id, ip_address) GameOverseer::Console.log("ClientManager> client with id '#{client_id}' connected") end
ruby
def add(client_id, ip_address) @clients << {client_id: client_id, ip_address: ip_address} GameOverseer::Services.client_connected(client_id, ip_address) GameOverseer::Console.log("ClientManager> client with id '#{client_id}' connected") end
[ "def", "add", "(", "client_id", ",", "ip_address", ")", "@clients", "<<", "{", "client_id", ":", "client_id", ",", "ip_address", ":", "ip_address", "}", "GameOverseer", "::", "Services", ".", "client_connected", "(", "client_id", ",", "ip_address", ")", "GameOverseer", "::", "Console", ".", "log", "(", "\"ClientManager> client with id '#{client_id}' connected\"", ")", "end" ]
Add client to clients list @param client_id [Integer] @param ip_address [String]
[ "Add", "client", "to", "clients", "list" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/clients/client_manager.rb#L15-L19
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/clients/client_manager.rb
GameOverseer.ClientManager.remove
def remove(client_id) @clients.each do |hash| if hash[:client_id] == client_id @clients.delete(hash) GameOverseer::Services.client_disconnected(client_id) GameOverseer::Console.log("ClientManager> client with id '#{client_id}' disconnected") end end end
ruby
def remove(client_id) @clients.each do |hash| if hash[:client_id] == client_id @clients.delete(hash) GameOverseer::Services.client_disconnected(client_id) GameOverseer::Console.log("ClientManager> client with id '#{client_id}' disconnected") end end end
[ "def", "remove", "(", "client_id", ")", "@clients", ".", "each", "do", "|", "hash", "|", "if", "hash", "[", ":client_id", "]", "==", "client_id", "@clients", ".", "delete", "(", "hash", ")", "GameOverseer", "::", "Services", ".", "client_disconnected", "(", "client_id", ")", "GameOverseer", "::", "Console", ".", "log", "(", "\"ClientManager> client with id '#{client_id}' disconnected\"", ")", "end", "end", "end" ]
Removes client data and disconnects client @param client_id [Integer] ID of client
[ "Removes", "client", "data", "and", "disconnects", "client" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/clients/client_manager.rb#L48-L56
train
eprothro/cassie
lib/cassie/schema/migration/dsl/table_operations.rb
Cassie::Schema::Migration::DSL.TableOperations.create_table
def create_table(table_name, options = {}) table_definition = TableDefinition.new table_definition.define_primary_keys(options[:primary_keys]) if options[:primary_keys] table_definition.define_partition_keys(options[:partition_keys]) if options[:partition_keys] table_definition.define_options(options[:options]) if options[:options] yield table_definition if block_given? announce_operation "create_table(#{table_name})" create_cql = "CREATE TABLE #{table_name} (" create_cql << table_definition.to_create_cql create_cql << ")" create_cql << table_definition.options announce_suboperation create_cql execute create_cql end
ruby
def create_table(table_name, options = {}) table_definition = TableDefinition.new table_definition.define_primary_keys(options[:primary_keys]) if options[:primary_keys] table_definition.define_partition_keys(options[:partition_keys]) if options[:partition_keys] table_definition.define_options(options[:options]) if options[:options] yield table_definition if block_given? announce_operation "create_table(#{table_name})" create_cql = "CREATE TABLE #{table_name} (" create_cql << table_definition.to_create_cql create_cql << ")" create_cql << table_definition.options announce_suboperation create_cql execute create_cql end
[ "def", "create_table", "(", "table_name", ",", "options", "=", "{", "}", ")", "table_definition", "=", "TableDefinition", ".", "new", "table_definition", ".", "define_primary_keys", "(", "options", "[", ":primary_keys", "]", ")", "if", "options", "[", ":primary_keys", "]", "table_definition", ".", "define_partition_keys", "(", "options", "[", ":partition_keys", "]", ")", "if", "options", "[", ":partition_keys", "]", "table_definition", ".", "define_options", "(", "options", "[", ":options", "]", ")", "if", "options", "[", ":options", "]", "yield", "table_definition", "if", "block_given?", "announce_operation", "\"create_table(#{table_name})\"", "create_cql", "=", "\"CREATE TABLE #{table_name} (\"", "create_cql", "<<", "table_definition", ".", "to_create_cql", "create_cql", "<<", "\")\"", "create_cql", "<<", "table_definition", ".", "options", "announce_suboperation", "create_cql", "execute", "create_cql", "end" ]
Creates a new table in the keyspace options: - :primary_keys: single value or array (for compound primary keys). If not defined, some column must be chosen as primary key in the table definition.
[ "Creates", "a", "new", "table", "in", "the", "keyspace" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migration/dsl/table_operations.rb#L15-L33
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/server/renet_server.rb
GameOverseer.ENetServer.transmit
def transmit(client_id, message, reliable = false, channel = ChannelManager::CHAT) @server.send_packet(client_id, message, reliable, channel) end
ruby
def transmit(client_id, message, reliable = false, channel = ChannelManager::CHAT) @server.send_packet(client_id, message, reliable, channel) end
[ "def", "transmit", "(", "client_id", ",", "message", ",", "reliable", "=", "false", ",", "channel", "=", "ChannelManager", "::", "CHAT", ")", "@server", ".", "send_packet", "(", "client_id", ",", "message", ",", "reliable", ",", "channel", ")", "end" ]
send message to a specific client @param client_id [Integer] ID of client @param message [String] message to be sent to client @param reliable [Boolean] whether or not the packet is guaranteed to be received by the client @param channel [Integer] what channel to send on
[ "send", "message", "to", "a", "specific", "client" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/server/renet_server.rb#L74-L76
train
cyberarm/rewrite-gameoverseer
lib/gameoverseer/server/renet_server.rb
GameOverseer.ENetServer.broadcast
def broadcast(message, reliable = false, channel = ChannelManager::CHAT) @server.broadcast_packet(message, reliable, channel) end
ruby
def broadcast(message, reliable = false, channel = ChannelManager::CHAT) @server.broadcast_packet(message, reliable, channel) end
[ "def", "broadcast", "(", "message", ",", "reliable", "=", "false", ",", "channel", "=", "ChannelManager", "::", "CHAT", ")", "@server", ".", "broadcast_packet", "(", "message", ",", "reliable", ",", "channel", ")", "end" ]
send message to all connected clients @param message [String] message to be sent to clients @param reliable [Boolean] whether or not the packet is guaranteed to be received by the clients @param channel [Integer] what channel to send on
[ "send", "message", "to", "all", "connected", "clients" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/server/renet_server.rb#L82-L84
train
Falkor/falkorlib
lib/falkorlib/versioning.rb
FalkorLib.Versioning.bump
def bump(oldversion, level) major = minor = patch = 0 if oldversion =~ /^(\d+)\.(\d+)\.(\d+)$/ major = Regexp.last_match(1).to_i minor = Regexp.last_match(2).to_i patch = Regexp.last_match(3).to_i end case level.to_sym when :major major += 1 minor = 0 patch = 0 when :minor minor += 1 patch = 0 when :patch patch += 1 end version = [major, minor, patch].compact.join('.') version end
ruby
def bump(oldversion, level) major = minor = patch = 0 if oldversion =~ /^(\d+)\.(\d+)\.(\d+)$/ major = Regexp.last_match(1).to_i minor = Regexp.last_match(2).to_i patch = Regexp.last_match(3).to_i end case level.to_sym when :major major += 1 minor = 0 patch = 0 when :minor minor += 1 patch = 0 when :patch patch += 1 end version = [major, minor, patch].compact.join('.') version end
[ "def", "bump", "(", "oldversion", ",", "level", ")", "major", "=", "minor", "=", "patch", "=", "0", "if", "oldversion", "=~", "/", "\\d", "\\.", "\\d", "\\.", "\\d", "/", "major", "=", "Regexp", ".", "last_match", "(", "1", ")", ".", "to_i", "minor", "=", "Regexp", ".", "last_match", "(", "2", ")", ".", "to_i", "patch", "=", "Regexp", ".", "last_match", "(", "3", ")", ".", "to_i", "end", "case", "level", ".", "to_sym", "when", ":major", "major", "+=", "1", "minor", "=", "0", "patch", "=", "0", "when", ":minor", "minor", "+=", "1", "patch", "=", "0", "when", ":patch", "patch", "+=", "1", "end", "version", "=", "[", "major", ",", "minor", ",", "patch", "]", ".", "compact", ".", "join", "(", "'.'", ")", "version", "end" ]
Return a new version number based on @param oldversion the old version (format: x.y.z) @param level the level of bumping (either :major, :minor, :patch)
[ "Return", "a", "new", "version", "number", "based", "on" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/versioning.rb#L164-L184
train
janfoeh/apidiesel
lib/apidiesel/dsl.rb
Apidiesel.Dsl.expects
def expects(&block) builder = ExpectationBuilder.new builder.instance_eval(&block) parameter_validations.concat builder.parameter_validations parameters_to_filter.concat builder.parameters_to_filter end
ruby
def expects(&block) builder = ExpectationBuilder.new builder.instance_eval(&block) parameter_validations.concat builder.parameter_validations parameters_to_filter.concat builder.parameters_to_filter end
[ "def", "expects", "(", "&", "block", ")", "builder", "=", "ExpectationBuilder", ".", "new", "builder", ".", "instance_eval", "(", "&", "block", ")", "parameter_validations", ".", "concat", "builder", ".", "parameter_validations", "parameters_to_filter", ".", "concat", "builder", ".", "parameters_to_filter", "end" ]
Defines the input parameters expected for this API action. @example expects do string :query integer :per_page, :optional => true, :default => 10 end See the {Apidiesel::Dsl::ExpectationBuilder ExpectationBuilder} instance methods for more information on what to use within `expect`. @macro [attach] expects @yield [Apidiesel::Dsl::ExpectationBuilder]
[ "Defines", "the", "input", "parameters", "expected", "for", "this", "API", "action", "." ]
eb334f5744389ebaad19eb1343c4a27b2e3cf2e3
https://github.com/janfoeh/apidiesel/blob/eb334f5744389ebaad19eb1343c4a27b2e3cf2e3/lib/apidiesel/dsl.rb#L16-L21
train
janfoeh/apidiesel
lib/apidiesel/dsl.rb
Apidiesel.Dsl.responds_with
def responds_with(**args, &block) builder = FilterBuilder.new builder.instance_eval(&block) response_filters.concat(builder.response_filters) response_formatters.concat(builder.response_formatters) if args[:unnested_hash] response_formatters << lambda do |_, response| if response.is_a?(Hash) && response.keys.length == 1 response.values.first else response end end end end
ruby
def responds_with(**args, &block) builder = FilterBuilder.new builder.instance_eval(&block) response_filters.concat(builder.response_filters) response_formatters.concat(builder.response_formatters) if args[:unnested_hash] response_formatters << lambda do |_, response| if response.is_a?(Hash) && response.keys.length == 1 response.values.first else response end end end end
[ "def", "responds_with", "(", "**", "args", ",", "&", "block", ")", "builder", "=", "FilterBuilder", ".", "new", "builder", ".", "instance_eval", "(", "&", "block", ")", "response_filters", ".", "concat", "(", "builder", ".", "response_filters", ")", "response_formatters", ".", "concat", "(", "builder", ".", "response_formatters", ")", "if", "args", "[", ":unnested_hash", "]", "response_formatters", "<<", "lambda", "do", "|", "_", ",", "response", "|", "if", "response", ".", "is_a?", "(", "Hash", ")", "&&", "response", ".", "keys", ".", "length", "==", "1", "response", ".", "values", ".", "first", "else", "response", "end", "end", "end", "end" ]
Defines the expected content and format of the response for this API action. @example responds_with do string :user_id end See the {Apidiesel::Dsl::FilterBuilder FilterBuilder} instance methods for more information on what to use within `responds_with`. @macro [attach] responds_with @yield [Apidiesel::Dsl::FilterBuilder]
[ "Defines", "the", "expected", "content", "and", "format", "of", "the", "response", "for", "this", "API", "action", "." ]
eb334f5744389ebaad19eb1343c4a27b2e3cf2e3
https://github.com/janfoeh/apidiesel/blob/eb334f5744389ebaad19eb1343c4a27b2e3cf2e3/lib/apidiesel/dsl.rb#L35-L52
train
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.really_continue?
def really_continue?(default_answer = 'Yes') return if FalkorLib.config[:no_interaction] pattern = (default_answer =~ /yes/i) ? '(Y|n)' : '(y|N)' answer = ask( cyan("=> Do you really want to continue #{pattern}?"), default_answer) exit 0 if answer =~ /n.*/i end
ruby
def really_continue?(default_answer = 'Yes') return if FalkorLib.config[:no_interaction] pattern = (default_answer =~ /yes/i) ? '(Y|n)' : '(y|N)' answer = ask( cyan("=> Do you really want to continue #{pattern}?"), default_answer) exit 0 if answer =~ /n.*/i end
[ "def", "really_continue?", "(", "default_answer", "=", "'Yes'", ")", "return", "if", "FalkorLib", ".", "config", "[", ":no_interaction", "]", "pattern", "=", "(", "default_answer", "=~", "/", "/i", ")", "?", "'(Y|n)'", ":", "'(y|N)'", "answer", "=", "ask", "(", "cyan", "(", "\"=> Do you really want to continue #{pattern}?\"", ")", ",", "default_answer", ")", "exit", "0", "if", "answer", "=~", "/", "/i", "end" ]
Ask whether or not to really continue
[ "Ask", "whether", "or", "not", "to", "really", "continue" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L99-L104
train
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.nice_execute
def nice_execute(cmd) puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}") stdout, stderr, exit_status = Open3.capture3( cmd ) unless stdout.empty? stdout.each_line do |line| print "** [out] #{line}" $stdout.flush end end unless stderr.empty? stderr.each_line do |line| $stderr.print red("** [err] #{line}") $stderr.flush end end exit_status end
ruby
def nice_execute(cmd) puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}") stdout, stderr, exit_status = Open3.capture3( cmd ) unless stdout.empty? stdout.each_line do |line| print "** [out] #{line}" $stdout.flush end end unless stderr.empty? stderr.each_line do |line| $stderr.print red("** [err] #{line}") $stderr.flush end end exit_status end
[ "def", "nice_execute", "(", "cmd", ")", "puts", "bold", "(", "\"[Running] #{cmd.gsub(/^\\s*/, ' ')}\"", ")", "stdout", ",", "stderr", ",", "exit_status", "=", "Open3", ".", "capture3", "(", "cmd", ")", "unless", "stdout", ".", "empty?", "stdout", ".", "each_line", "do", "|", "line", "|", "print", "\"** [out] #{line}\"", "$stdout", ".", "flush", "end", "end", "unless", "stderr", ".", "empty?", "stderr", ".", "each_line", "do", "|", "line", "|", "$stderr", ".", "print", "red", "(", "\"** [err] #{line}\"", ")", "$stderr", ".", "flush", "end", "end", "exit_status", "end" ]
Execute a given command, return exit code and print nicely stdout and stderr
[ "Execute", "a", "given", "command", "return", "exit", "code", "and", "print", "nicely", "stdout", "and", "stderr" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L117-L133
train
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.execute_in_dir
def execute_in_dir(path, cmd) exit_status = 0 Dir.chdir(path) do exit_status = run %( #{cmd} ) end exit_status end
ruby
def execute_in_dir(path, cmd) exit_status = 0 Dir.chdir(path) do exit_status = run %( #{cmd} ) end exit_status end
[ "def", "execute_in_dir", "(", "path", ",", "cmd", ")", "exit_status", "=", "0", "Dir", ".", "chdir", "(", "path", ")", "do", "exit_status", "=", "run", "%( #{cmd} )", "end", "exit_status", "end" ]
Execute in a given directory
[ "Execute", "in", "a", "given", "directory" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L143-L149
train
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.exec_or_exit
def exec_or_exit(cmd) status = execute(cmd) if (status.to_i.nonzero?) error("The command '#{cmd}' failed with exit status #{status.to_i}") end status end
ruby
def exec_or_exit(cmd) status = execute(cmd) if (status.to_i.nonzero?) error("The command '#{cmd}' failed with exit status #{status.to_i}") end status end
[ "def", "exec_or_exit", "(", "cmd", ")", "status", "=", "execute", "(", "cmd", ")", "if", "(", "status", ".", "to_i", ".", "nonzero?", ")", "error", "(", "\"The command '#{cmd}' failed with exit status #{status.to_i}\"", ")", "end", "status", "end" ]
execute_in_dir Execute a given command - exit if status != 0
[ "execute_in_dir", "Execute", "a", "given", "command", "-", "exit", "if", "status", "!", "=", "0" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L152-L158
train
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.select_from
def select_from(list, text = 'Select the index', default_idx = 0, raw_list = list) error "list and raw_list differs in size" if list.size != raw_list.size l = list raw_l = raw_list if list.is_a?(Array) l = raw_l = { 0 => 'Exit' } list.each_with_index do |e, idx| l[idx + 1] = e raw_l[idx + 1] = raw_list[idx] end end puts l.to_yaml answer = ask("=> #{text}", default_idx.to_s) raise SystemExit, 'exiting selection' if answer == '0' raise RangeError, 'Undefined index' if Integer(answer) >= l.length raw_l[Integer(answer)] end
ruby
def select_from(list, text = 'Select the index', default_idx = 0, raw_list = list) error "list and raw_list differs in size" if list.size != raw_list.size l = list raw_l = raw_list if list.is_a?(Array) l = raw_l = { 0 => 'Exit' } list.each_with_index do |e, idx| l[idx + 1] = e raw_l[idx + 1] = raw_list[idx] end end puts l.to_yaml answer = ask("=> #{text}", default_idx.to_s) raise SystemExit, 'exiting selection' if answer == '0' raise RangeError, 'Undefined index' if Integer(answer) >= l.length raw_l[Integer(answer)] end
[ "def", "select_from", "(", "list", ",", "text", "=", "'Select the index'", ",", "default_idx", "=", "0", ",", "raw_list", "=", "list", ")", "error", "\"list and raw_list differs in size\"", "if", "list", ".", "size", "!=", "raw_list", ".", "size", "l", "=", "list", "raw_l", "=", "raw_list", "if", "list", ".", "is_a?", "(", "Array", ")", "l", "=", "raw_l", "=", "{", "0", "=>", "'Exit'", "}", "list", ".", "each_with_index", "do", "|", "e", ",", "idx", "|", "l", "[", "idx", "+", "1", "]", "=", "e", "raw_l", "[", "idx", "+", "1", "]", "=", "raw_list", "[", "idx", "]", "end", "end", "puts", "l", ".", "to_yaml", "answer", "=", "ask", "(", "\"=> #{text}\"", ",", "default_idx", ".", "to_s", ")", "raise", "SystemExit", ",", "'exiting selection'", "if", "answer", "==", "'0'", "raise", "RangeError", ",", "'Undefined index'", "if", "Integer", "(", "answer", ")", ">=", "l", ".", "length", "raw_l", "[", "Integer", "(", "answer", ")", "]", "end" ]
Display a indexed list to select an i
[ "Display", "a", "indexed", "list", "to", "select", "an", "i" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L227-L243
train
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.init_rvm
def init_rvm(rootdir = Dir.pwd, gemset = '') rvm_files = { :version => File.join(rootdir, '.ruby-version'), :gemset => File.join(rootdir, '.ruby-gemset') } unless File.exist?( (rvm_files[:version]).to_s) v = select_from(FalkorLib.config[:rvm][:rubies], "Select RVM ruby to configure for this directory", 3) File.open( rvm_files[:version], 'w') do |f| f.puts v end end unless File.exist?( (rvm_files[:gemset]).to_s) g = (gemset.empty?) ? ask("Enter RVM gemset name for this directory", File.basename(rootdir)) : gemset File.open( rvm_files[:gemset], 'w') do |f| f.puts g end end end
ruby
def init_rvm(rootdir = Dir.pwd, gemset = '') rvm_files = { :version => File.join(rootdir, '.ruby-version'), :gemset => File.join(rootdir, '.ruby-gemset') } unless File.exist?( (rvm_files[:version]).to_s) v = select_from(FalkorLib.config[:rvm][:rubies], "Select RVM ruby to configure for this directory", 3) File.open( rvm_files[:version], 'w') do |f| f.puts v end end unless File.exist?( (rvm_files[:gemset]).to_s) g = (gemset.empty?) ? ask("Enter RVM gemset name for this directory", File.basename(rootdir)) : gemset File.open( rvm_files[:gemset], 'w') do |f| f.puts g end end end
[ "def", "init_rvm", "(", "rootdir", "=", "Dir", ".", "pwd", ",", "gemset", "=", "''", ")", "rvm_files", "=", "{", ":version", "=>", "File", ".", "join", "(", "rootdir", ",", "'.ruby-version'", ")", ",", ":gemset", "=>", "File", ".", "join", "(", "rootdir", ",", "'.ruby-gemset'", ")", "}", "unless", "File", ".", "exist?", "(", "(", "rvm_files", "[", ":version", "]", ")", ".", "to_s", ")", "v", "=", "select_from", "(", "FalkorLib", ".", "config", "[", ":rvm", "]", "[", ":rubies", "]", ",", "\"Select RVM ruby to configure for this directory\"", ",", "3", ")", "File", ".", "open", "(", "rvm_files", "[", ":version", "]", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "puts", "v", "end", "end", "unless", "File", ".", "exist?", "(", "(", "rvm_files", "[", ":gemset", "]", ")", ".", "to_s", ")", "g", "=", "(", "gemset", ".", "empty?", ")", "?", "ask", "(", "\"Enter RVM gemset name for this directory\"", ",", "File", ".", "basename", "(", "rootdir", ")", ")", ":", "gemset", "File", ".", "open", "(", "rvm_files", "[", ":gemset", "]", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "puts", "g", "end", "end", "end" ]
copy_from_template RVM init
[ "copy_from_template", "RVM", "init" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L452-L471
train
Falkor/falkorlib
lib/falkorlib/bootstrap/base.rb
FalkorLib.Bootstrap.select_licence
def select_licence(default_licence = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata][:license], _options = {}) list_license = FalkorLib::Config::Bootstrap::DEFAULTS[:licenses].keys idx = list_license.index(default_licence) unless default_licence.nil? select_from(list_license, 'Select the license index for this project:', (idx.nil?) ? 1 : idx + 1) #licence end
ruby
def select_licence(default_licence = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata][:license], _options = {}) list_license = FalkorLib::Config::Bootstrap::DEFAULTS[:licenses].keys idx = list_license.index(default_licence) unless default_licence.nil? select_from(list_license, 'Select the license index for this project:', (idx.nil?) ? 1 : idx + 1) #licence end
[ "def", "select_licence", "(", "default_licence", "=", "FalkorLib", "::", "Config", "::", "Bootstrap", "::", "DEFAULTS", "[", ":metadata", "]", "[", ":license", "]", ",", "_options", "=", "{", "}", ")", "list_license", "=", "FalkorLib", "::", "Config", "::", "Bootstrap", "::", "DEFAULTS", "[", ":licenses", "]", ".", "keys", "idx", "=", "list_license", ".", "index", "(", "default_licence", ")", "unless", "default_licence", ".", "nil?", "select_from", "(", "list_license", ",", "'Select the license index for this project:'", ",", "(", "idx", ".", "nil?", ")", "?", "1", ":", "idx", "+", "1", ")", "end" ]
select_forge select_licence Select a given licence for the project
[ "select_forge", "select_licence", "Select", "a", "given", "licence", "for", "the", "project" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/bootstrap/base.rb#L459-L467
train