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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
longhotsummer/slaw
lib/slaw/generator.rb
Slaw.ActGenerator.guess_section_number_after_title
def guess_section_number_after_title(text) before = text.scan(/^\w{4,}[^\n]+\n\d+\. /).length after = text.scan(/^\s*\n\d+\. \w{4,}/).length before > after * 1.25 end
ruby
def guess_section_number_after_title(text) before = text.scan(/^\w{4,}[^\n]+\n\d+\. /).length after = text.scan(/^\s*\n\d+\. \w{4,}/).length before > after * 1.25 end
[ "def", "guess_section_number_after_title", "(", "text", ")", "before", "=", "text", ".", "scan", "(", "/", "\\w", "\\n", "\\n", "\\d", "\\.", "/", ")", ".", "length", "after", "=", "text", ".", "scan", "(", "/", "\\s", "\\n", "\\d", "\\.", "\\w", "/", ")", ".", "length", "before", ">", "after", "*", "1.25", "end" ]
Try to determine if section numbers come after titles, rather than before. eg: Section title 1. Section content versus 1. Section title Section content
[ "Try", "to", "determine", "if", "section", "numbers", "come", "after", "titles", "rather", "than", "before", "." ]
cab2a7c74f9d820e64324aaf10328ff9a5c91dbb
https://github.com/longhotsummer/slaw/blob/cab2a7c74f9d820e64324aaf10328ff9a5c91dbb/lib/slaw/generator.rb#L75-L80
train
longhotsummer/slaw
lib/slaw/generator.rb
Slaw.ActGenerator.text_from_act
def text_from_act(doc) # look on the load path for an XSL file for this grammar filename = "/slaw/grammars/#{@grammar}/act_text.xsl" if dir = $LOAD_PATH.find { |p| File.exist?(p + filename) } xslt = Nokogiri::XSLT(File.read(dir + filename)) xslt.transform(doc).child.to_xml else raise "Unable to find text XSL for grammar #{@grammar}: #{fragment}" end end
ruby
def text_from_act(doc) # look on the load path for an XSL file for this grammar filename = "/slaw/grammars/#{@grammar}/act_text.xsl" if dir = $LOAD_PATH.find { |p| File.exist?(p + filename) } xslt = Nokogiri::XSLT(File.read(dir + filename)) xslt.transform(doc).child.to_xml else raise "Unable to find text XSL for grammar #{@grammar}: #{fragment}" end end
[ "def", "text_from_act", "(", "doc", ")", "filename", "=", "\"/slaw/grammars/#{@grammar}/act_text.xsl\"", "if", "dir", "=", "$LOAD_PATH", ".", "find", "{", "|", "p", "|", "File", ".", "exist?", "(", "p", "+", "filename", ")", "}", "xslt", "=", "Nokogiri", "::", "XSLT", "(", "File", ".", "read", "(", "dir", "+", "filename", ")", ")", "xslt", ".", "transform", "(", "doc", ")", ".", "child", ".", "to_xml", "else", "raise", "\"Unable to find text XSL for grammar #{@grammar}: #{fragment}\"", "end", "end" ]
Transform an Akoma Ntoso XML document back into a plain-text version suitable for re-parsing back into XML with no loss of structure.
[ "Transform", "an", "Akoma", "Ntoso", "XML", "document", "back", "into", "a", "plain", "-", "text", "version", "suitable", "for", "re", "-", "parsing", "back", "into", "XML", "with", "no", "loss", "of", "structure", "." ]
cab2a7c74f9d820e64324aaf10328ff9a5c91dbb
https://github.com/longhotsummer/slaw/blob/cab2a7c74f9d820e64324aaf10328ff9a5c91dbb/lib/slaw/generator.rb#L84-L94
train
3scale/3scale_ws_api_for_ruby
lib/3scale/client.rb
ThreeScale.Client.authorize
def authorize(options) extensions = options.delete :extensions creds = creds_params(options) path = "/transactions/authorize.xml" + options_to_params(options, ALL_PARAMS) + '&' + creds headers = extensions_to_header extensions if extensions http_response = @http.get(path, headers: headers) case http_response when Net::HTTPSuccess,Net::HTTPConflict build_authorize_response(http_response.body) when Net::HTTPClientError build_error_response(http_response.body, AuthorizeResponse) else raise ServerError.new(http_response) end end
ruby
def authorize(options) extensions = options.delete :extensions creds = creds_params(options) path = "/transactions/authorize.xml" + options_to_params(options, ALL_PARAMS) + '&' + creds headers = extensions_to_header extensions if extensions http_response = @http.get(path, headers: headers) case http_response when Net::HTTPSuccess,Net::HTTPConflict build_authorize_response(http_response.body) when Net::HTTPClientError build_error_response(http_response.body, AuthorizeResponse) else raise ServerError.new(http_response) end end
[ "def", "authorize", "(", "options", ")", "extensions", "=", "options", ".", "delete", ":extensions", "creds", "=", "creds_params", "(", "options", ")", "path", "=", "\"/transactions/authorize.xml\"", "+", "options_to_params", "(", "options", ",", "ALL_PARAMS", ")", "+", "'&'", "+", "creds", "headers", "=", "extensions_to_header", "extensions", "if", "extensions", "http_response", "=", "@http", ".", "get", "(", "path", ",", "headers", ":", "headers", ")", "case", "http_response", "when", "Net", "::", "HTTPSuccess", ",", "Net", "::", "HTTPConflict", "build_authorize_response", "(", "http_response", ".", "body", ")", "when", "Net", "::", "HTTPClientError", "build_error_response", "(", "http_response", ".", "body", ",", "AuthorizeResponse", ")", "else", "raise", "ServerError", ".", "new", "(", "http_response", ")", "end", "end" ]
Authorize an application. == Parameters Hash with options: service_token:: token granting access to the specified service_id. app_id:: id of the application to authorize. This is required. app_key:: secret key assigned to the application. Required only if application has a key defined. service_id:: id of the service (required if you have more than one service) user_id:: id of an end user. Required only when the application is rate limiting end users. usage:: predicted usage. It is optional. It is a hash where the keys are metrics and the values their predicted usage. Example: {'hits' => 1, 'my_metric' => 100} extensions:: Optional. Hash of extension keys and values. == Return An ThreeScale::AuthorizeResponse object. It's +success?+ method returns true if the authorization is successful, false otherwise. It contains additional information about the status of the usage. See the ThreeScale::AuthorizeResponse for more information. In case of error, the +error_code+ returns code of the error and +error_message+ human readable error description. In case of unexpected internal server error, this method raises a ThreeScale::ServerError exception. == Examples response = client.authorize(:app_id => '1234') if response.success? # All good. Proceed... end
[ "Authorize", "an", "application", "." ]
c4952601a3ad3b6c3e5fda6dffc003bbcaaca3aa
https://github.com/3scale/3scale_ws_api_for_ruby/blob/c4952601a3ad3b6c3e5fda6dffc003bbcaaca3aa/lib/3scale/client.rb#L237-L253
train
3scale/3scale_ws_api_for_ruby
lib/3scale/client.rb
ThreeScale.Client.usage_report
def usage_report(node) period_start = node.at('period_start') period_end = node.at('period_end') { :metric => node['metric'].to_s.strip, :period => node['period'].to_s.strip.to_sym, :period_start => period_start ? period_start.content : '', :period_end => period_end ? period_end.content : '', :current_value => node.at('current_value').content.to_i, :max_value => node.at('max_value').content.to_i } end
ruby
def usage_report(node) period_start = node.at('period_start') period_end = node.at('period_end') { :metric => node['metric'].to_s.strip, :period => node['period'].to_s.strip.to_sym, :period_start => period_start ? period_start.content : '', :period_end => period_end ? period_end.content : '', :current_value => node.at('current_value').content.to_i, :max_value => node.at('max_value').content.to_i } end
[ "def", "usage_report", "(", "node", ")", "period_start", "=", "node", ".", "at", "(", "'period_start'", ")", "period_end", "=", "node", ".", "at", "(", "'period_end'", ")", "{", ":metric", "=>", "node", "[", "'metric'", "]", ".", "to_s", ".", "strip", ",", ":period", "=>", "node", "[", "'period'", "]", ".", "to_s", ".", "strip", ".", "to_sym", ",", ":period_start", "=>", "period_start", "?", "period_start", ".", "content", ":", "''", ",", ":period_end", "=>", "period_end", "?", "period_end", ".", "content", ":", "''", ",", ":current_value", "=>", "node", ".", "at", "(", "'current_value'", ")", ".", "content", ".", "to_i", ",", ":max_value", "=>", "node", ".", "at", "(", "'max_value'", ")", ".", "content", ".", "to_i", "}", "end" ]
It can be a user usage report or an app usage report
[ "It", "can", "be", "a", "user", "usage", "report", "or", "an", "app", "usage", "report" ]
c4952601a3ad3b6c3e5fda6dffc003bbcaaca3aa
https://github.com/3scale/3scale_ws_api_for_ruby/blob/c4952601a3ad3b6c3e5fda6dffc003bbcaaca3aa/lib/3scale/client.rb#L409-L419
train
3scale/3scale_ws_api_for_ruby
lib/3scale/client.rb
ThreeScale.Client.generate_creds_params
def generate_creds_params define_singleton_method :creds_params, if @service_tokens lambda do |options| token = options.delete(:service_token) service_id = options[:service_id] raise ArgumentError, "need to specify a service_token and a service_id" unless token && service_id 'service_token='.freeze + CGI.escape(token) end elsif @provider_key warn DEPRECATION_MSG_PROVIDER_KEY if @warn_deprecated lambda do |_| "provider_key=#{CGI.escape @provider_key}".freeze end else raise ArgumentError, 'missing credentials - either use "service_tokens: true" or specify a provider_key value' end end
ruby
def generate_creds_params define_singleton_method :creds_params, if @service_tokens lambda do |options| token = options.delete(:service_token) service_id = options[:service_id] raise ArgumentError, "need to specify a service_token and a service_id" unless token && service_id 'service_token='.freeze + CGI.escape(token) end elsif @provider_key warn DEPRECATION_MSG_PROVIDER_KEY if @warn_deprecated lambda do |_| "provider_key=#{CGI.escape @provider_key}".freeze end else raise ArgumentError, 'missing credentials - either use "service_tokens: true" or specify a provider_key value' end end
[ "def", "generate_creds_params", "define_singleton_method", ":creds_params", ",", "if", "@service_tokens", "lambda", "do", "|", "options", "|", "token", "=", "options", ".", "delete", "(", ":service_token", ")", "service_id", "=", "options", "[", ":service_id", "]", "raise", "ArgumentError", ",", "\"need to specify a service_token and a service_id\"", "unless", "token", "&&", "service_id", "'service_token='", ".", "freeze", "+", "CGI", ".", "escape", "(", "token", ")", "end", "elsif", "@provider_key", "warn", "DEPRECATION_MSG_PROVIDER_KEY", "if", "@warn_deprecated", "lambda", "do", "|", "_", "|", "\"provider_key=#{CGI.escape @provider_key}\"", ".", "freeze", "end", "else", "raise", "ArgumentError", ",", "'missing credentials - either use \"service_tokens: true\" or specify a provider_key value'", "end", "end" ]
helper to generate the creds_params method
[ "helper", "to", "generate", "the", "creds_params", "method" ]
c4952601a3ad3b6c3e5fda6dffc003bbcaaca3aa
https://github.com/3scale/3scale_ws_api_for_ruby/blob/c4952601a3ad3b6c3e5fda6dffc003bbcaaca3aa/lib/3scale/client.rb#L436-L453
train
nilsding/twittbot
lib/twittbot/gem_ext/twitter/tweet.rb
Twitter.Tweet.reply
def reply(tweet_text, options = {}) return if $bot.nil? or $bot[:client].nil? opts = { reply_all: false }.merge(options) mentions = self.mentioned_users(opts[:reply_all]) result = "@#{mentions.join(" @")} #{tweet_text}"[(0...140)] $bot[:client].update result, in_reply_to_status_id: self.id rescue Twitter::Error => e puts "caught Twitter error while replying: #{e.message}" end
ruby
def reply(tweet_text, options = {}) return if $bot.nil? or $bot[:client].nil? opts = { reply_all: false }.merge(options) mentions = self.mentioned_users(opts[:reply_all]) result = "@#{mentions.join(" @")} #{tweet_text}"[(0...140)] $bot[:client].update result, in_reply_to_status_id: self.id rescue Twitter::Error => e puts "caught Twitter error while replying: #{e.message}" end
[ "def", "reply", "(", "tweet_text", ",", "options", "=", "{", "}", ")", "return", "if", "$bot", ".", "nil?", "or", "$bot", "[", ":client", "]", ".", "nil?", "opts", "=", "{", "reply_all", ":", "false", "}", ".", "merge", "(", "options", ")", "mentions", "=", "self", ".", "mentioned_users", "(", "opts", "[", ":reply_all", "]", ")", "result", "=", "\"@#{mentions.join(\" @\")} #{tweet_text}\"", "[", "(", "0", "...", "140", ")", "]", "$bot", "[", ":client", "]", ".", "update", "result", ",", "in_reply_to_status_id", ":", "self", ".", "id", "rescue", "Twitter", "::", "Error", "=>", "e", "puts", "\"caught Twitter error while replying: #{e.message}\"", "end" ]
Creates a reply to this tweet. @param tweet_text [:String] tweet text @param options [Hash] A customizable set of options. @option options [Boolean] :reply_all (false) Add all users mentioned in the tweet text to the reply.
[ "Creates", "a", "reply", "to", "this", "tweet", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/gem_ext/twitter/tweet.rb#L7-L20
train
nilsding/twittbot
lib/twittbot/gem_ext/twitter/tweet.rb
Twitter.Tweet.mentioned_users
def mentioned_users(reply_all = true, screen_name = $bot[:config][:screen_name]) userlist = [ self.user.screen_name ] if reply_all self.text.scan /@([A-Za-z0-9_]{1,16})/ do |user_name| user_name = user_name[0] userlist << user_name unless userlist.include?(user_name) or screen_name == user_name end end userlist end
ruby
def mentioned_users(reply_all = true, screen_name = $bot[:config][:screen_name]) userlist = [ self.user.screen_name ] if reply_all self.text.scan /@([A-Za-z0-9_]{1,16})/ do |user_name| user_name = user_name[0] userlist << user_name unless userlist.include?(user_name) or screen_name == user_name end end userlist end
[ "def", "mentioned_users", "(", "reply_all", "=", "true", ",", "screen_name", "=", "$bot", "[", ":config", "]", "[", ":screen_name", "]", ")", "userlist", "=", "[", "self", ".", "user", ".", "screen_name", "]", "if", "reply_all", "self", ".", "text", ".", "scan", "/", "/", "do", "|", "user_name", "|", "user_name", "=", "user_name", "[", "0", "]", "userlist", "<<", "user_name", "unless", "userlist", ".", "include?", "(", "user_name", ")", "or", "screen_name", "==", "user_name", "end", "end", "userlist", "end" ]
Scans the tweet text for screen names. @param reply_all [Boolean] Include all users in the reply. @param screen_name [String] The user's screen name (i.e. that one who clicked "Reply") @return [Array] An array of user names.
[ "Scans", "the", "tweet", "text", "for", "screen", "names", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/gem_ext/twitter/tweet.rb#L47-L56
train
nilsding/twittbot
lib/twittbot/gem_ext/twitter/direct_message.rb
Twitter.DirectMessage.reply
def reply(direct_message_text) return if $bot.nil? or $bot[:client].nil? $bot[:client].create_direct_message self.sender.id, direct_message_text rescue Twitter::Error => e puts "caught Twitter error while replying via DM: #{e.message}" end
ruby
def reply(direct_message_text) return if $bot.nil? or $bot[:client].nil? $bot[:client].create_direct_message self.sender.id, direct_message_text rescue Twitter::Error => e puts "caught Twitter error while replying via DM: #{e.message}" end
[ "def", "reply", "(", "direct_message_text", ")", "return", "if", "$bot", ".", "nil?", "or", "$bot", "[", ":client", "]", ".", "nil?", "$bot", "[", ":client", "]", ".", "create_direct_message", "self", ".", "sender", ".", "id", ",", "direct_message_text", "rescue", "Twitter", "::", "Error", "=>", "e", "puts", "\"caught Twitter error while replying via DM: #{e.message}\"", "end" ]
Replies to this direct message. @param direct_message_text [:String] direct message text
[ "Replies", "to", "this", "direct", "message", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/gem_ext/twitter/direct_message.rb#L5-L11
train
gurgeous/sinew
lib/sinew/request.rb
Sinew.Request.perform
def perform validate! party_options = options.dup # merge proxy if proxy = self.proxy addr, port = proxy.split(':') party_options[:http_proxyaddr] = addr party_options[:http_proxyport] = port || 80 end # now merge runtime_options party_options = party_options.merge(sinew.runtime_options.httparty_options) # merge headers headers = sinew.runtime_options.headers headers = headers.merge(party_options[:headers]) if party_options[:headers] party_options[:headers] = headers party_response = HTTParty.send(method, uri, party_options) Response.from_network(self, party_response) end
ruby
def perform validate! party_options = options.dup # merge proxy if proxy = self.proxy addr, port = proxy.split(':') party_options[:http_proxyaddr] = addr party_options[:http_proxyport] = port || 80 end # now merge runtime_options party_options = party_options.merge(sinew.runtime_options.httparty_options) # merge headers headers = sinew.runtime_options.headers headers = headers.merge(party_options[:headers]) if party_options[:headers] party_options[:headers] = headers party_response = HTTParty.send(method, uri, party_options) Response.from_network(self, party_response) end
[ "def", "perform", "validate!", "party_options", "=", "options", ".", "dup", "if", "proxy", "=", "self", ".", "proxy", "addr", ",", "port", "=", "proxy", ".", "split", "(", "':'", ")", "party_options", "[", ":http_proxyaddr", "]", "=", "addr", "party_options", "[", ":http_proxyport", "]", "=", "port", "||", "80", "end", "party_options", "=", "party_options", ".", "merge", "(", "sinew", ".", "runtime_options", ".", "httparty_options", ")", "headers", "=", "sinew", ".", "runtime_options", ".", "headers", "headers", "=", "headers", ".", "merge", "(", "party_options", "[", ":headers", "]", ")", "if", "party_options", "[", ":headers", "]", "party_options", "[", ":headers", "]", "=", "headers", "party_response", "=", "HTTParty", ".", "send", "(", "method", ",", "uri", ",", "party_options", ")", "Response", ".", "from_network", "(", "self", ",", "party_response", ")", "end" ]
run the request, return the result
[ "run", "the", "request", "return", "the", "result" ]
c5a0f027939fedb597c28a8553f63f514584724a
https://github.com/gurgeous/sinew/blob/c5a0f027939fedb597c28a8553f63f514584724a/lib/sinew/request.rb#L36-L58
train
gurgeous/sinew
lib/sinew/request.rb
Sinew.Request.parse_url
def parse_url(url) s = url # remove entities s = HTML_ENTITIES.decode(s) # fix a couple of common encoding bugs s = s.gsub(' ', '%20') s = s.gsub("'", '%27') # append query manually (instead of letting HTTParty handle it) so we can # include it in cache_key query = options.delete(:query) if query.present? q = HTTParty::HashConversions.to_params(query) separator = s.include?('?') ? '&' : '?' s = "#{s}#{separator}#{q}" end URI.parse(s) end
ruby
def parse_url(url) s = url # remove entities s = HTML_ENTITIES.decode(s) # fix a couple of common encoding bugs s = s.gsub(' ', '%20') s = s.gsub("'", '%27') # append query manually (instead of letting HTTParty handle it) so we can # include it in cache_key query = options.delete(:query) if query.present? q = HTTParty::HashConversions.to_params(query) separator = s.include?('?') ? '&' : '?' s = "#{s}#{separator}#{q}" end URI.parse(s) end
[ "def", "parse_url", "(", "url", ")", "s", "=", "url", "s", "=", "HTML_ENTITIES", ".", "decode", "(", "s", ")", "s", "=", "s", ".", "gsub", "(", "' '", ",", "'%20'", ")", "s", "=", "s", ".", "gsub", "(", "\"'\"", ",", "'%27'", ")", "query", "=", "options", ".", "delete", "(", ":query", ")", "if", "query", ".", "present?", "q", "=", "HTTParty", "::", "HashConversions", ".", "to_params", "(", "query", ")", "separator", "=", "s", ".", "include?", "(", "'?'", ")", "?", "'&'", ":", "'?'", "s", "=", "\"#{s}#{separator}#{q}\"", "end", "URI", ".", "parse", "(", "s", ")", "end" ]
We accept sloppy urls and attempt to clean them up
[ "We", "accept", "sloppy", "urls", "and", "attempt", "to", "clean", "them", "up" ]
c5a0f027939fedb597c28a8553f63f514584724a
https://github.com/gurgeous/sinew/blob/c5a0f027939fedb597c28a8553f63f514584724a/lib/sinew/request.rb#L61-L81
train
nilsding/twittbot
lib/twittbot/botpart.rb
Twittbot.BotPart.cmd
def cmd(name, options = {}, &block) raise "Command already exists: #{name}" if $bot[:commands].include? name raise "Command name does not contain only alphanumerical characters" unless name.to_s.match /\A[A-Za-z0-9]+\z/ opts = { admin: true }.merge(options) $bot[:commands][name] ||= { admin: opts[:admin], block: block } end
ruby
def cmd(name, options = {}, &block) raise "Command already exists: #{name}" if $bot[:commands].include? name raise "Command name does not contain only alphanumerical characters" unless name.to_s.match /\A[A-Za-z0-9]+\z/ opts = { admin: true }.merge(options) $bot[:commands][name] ||= { admin: opts[:admin], block: block } end
[ "def", "cmd", "(", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "\"Command already exists: #{name}\"", "if", "$bot", "[", ":commands", "]", ".", "include?", "name", "raise", "\"Command name does not contain only alphanumerical characters\"", "unless", "name", ".", "to_s", ".", "match", "/", "\\A", "\\z", "/", "opts", "=", "{", "admin", ":", "true", "}", ".", "merge", "(", "options", ")", "$bot", "[", ":commands", "]", "[", "name", "]", "||=", "{", "admin", ":", "opts", "[", ":admin", "]", ",", "block", ":", "block", "}", "end" ]
Defines a new direct message command. @param name [Symbol] The name of the command. Can only contain alphanumerical characters. The recommended maximum length is 4 characters. @param options [Hash] A customizable set of options. @option options [Boolean] :admin (true) Require admin status for this command.
[ "Defines", "a", "new", "direct", "message", "command", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/botpart.rb#L80-L92
train
nilsding/twittbot
lib/twittbot/botpart.rb
Twittbot.BotPart.task
def task(name, options = {}, &block) name = name.to_s.downcase.to_sym task_re = /\A[a-z0-9.:-_]+\z/ raise "Task already exists: #{name}" if $bot[:tasks].include?(name) raise "Task name does not match regexp #{task_re.to_s}" unless name.to_s.match(task_re) opts = { desc: '' }.merge(options) $bot[:tasks][name] ||= { block: block, desc: opts[:desc] } end
ruby
def task(name, options = {}, &block) name = name.to_s.downcase.to_sym task_re = /\A[a-z0-9.:-_]+\z/ raise "Task already exists: #{name}" if $bot[:tasks].include?(name) raise "Task name does not match regexp #{task_re.to_s}" unless name.to_s.match(task_re) opts = { desc: '' }.merge(options) $bot[:tasks][name] ||= { block: block, desc: opts[:desc] } end
[ "def", "task", "(", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "name", "=", "name", ".", "to_s", ".", "downcase", ".", "to_sym", "task_re", "=", "/", "\\A", "\\z", "/", "raise", "\"Task already exists: #{name}\"", "if", "$bot", "[", ":tasks", "]", ".", "include?", "(", "name", ")", "raise", "\"Task name does not match regexp #{task_re.to_s}\"", "unless", "name", ".", "to_s", ".", "match", "(", "task_re", ")", "opts", "=", "{", "desc", ":", "''", "}", ".", "merge", "(", "options", ")", "$bot", "[", ":tasks", "]", "[", "name", "]", "||=", "{", "block", ":", "block", ",", "desc", ":", "opts", "[", ":desc", "]", "}", "end" ]
Defines a new task to be run outside of a running Twittbot process. @param name [Symbol] The name of the task. @param options [Hash] A customizable set of options. @option options [String] :desc ("") Description of this task
[ "Defines", "a", "new", "task", "to", "be", "run", "outside", "of", "a", "running", "Twittbot", "process", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/botpart.rb#L98-L112
train
nilsding/twittbot
lib/twittbot/botpart.rb
Twittbot.BotPart.save_config
def save_config botpart_config = Hash[@config.to_a - $bot[:config].to_a] unless botpart_config.empty? File.open @botpart_config_path, 'w' do |f| f.write botpart_config.to_yaml end end end
ruby
def save_config botpart_config = Hash[@config.to_a - $bot[:config].to_a] unless botpart_config.empty? File.open @botpart_config_path, 'w' do |f| f.write botpart_config.to_yaml end end end
[ "def", "save_config", "botpart_config", "=", "Hash", "[", "@config", ".", "to_a", "-", "$bot", "[", ":config", "]", ".", "to_a", "]", "unless", "botpart_config", ".", "empty?", "File", ".", "open", "@botpart_config_path", ",", "'w'", "do", "|", "f", "|", "f", ".", "write", "botpart_config", ".", "to_yaml", "end", "end", "end" ]
Saves the botpart's configuration. This is automatically called when Twittbot exits.
[ "Saves", "the", "botpart", "s", "configuration", ".", "This", "is", "automatically", "called", "when", "Twittbot", "exits", "." ]
acddc9514453b17461255c1201f6309b3fc42b17
https://github.com/nilsding/twittbot/blob/acddc9514453b17461255c1201f6309b3fc42b17/lib/twittbot/botpart.rb#L116-L124
train
cloudfoundry-attic/cfoundry
lib/cfoundry/v2/app.rb
CFoundry::V2.App.health
def health if state == "STARTED" healthy_count = running_instances expected = total_instances if expected > 0 ratio = healthy_count / expected.to_f if ratio == 1.0 "RUNNING" else "#{(ratio * 100).to_i}%" end else "N/A" end else state end rescue CFoundry::StagingError, CFoundry::NotStaged "STAGING FAILED" end
ruby
def health if state == "STARTED" healthy_count = running_instances expected = total_instances if expected > 0 ratio = healthy_count / expected.to_f if ratio == 1.0 "RUNNING" else "#{(ratio * 100).to_i}%" end else "N/A" end else state end rescue CFoundry::StagingError, CFoundry::NotStaged "STAGING FAILED" end
[ "def", "health", "if", "state", "==", "\"STARTED\"", "healthy_count", "=", "running_instances", "expected", "=", "total_instances", "if", "expected", ">", "0", "ratio", "=", "healthy_count", "/", "expected", ".", "to_f", "if", "ratio", "==", "1.0", "\"RUNNING\"", "else", "\"#{(ratio * 100).to_i}%\"", "end", "else", "\"N/A\"", "end", "else", "state", "end", "rescue", "CFoundry", "::", "StagingError", ",", "CFoundry", "::", "NotStaged", "\"STAGING FAILED\"", "end" ]
Determine application health. If all instances are running, returns "RUNNING". If only some are started, returns the percentage of them that are healthy. Otherwise, returns application's status.
[ "Determine", "application", "health", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/v2/app.rb#L182-L202
train
cloudfoundry-attic/cfoundry
lib/cfoundry/v2/app.rb
CFoundry::V2.App.bind
def bind(*instances) instances.each do |i| binding = @client.service_binding binding.app = self binding.service_instance = i binding.create! end self end
ruby
def bind(*instances) instances.each do |i| binding = @client.service_binding binding.app = self binding.service_instance = i binding.create! end self end
[ "def", "bind", "(", "*", "instances", ")", "instances", ".", "each", "do", "|", "i", "|", "binding", "=", "@client", ".", "service_binding", "binding", ".", "app", "=", "self", "binding", ".", "service_instance", "=", "i", "binding", ".", "create!", "end", "self", "end" ]
Bind services to application.
[ "Bind", "services", "to", "application", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/v2/app.rb#L251-L260
train
cloudfoundry-attic/cfoundry
lib/cfoundry/v2/app.rb
CFoundry::V2.App.unbind
def unbind(*instances) service_bindings.each do |b| if instances.include? b.service_instance b.delete! end end self end
ruby
def unbind(*instances) service_bindings.each do |b| if instances.include? b.service_instance b.delete! end end self end
[ "def", "unbind", "(", "*", "instances", ")", "service_bindings", ".", "each", "do", "|", "b", "|", "if", "instances", ".", "include?", "b", ".", "service_instance", "b", ".", "delete!", "end", "end", "self", "end" ]
Unbind services from application.
[ "Unbind", "services", "from", "application", "." ]
028576968a054e2524be0b6e00b1400a831db9f4
https://github.com/cloudfoundry-attic/cfoundry/blob/028576968a054e2524be0b6e00b1400a831db9f4/lib/cfoundry/v2/app.rb#L263-L271
train
joeyates/metar-parser
lib/metar/station.rb
Metar.Station.parser
def parser raw = Metar::Raw::Noaa.new(@cccc) Metar::Parser.new(raw) end
ruby
def parser raw = Metar::Raw::Noaa.new(@cccc) Metar::Parser.new(raw) end
[ "def", "parser", "raw", "=", "Metar", "::", "Raw", "::", "Noaa", ".", "new", "(", "@cccc", ")", "Metar", "::", "Parser", ".", "new", "(", "raw", ")", "end" ]
No check is made on the existence of the station
[ "No", "check", "is", "made", "on", "the", "existence", "of", "the", "station" ]
8a771e046d62bd15d87b24a86d21891202ecccaf
https://github.com/joeyates/metar-parser/blob/8a771e046d62bd15d87b24a86d21891202ecccaf/lib/metar/station.rb#L64-L67
train
openfoodfacts/openfoodfacts-ruby
lib/openfoodfacts/product.rb
Openfoodfacts.Product.weburl
def weburl(locale: nil, domain: DEFAULT_DOMAIN) locale ||= self.lc || DEFAULT_LOCALE if self.code && prefix = LOCALE_WEBURL_PREFIXES[locale] path = "#{prefix}/#{self.code}" "https://#{locale}.#{domain}/#{path}" end end
ruby
def weburl(locale: nil, domain: DEFAULT_DOMAIN) locale ||= self.lc || DEFAULT_LOCALE if self.code && prefix = LOCALE_WEBURL_PREFIXES[locale] path = "#{prefix}/#{self.code}" "https://#{locale}.#{domain}/#{path}" end end
[ "def", "weburl", "(", "locale", ":", "nil", ",", "domain", ":", "DEFAULT_DOMAIN", ")", "locale", "||=", "self", ".", "lc", "||", "DEFAULT_LOCALE", "if", "self", ".", "code", "&&", "prefix", "=", "LOCALE_WEBURL_PREFIXES", "[", "locale", "]", "path", "=", "\"#{prefix}/#{self.code}\"", "\"https://#{locale}.#{domain}/#{path}\"", "end", "end" ]
Return Product web URL according to locale
[ "Return", "Product", "web", "URL", "according", "to", "locale" ]
34bfbcb090ec8fc355b2da76ca73421a68aeb84c
https://github.com/openfoodfacts/openfoodfacts-ruby/blob/34bfbcb090ec8fc355b2da76ca73421a68aeb84c/lib/openfoodfacts/product.rb#L175-L182
train
joeyates/metar-parser
lib/metar/parser.rb
Metar.Parser.seek_visibility
def seek_visibility if observer.value == :auto # WMO 15.4 if @chunks[0] == '////' @chunks.shift # Simply dispose of it return end end if @chunks[0] == '1' or @chunks[0] == '2' @visibility = Metar::Data::Visibility.parse(@chunks[0] + ' ' + @chunks[1]) if @visibility @chunks.shift @chunks.shift end else @visibility = Metar::Data::Visibility.parse(@chunks[0]) if @visibility @chunks.shift end end @visibility end
ruby
def seek_visibility if observer.value == :auto # WMO 15.4 if @chunks[0] == '////' @chunks.shift # Simply dispose of it return end end if @chunks[0] == '1' or @chunks[0] == '2' @visibility = Metar::Data::Visibility.parse(@chunks[0] + ' ' + @chunks[1]) if @visibility @chunks.shift @chunks.shift end else @visibility = Metar::Data::Visibility.parse(@chunks[0]) if @visibility @chunks.shift end end @visibility end
[ "def", "seek_visibility", "if", "observer", ".", "value", "==", ":auto", "if", "@chunks", "[", "0", "]", "==", "'////'", "@chunks", ".", "shift", "return", "end", "end", "if", "@chunks", "[", "0", "]", "==", "'1'", "or", "@chunks", "[", "0", "]", "==", "'2'", "@visibility", "=", "Metar", "::", "Data", "::", "Visibility", ".", "parse", "(", "@chunks", "[", "0", "]", "+", "' '", "+", "@chunks", "[", "1", "]", ")", "if", "@visibility", "@chunks", ".", "shift", "@chunks", ".", "shift", "end", "else", "@visibility", "=", "Metar", "::", "Data", "::", "Visibility", ".", "parse", "(", "@chunks", "[", "0", "]", ")", "if", "@visibility", "@chunks", ".", "shift", "end", "end", "@visibility", "end" ]
15.10, 15.6.1
[ "15", ".", "10", "15", ".", "6", ".", "1" ]
8a771e046d62bd15d87b24a86d21891202ecccaf
https://github.com/joeyates/metar-parser/blob/8a771e046d62bd15d87b24a86d21891202ecccaf/lib/metar/parser.rb#L223-L244
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.inspect
def inspect use_dimension a = [Utils.num_inspect(@factor), @dim.inspect] a << "@name="[email protected] if @name a << "@expr="[email protected] if @expr a << "@offset="[email protected] if @offset a << "@dimensionless=true" if @dimensionless if @dimension_value && @dimension_value!=1 a << "@dimension_value="+@dimension_value.inspect end s = a.join(",") "#<#{self.class} #{s}>" end
ruby
def inspect use_dimension a = [Utils.num_inspect(@factor), @dim.inspect] a << "@name="[email protected] if @name a << "@expr="[email protected] if @expr a << "@offset="[email protected] if @offset a << "@dimensionless=true" if @dimensionless if @dimension_value && @dimension_value!=1 a << "@dimension_value="+@dimension_value.inspect end s = a.join(",") "#<#{self.class} #{s}>" end
[ "def", "inspect", "use_dimension", "a", "=", "[", "Utils", ".", "num_inspect", "(", "@factor", ")", ",", "@dim", ".", "inspect", "]", "a", "<<", "\"@name=\"", "+", "@name", ".", "inspect", "if", "@name", "a", "<<", "\"@expr=\"", "+", "@expr", ".", "inspect", "if", "@expr", "a", "<<", "\"@offset=\"", "+", "@offset", ".", "inspect", "if", "@offset", "a", "<<", "\"@dimensionless=true\"", "if", "@dimensionless", "if", "@dimension_value", "&&", "@dimension_value", "!=", "1", "a", "<<", "\"@dimension_value=\"", "+", "@dimension_value", ".", "inspect", "end", "s", "=", "a", ".", "join", "(", "\",\"", ")", "\"#<#{self.class} #{s}>\"", "end" ]
Inspect string. @return [String] @example Phys::Unit["N"].inspect #=> '#<Phys::Unit 1,{"kg"=>1, "m"=>1, "s"=>-2},@expr="newton">'
[ "Inspect", "string", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L173-L185
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.unit_string
def unit_string use_dimension a = [] a << Utils.num_inspect(@factor) if @factor!=1 a += @dim.map do |k,d| if d==1 k else "#{k}^#{d}" end end a.join(" ") end
ruby
def unit_string use_dimension a = [] a << Utils.num_inspect(@factor) if @factor!=1 a += @dim.map do |k,d| if d==1 k else "#{k}^#{d}" end end a.join(" ") end
[ "def", "unit_string", "use_dimension", "a", "=", "[", "]", "a", "<<", "Utils", ".", "num_inspect", "(", "@factor", ")", "if", "@factor", "!=", "1", "a", "+=", "@dim", ".", "map", "do", "|", "k", ",", "d", "|", "if", "d", "==", "1", "k", "else", "\"#{k}^#{d}\"", "end", "end", "a", ".", "join", "(", "\" \"", ")", "end" ]
Make a string of this unit expressed in base units. @return [String] @example Phys::Unit["psi"].string_form #=> "(8896443230521/129032)*1e-04 kg m^-1 s^-2"
[ "Make", "a", "string", "of", "this", "unit", "expressed", "in", "base", "units", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L191-L203
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.conversion_factor
def conversion_factor use_dimension f = @factor @dim.each do |k,d| if d != 0 u = LIST[k] if u.dimensionless? f *= u.dimension_value**d end end end f end
ruby
def conversion_factor use_dimension f = @factor @dim.each do |k,d| if d != 0 u = LIST[k] if u.dimensionless? f *= u.dimension_value**d end end end f end
[ "def", "conversion_factor", "use_dimension", "f", "=", "@factor", "@dim", ".", "each", "do", "|", "k", ",", "d", "|", "if", "d", "!=", "0", "u", "=", "LIST", "[", "k", "]", "if", "u", ".", "dimensionless?", "f", "*=", "u", ".", "dimension_value", "**", "d", "end", "end", "end", "f", "end" ]
Conversion Factor to base unit, including dimension-value. @return [Numeric] @example Phys::Unit["deg"].dimension #=> {"pi"=>1, "radian"=>1} Phys::Unit["deg"].factor #=> (1/180) Phys::Unit["deg"].conversion_factor #=> 0.017453292519943295 @see #factor
[ "Conversion", "Factor", "to", "base", "unit", "including", "dimension", "-", "value", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L219-L231
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.convert
def convert(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.unit.convert_value_to_base_unit(quantity.value) convert_value_from_base_unit(v) else quantity / to_numeric end end
ruby
def convert(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.unit.convert_value_to_base_unit(quantity.value) convert_value_from_base_unit(v) else quantity / to_numeric end end
[ "def", "convert", "(", "quantity", ")", "if", "Quantity", "===", "quantity", "assert_same_dimension", "(", "quantity", ".", "unit", ")", "v", "=", "quantity", ".", "unit", ".", "convert_value_to_base_unit", "(", "quantity", ".", "value", ")", "convert_value_from_base_unit", "(", "v", ")", "else", "quantity", "/", "to_numeric", "end", "end" ]
Convert a quantity to this unit. @param [Phys::Quantity] quantity to be converted. @return [Phys::Quantity] @raise [UnitError] if unit conversion is failed.
[ "Convert", "a", "quantity", "to", "this", "unit", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L304-L312
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.convert_scale
def convert_scale(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.value * quantity.unit.conversion_factor v = v / self.conversion_factor else quantity / to_numeric end end
ruby
def convert_scale(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.value * quantity.unit.conversion_factor v = v / self.conversion_factor else quantity / to_numeric end end
[ "def", "convert_scale", "(", "quantity", ")", "if", "Quantity", "===", "quantity", "assert_same_dimension", "(", "quantity", ".", "unit", ")", "v", "=", "quantity", ".", "value", "*", "quantity", ".", "unit", ".", "conversion_factor", "v", "=", "v", "/", "self", ".", "conversion_factor", "else", "quantity", "/", "to_numeric", "end", "end" ]
Convert a quantity to this unit only in scale. @param [Phys::Quantity] quantity to be converted. @return [Phys::Quantity] @raise [UnitError] if unit conversion is failed.
[ "Convert", "a", "quantity", "to", "this", "unit", "only", "in", "scale", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L318-L326
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.+
def +(x) x = Unit.cast(x) check_operable2(x) assert_same_dimension(x) Unit.new(@factor+x.factor,@dim.dup) end
ruby
def +(x) x = Unit.cast(x) check_operable2(x) assert_same_dimension(x) Unit.new(@factor+x.factor,@dim.dup) end
[ "def", "+", "(", "x", ")", "x", "=", "Unit", ".", "cast", "(", "x", ")", "check_operable2", "(", "x", ")", "assert_same_dimension", "(", "x", ")", "Unit", ".", "new", "(", "@factor", "+", "x", ".", "factor", ",", "@dim", ".", "dup", ")", "end" ]
Addition of units. Both units must be operable and conversion-allowed. @param [Phys::Unit, Numeric] x other unit @return [Phys::Unit] @raise [Phys::UnitError] if unit conversion is failed.
[ "Addition", "of", "units", ".", "Both", "units", "must", "be", "operable", "and", "conversion", "-", "allowed", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L432-L437
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.*
def *(x) x = Unit.cast(x) if scalar? return x elsif x.scalar? return self.dup end check_operable2(x) dims = dimension_binop(x){|a,b| a+b} factor = self.factor * x.factor Unit.new(factor,dims) end
ruby
def *(x) x = Unit.cast(x) if scalar? return x elsif x.scalar? return self.dup end check_operable2(x) dims = dimension_binop(x){|a,b| a+b} factor = self.factor * x.factor Unit.new(factor,dims) end
[ "def", "*", "(", "x", ")", "x", "=", "Unit", ".", "cast", "(", "x", ")", "if", "scalar?", "return", "x", "elsif", "x", ".", "scalar?", "return", "self", ".", "dup", "end", "check_operable2", "(", "x", ")", "dims", "=", "dimension_binop", "(", "x", ")", "{", "|", "a", ",", "b", "|", "a", "+", "b", "}", "factor", "=", "self", ".", "factor", "*", "x", ".", "factor", "Unit", ".", "new", "(", "factor", ",", "dims", ")", "end" ]
Multiplication of units. Both units must be operable. @param [Phys::Unit, Numeric] x other unit @return [Phys::Unit] @raise [Phys::UnitError] if not operable.
[ "Multiplication", "of", "units", ".", "Both", "units", "must", "be", "operable", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L473-L484
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.inverse
def inverse check_operable dims = dimension_uop{|a| -a} Unit.new(Rational(1,self.factor), dims) end
ruby
def inverse check_operable dims = dimension_uop{|a| -a} Unit.new(Rational(1,self.factor), dims) end
[ "def", "inverse", "check_operable", "dims", "=", "dimension_uop", "{", "|", "a", "|", "-", "a", "}", "Unit", ".", "new", "(", "Rational", "(", "1", ",", "self", ".", "factor", ")", ",", "dims", ")", "end" ]
Inverse of units. This unit must be operable. @param [Phys::Unit, Numeric] unit @return [Phys::Unit] @raise [Phys::UnitError] if not operable.
[ "Inverse", "of", "units", ".", "This", "unit", "must", "be", "operable", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L509-L513
train
masa16/phys-units
lib/phys/units/unit.rb
Phys.Unit.**
def **(x) check_operable m = Utils.as_numeric(x) dims = dimension_uop{|a| a*m} Unit.new(@factor**m,dims) end
ruby
def **(x) check_operable m = Utils.as_numeric(x) dims = dimension_uop{|a| a*m} Unit.new(@factor**m,dims) end
[ "def", "**", "(", "x", ")", "check_operable", "m", "=", "Utils", ".", "as_numeric", "(", "x", ")", "dims", "=", "dimension_uop", "{", "|", "a", "|", "a", "*", "m", "}", "Unit", ".", "new", "(", "@factor", "**", "m", ",", "dims", ")", "end" ]
Exponentiation of units. This units must be operable. @param [Numeric] x numeric @return [Phys::Unit] @raise [Phys::UnitError] if not operable.
[ "Exponentiation", "of", "units", ".", "This", "units", "must", "be", "operable", "." ]
f781f0a031f5476940c4acc175ff5a9cfd197d84
https://github.com/masa16/phys-units/blob/f781f0a031f5476940c4acc175ff5a9cfd197d84/lib/phys/units/unit.rb#L520-L525
train
openfoodfacts/openfoodfacts-ruby
lib/openfoodfacts/country.rb
Openfoodfacts.Country.products
def products(page: -1) Product.from_website_page(url, page: page, products_count: products_count) if url end
ruby
def products(page: -1) Product.from_website_page(url, page: page, products_count: products_count) if url end
[ "def", "products", "(", "page", ":", "-", "1", ")", "Product", ".", "from_website_page", "(", "url", ",", "page", ":", "page", ",", "products_count", ":", "products_count", ")", "if", "url", "end" ]
Get products with country
[ "Get", "products", "with", "country" ]
34bfbcb090ec8fc355b2da76ca73421a68aeb84c
https://github.com/openfoodfacts/openfoodfacts-ruby/blob/34bfbcb090ec8fc355b2da76ca73421a68aeb84c/lib/openfoodfacts/country.rb#L28-L30
train
pellegrino/jackpot
app/mailers/jackpot/notifier.rb
Jackpot.Notifier.send_receipt
def send_receipt(payment) @payment = payment @payment_url = public_receipt_payment_url(:payment_id => @payment.id, :public_token => @payment.public_token) mail(:to => "#{@payment.customer.email}", :from => Jackpot.configuration.mailer[:from], :subject => "Payment receipt") end
ruby
def send_receipt(payment) @payment = payment @payment_url = public_receipt_payment_url(:payment_id => @payment.id, :public_token => @payment.public_token) mail(:to => "#{@payment.customer.email}", :from => Jackpot.configuration.mailer[:from], :subject => "Payment receipt") end
[ "def", "send_receipt", "(", "payment", ")", "@payment", "=", "payment", "@payment_url", "=", "public_receipt_payment_url", "(", ":payment_id", "=>", "@payment", ".", "id", ",", ":public_token", "=>", "@payment", ".", "public_token", ")", "mail", "(", ":to", "=>", "\"#{@payment.customer.email}\"", ",", ":from", "=>", "Jackpot", ".", "configuration", ".", "mailer", "[", ":from", "]", ",", ":subject", "=>", "\"Payment receipt\"", ")", "end" ]
Sends the receipt to the customer who made this payment
[ "Sends", "the", "receipt", "to", "the", "customer", "who", "made", "this", "payment" ]
188b476cd26f319ee7f5cceceb1caa4205424ed8
https://github.com/pellegrino/jackpot/blob/188b476cd26f319ee7f5cceceb1caa4205424ed8/app/mailers/jackpot/notifier.rb#L9-L17
train
planio-gmbh/plaintext
lib/plaintext/resolver.rb
Plaintext.Resolver.text
def text if handler = find_handler and text = handler.text(@file, max_size: max_plaintext_bytes) text.gsub!(/\s+/m, ' ') text.strip! text.mb_chars.compose.limit(max_plaintext_bytes).to_s end end
ruby
def text if handler = find_handler and text = handler.text(@file, max_size: max_plaintext_bytes) text.gsub!(/\s+/m, ' ') text.strip! text.mb_chars.compose.limit(max_plaintext_bytes).to_s end end
[ "def", "text", "if", "handler", "=", "find_handler", "and", "text", "=", "handler", ".", "text", "(", "@file", ",", "max_size", ":", "max_plaintext_bytes", ")", "text", ".", "gsub!", "(", "/", "\\s", "/m", ",", "' '", ")", "text", ".", "strip!", "text", ".", "mb_chars", ".", "compose", ".", "limit", "(", "max_plaintext_bytes", ")", ".", "to_s", "end", "end" ]
Returns the extracted fulltext or nil if no matching handler was found for the file type.
[ "Returns", "the", "extracted", "fulltext", "or", "nil", "if", "no", "matching", "handler", "was", "found", "for", "the", "file", "type", "." ]
3adf9266d7d998cae6a5f5a4c360b232dab2de8f
https://github.com/planio-gmbh/plaintext/blob/3adf9266d7d998cae6a5f5a4c360b232dab2de8f/lib/plaintext/resolver.rb#L37-L45
train
sonots/kondate
lib/kondate/role_file.rb
Kondate.RoleFile.explore
def explore paths = if Config.explore_role_files? possible_paths else [get_path] end paths.find {|path| File.readable?(path) } || paths.last end
ruby
def explore paths = if Config.explore_role_files? possible_paths else [get_path] end paths.find {|path| File.readable?(path) } || paths.last end
[ "def", "explore", "paths", "=", "if", "Config", ".", "explore_role_files?", "possible_paths", "else", "[", "get_path", "]", "end", "paths", ".", "find", "{", "|", "path", "|", "File", ".", "readable?", "(", "path", ")", "}", "||", "paths", ".", "last", "end" ]
Returns readable role file exploring possible role files. For example, if `role` is `myapp-web-staging`, this method explores files as 1. myapp-web-staging.yml 1. myapp-web-base.yml 1. myapp-web.yml 1. myapp-base.yml 1. myapp.yml 1. base.yml @return [String] detected file path or last candidate path
[ "Returns", "readable", "role", "file", "exploring", "possible", "role", "files", ".", "For", "example", "if", "role", "is", "myapp", "-", "web", "-", "staging", "this", "method", "explores", "files", "as" ]
a56d520b08a1a2bf2d992067ef017175401684ef
https://github.com/sonots/kondate/blob/a56d520b08a1a2bf2d992067ef017175401684ef/lib/kondate/role_file.rb#L28-L35
train
jronallo/djatoka
lib/djatoka/view_helpers.rb
Djatoka.ViewHelpers.djatoka_init_openlayers
def djatoka_init_openlayers(rft_id, div_identifier, params={}) resolver = determine_resolver(params) metadata_url = resolver.metadata_url(rft_id) %Q|<script type="text/javascript"> jQuery(document).ready(function() {openlayersInit('#{resolver.scheme}://#{resolver.host}', '#{metadata_url}', '#{rft_id}', '#{div_identifier}'); }); </script> | end
ruby
def djatoka_init_openlayers(rft_id, div_identifier, params={}) resolver = determine_resolver(params) metadata_url = resolver.metadata_url(rft_id) %Q|<script type="text/javascript"> jQuery(document).ready(function() {openlayersInit('#{resolver.scheme}://#{resolver.host}', '#{metadata_url}', '#{rft_id}', '#{div_identifier}'); }); </script> | end
[ "def", "djatoka_init_openlayers", "(", "rft_id", ",", "div_identifier", ",", "params", "=", "{", "}", ")", "resolver", "=", "determine_resolver", "(", "params", ")", "metadata_url", "=", "resolver", ".", "metadata_url", "(", "rft_id", ")", "%Q|<script type=\"text/javascript\"> jQuery(document).ready(function() {openlayersInit('#{resolver.scheme}://#{resolver.host}', '#{metadata_url}', '#{rft_id}', '#{div_identifier}'); }); </script> |", "end" ]
View helper to include a bit of jQuery on the page which waits for document load and then initializes the Ajax, OpenLayers viewer. Since this works via Ajax, Djatoka will need to be running or proxied at the same domain as the application to avoid cross-domain restrictions.
[ "View", "helper", "to", "include", "a", "bit", "of", "jQuery", "on", "the", "page", "which", "waits", "for", "document", "load", "and", "then", "initializes", "the", "Ajax", "OpenLayers", "viewer", ".", "Since", "this", "works", "via", "Ajax", "Djatoka", "will", "need", "to", "be", "running", "or", "proxied", "at", "the", "same", "domain", "as", "the", "application", "to", "avoid", "cross", "-", "domain", "restrictions", "." ]
95e99ac48fbaff938ac9795cf9c193881925cc3b
https://github.com/jronallo/djatoka/blob/95e99ac48fbaff938ac9795cf9c193881925cc3b/lib/djatoka/view_helpers.rb#L93-L103
train
kwi/i18n_routing
lib/i18n_routing_rails31.rb
I18nRouting.Mapper.localized_resources
def localized_resources(type = :resources, *resources, &block) localizable_route = nil if @locales res = resources.clone options = res.extract_options! r = res.first resource = resource_from_params(type, r, options.dup) # Check for translated resource stored_locale = I18n.locale @locales.each do |locale| I18n.locale = locale localized_path = I18nRouting.translation_for(resource.name, type) # A translated route exists : if !localized_path.blank? and String === localized_path puts("[I18n] > localize %-10s: %40s (%s) => /%s" % [type, resource.name, locale, localized_path]) if @i18n_verbose opts = options.dup opts[:path] = localized_path opts[:controller] ||= r.to_s.pluralize resource = resource_from_params(type, r, opts.dup) res = ["#{I18nRouting.locale_escaped(locale)}_#{r}".to_sym, opts] constraints = opts[:constraints] ? opts[:constraints].dup : {} constraints[:i18n_locale] = locale.to_s scope(:constraints => constraints, :path_names => I18nRouting.path_names(resource.name, @scope)) do localized_branch(locale) do send(type, *res) do # In the resource(s) block, we need to keep and restore some context : if block old_name = @scope[:i18n_real_resource_name] old = @scope[:scope_level_resource] @scope[:i18n_real_resource_name] = resource.name @scope[:i18n_scope_level_resource] = old @scope[:scope_level_resource] = resource if type == :resource and @scope[:name_prefix] # Need to fake name_prefix for singleton resource @scope[:name_prefix] = @scope[:name_prefix].gsub(Regexp.new("#{old.name}$"), resource.name) end block.call if block @scope[:scope_level_resource] = old @scope[:i18n_real_resource_name] = old_name end @scope[:i18n_scope_level_resource] = nil end end end localizable_route = resource end end I18n.locale = stored_locale end return localizable_route end
ruby
def localized_resources(type = :resources, *resources, &block) localizable_route = nil if @locales res = resources.clone options = res.extract_options! r = res.first resource = resource_from_params(type, r, options.dup) # Check for translated resource stored_locale = I18n.locale @locales.each do |locale| I18n.locale = locale localized_path = I18nRouting.translation_for(resource.name, type) # A translated route exists : if !localized_path.blank? and String === localized_path puts("[I18n] > localize %-10s: %40s (%s) => /%s" % [type, resource.name, locale, localized_path]) if @i18n_verbose opts = options.dup opts[:path] = localized_path opts[:controller] ||= r.to_s.pluralize resource = resource_from_params(type, r, opts.dup) res = ["#{I18nRouting.locale_escaped(locale)}_#{r}".to_sym, opts] constraints = opts[:constraints] ? opts[:constraints].dup : {} constraints[:i18n_locale] = locale.to_s scope(:constraints => constraints, :path_names => I18nRouting.path_names(resource.name, @scope)) do localized_branch(locale) do send(type, *res) do # In the resource(s) block, we need to keep and restore some context : if block old_name = @scope[:i18n_real_resource_name] old = @scope[:scope_level_resource] @scope[:i18n_real_resource_name] = resource.name @scope[:i18n_scope_level_resource] = old @scope[:scope_level_resource] = resource if type == :resource and @scope[:name_prefix] # Need to fake name_prefix for singleton resource @scope[:name_prefix] = @scope[:name_prefix].gsub(Regexp.new("#{old.name}$"), resource.name) end block.call if block @scope[:scope_level_resource] = old @scope[:i18n_real_resource_name] = old_name end @scope[:i18n_scope_level_resource] = nil end end end localizable_route = resource end end I18n.locale = stored_locale end return localizable_route end
[ "def", "localized_resources", "(", "type", "=", ":resources", ",", "*", "resources", ",", "&", "block", ")", "localizable_route", "=", "nil", "if", "@locales", "res", "=", "resources", ".", "clone", "options", "=", "res", ".", "extract_options!", "r", "=", "res", ".", "first", "resource", "=", "resource_from_params", "(", "type", ",", "r", ",", "options", ".", "dup", ")", "stored_locale", "=", "I18n", ".", "locale", "@locales", ".", "each", "do", "|", "locale", "|", "I18n", ".", "locale", "=", "locale", "localized_path", "=", "I18nRouting", ".", "translation_for", "(", "resource", ".", "name", ",", "type", ")", "if", "!", "localized_path", ".", "blank?", "and", "String", "===", "localized_path", "puts", "(", "\"[I18n] > localize %-10s: %40s (%s) => /%s\"", "%", "[", "type", ",", "resource", ".", "name", ",", "locale", ",", "localized_path", "]", ")", "if", "@i18n_verbose", "opts", "=", "options", ".", "dup", "opts", "[", ":path", "]", "=", "localized_path", "opts", "[", ":controller", "]", "||=", "r", ".", "to_s", ".", "pluralize", "resource", "=", "resource_from_params", "(", "type", ",", "r", ",", "opts", ".", "dup", ")", "res", "=", "[", "\"#{I18nRouting.locale_escaped(locale)}_#{r}\"", ".", "to_sym", ",", "opts", "]", "constraints", "=", "opts", "[", ":constraints", "]", "?", "opts", "[", ":constraints", "]", ".", "dup", ":", "{", "}", "constraints", "[", ":i18n_locale", "]", "=", "locale", ".", "to_s", "scope", "(", ":constraints", "=>", "constraints", ",", ":path_names", "=>", "I18nRouting", ".", "path_names", "(", "resource", ".", "name", ",", "@scope", ")", ")", "do", "localized_branch", "(", "locale", ")", "do", "send", "(", "type", ",", "*", "res", ")", "do", "if", "block", "old_name", "=", "@scope", "[", ":i18n_real_resource_name", "]", "old", "=", "@scope", "[", ":scope_level_resource", "]", "@scope", "[", ":i18n_real_resource_name", "]", "=", "resource", ".", "name", "@scope", "[", ":i18n_scope_level_resource", "]", "=", "old", "@scope", "[", ":scope_level_resource", "]", "=", "resource", "if", "type", "==", ":resource", "and", "@scope", "[", ":name_prefix", "]", "@scope", "[", ":name_prefix", "]", "=", "@scope", "[", ":name_prefix", "]", ".", "gsub", "(", "Regexp", ".", "new", "(", "\"#{old.name}$\"", ")", ",", "resource", ".", "name", ")", "end", "block", ".", "call", "if", "block", "@scope", "[", ":scope_level_resource", "]", "=", "old", "@scope", "[", ":i18n_real_resource_name", "]", "=", "old_name", "end", "@scope", "[", ":i18n_scope_level_resource", "]", "=", "nil", "end", "end", "end", "localizable_route", "=", "resource", "end", "end", "I18n", ".", "locale", "=", "stored_locale", "end", "return", "localizable_route", "end" ]
Localize a resources or a resource
[ "Localize", "a", "resources", "or", "a", "resource" ]
edd30ac3445b928f34a97e3762df0ded3c136230
https://github.com/kwi/i18n_routing/blob/edd30ac3445b928f34a97e3762df0ded3c136230/lib/i18n_routing_rails31.rb#L22-L89
train
kwi/i18n_routing
lib/i18n_routing_rails31.rb
I18nRouting.RackMountRoute.initialize_with_i18n_routing
def initialize_with_i18n_routing(app, conditions, defaults, name) @locale = if conditions.key?(:i18n_locale) c = conditions.delete(:i18n_locale) # In rails 3.0 it's a regexp otherwise it's a string, so we need to call source on the regexp (c.respond_to?(:source) ? c.source : c).to_sym else nil end initialize_without_i18n_routing(app, conditions, defaults, name) end
ruby
def initialize_with_i18n_routing(app, conditions, defaults, name) @locale = if conditions.key?(:i18n_locale) c = conditions.delete(:i18n_locale) # In rails 3.0 it's a regexp otherwise it's a string, so we need to call source on the regexp (c.respond_to?(:source) ? c.source : c).to_sym else nil end initialize_without_i18n_routing(app, conditions, defaults, name) end
[ "def", "initialize_with_i18n_routing", "(", "app", ",", "conditions", ",", "defaults", ",", "name", ")", "@locale", "=", "if", "conditions", ".", "key?", "(", ":i18n_locale", ")", "c", "=", "conditions", ".", "delete", "(", ":i18n_locale", ")", "(", "c", ".", "respond_to?", "(", ":source", ")", "?", "c", ".", "source", ":", "c", ")", ".", "to_sym", "else", "nil", "end", "initialize_without_i18n_routing", "(", "app", ",", "conditions", ",", "defaults", ",", "name", ")", "end" ]
During route initialization, if a condition i18n_locale is present Delete it, and store it in @locale
[ "During", "route", "initialization", "if", "a", "condition", "i18n_locale", "is", "present", "Delete", "it", "and", "store", "it", "in" ]
edd30ac3445b928f34a97e3762df0ded3c136230
https://github.com/kwi/i18n_routing/blob/edd30ac3445b928f34a97e3762df0ded3c136230/lib/i18n_routing_rails31.rb#L401-L410
train
kwi/i18n_routing
lib/i18n_routing_rails31.rb
I18nRouting.RackMountRoute.generate_with_i18n_routing
def generate_with_i18n_routing(method, params = {}, recall = {}, options = {}) return nil if @locale and @locale != I18n.locale.to_sym generate_without_i18n_routing(method, params, recall, options) end
ruby
def generate_with_i18n_routing(method, params = {}, recall = {}, options = {}) return nil if @locale and @locale != I18n.locale.to_sym generate_without_i18n_routing(method, params, recall, options) end
[ "def", "generate_with_i18n_routing", "(", "method", ",", "params", "=", "{", "}", ",", "recall", "=", "{", "}", ",", "options", "=", "{", "}", ")", "return", "nil", "if", "@locale", "and", "@locale", "!=", "I18n", ".", "locale", ".", "to_sym", "generate_without_i18n_routing", "(", "method", ",", "params", ",", "recall", ",", "options", ")", "end" ]
Called for dynamic route generation If a @locale is present and if this locale is not the current one => return nil and refuse to generate the route
[ "Called", "for", "dynamic", "route", "generation", "If", "a" ]
edd30ac3445b928f34a97e3762df0ded3c136230
https://github.com/kwi/i18n_routing/blob/edd30ac3445b928f34a97e3762df0ded3c136230/lib/i18n_routing_rails31.rb#L415-L418
train
snltd/wavefront-sdk
lib/wavefront-sdk/maintenancewindow.rb
Wavefront.MaintenanceWindow.pending
def pending(hours = 24) cutoff = Time.now.to_i + hours * 3600 windows_in_state(:pending).tap do |r| r.response.items.delete_if { |w| w.startTimeInSeconds > cutoff } end end
ruby
def pending(hours = 24) cutoff = Time.now.to_i + hours * 3600 windows_in_state(:pending).tap do |r| r.response.items.delete_if { |w| w.startTimeInSeconds > cutoff } end end
[ "def", "pending", "(", "hours", "=", "24", ")", "cutoff", "=", "Time", ".", "now", ".", "to_i", "+", "hours", "*", "3600", "windows_in_state", "(", ":pending", ")", ".", "tap", "do", "|", "r", "|", "r", ".", "response", ".", "items", ".", "delete_if", "{", "|", "w", "|", "w", ".", "startTimeInSeconds", ">", "cutoff", "}", "end", "end" ]
Get the windows which will be open in the next so-many hours @param hours [Numeric] how many hours to look ahead @return [Wavefront::Response]
[ "Get", "the", "windows", "which", "will", "be", "open", "in", "the", "next", "so", "-", "many", "hours" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/maintenancewindow.rb#L92-L98
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/delivery/s3/s3-plugin.rb
BoxGrinder.S3Plugin.constraint_equal?
def constraint_equal?(region, constraint) [region, constraint].collect{ |v| v.nil? || v == '' ? 'us-east-1' : v }.reduce(:==) end
ruby
def constraint_equal?(region, constraint) [region, constraint].collect{ |v| v.nil? || v == '' ? 'us-east-1' : v }.reduce(:==) end
[ "def", "constraint_equal?", "(", "region", ",", "constraint", ")", "[", "region", ",", "constraint", "]", ".", "collect", "{", "|", "v", "|", "v", ".", "nil?", "||", "v", "==", "''", "?", "'us-east-1'", ":", "v", "}", ".", "reduce", "(", ":==", ")", "end" ]
US default constraint is often represented as '' or nil
[ "US", "default", "constraint", "is", "often", "represented", "as", "or", "nil" ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/s3/s3-plugin.rb#L246-L248
train
jasonroelofs/rbgccxml
lib/rbgccxml/nodes/type.rb
RbGCCXML.Type.check_sub_type_without
def check_sub_type_without(val, delim) return false unless val =~ delim new_val = val.gsub(delim, "").strip NodeCache.find(attributes["type"]) == new_valu end
ruby
def check_sub_type_without(val, delim) return false unless val =~ delim new_val = val.gsub(delim, "").strip NodeCache.find(attributes["type"]) == new_valu end
[ "def", "check_sub_type_without", "(", "val", ",", "delim", ")", "return", "false", "unless", "val", "=~", "delim", "new_val", "=", "val", ".", "gsub", "(", "delim", ",", "\"\"", ")", ".", "strip", "NodeCache", ".", "find", "(", "attributes", "[", "\"type\"", "]", ")", "==", "new_valu", "end" ]
For types like pointers or references, we recursively track down the base type when doing comparisons. delim needs to be a regex
[ "For", "types", "like", "pointers", "or", "references", "we", "recursively", "track", "down", "the", "base", "type", "when", "doing", "comparisons", "." ]
f9051f46277a6b4f580dd779012c61e482d11410
https://github.com/jasonroelofs/rbgccxml/blob/f9051f46277a6b4f580dd779012c61e482d11410/lib/rbgccxml/nodes/type.rb#L12-L16
train
enkessler/cucumber_analytics
lib/cucumber_analytics/feature.rb
CucumberAnalytics.Feature.to_s
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Feature:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n\n" + background_output_string if background text << "\n\n" + tests_output_string unless tests.empty? text end
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Feature:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n\n" + background_output_string if background text << "\n\n" + tests_output_string unless tests.empty? text end
[ "def", "to_s", "text", "=", "''", "text", "<<", "tag_output_string", "+", "\"\\n\"", "unless", "tags", ".", "empty?", "text", "<<", "\"Feature:#{name_output_string}\"", "text", "<<", "\"\\n\"", "+", "description_output_string", "unless", "description_text", ".", "empty?", "text", "<<", "\"\\n\\n\"", "+", "background_output_string", "if", "background", "text", "<<", "\"\\n\\n\"", "+", "tests_output_string", "unless", "tests", ".", "empty?", "text", "end" ]
Returns gherkin representation of the feature.
[ "Returns", "gherkin", "representation", "of", "the", "feature", "." ]
a74642d30b3566fc11fb43c920518fea4587c6bd
https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/feature.rb#L79-L89
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/delivery/openstack/openstack-plugin.rb
BoxGrinder.OpenStackPlugin.get_images
def get_images(params = {}) @log.trace "Listing images with params = #{params.to_json}..." data = JSON.parse(RestClient.get("#{url}/v1/images", :params => params))['images'] @log.trace "Listing done." data end
ruby
def get_images(params = {}) @log.trace "Listing images with params = #{params.to_json}..." data = JSON.parse(RestClient.get("#{url}/v1/images", :params => params))['images'] @log.trace "Listing done." data end
[ "def", "get_images", "(", "params", "=", "{", "}", ")", "@log", ".", "trace", "\"Listing images with params = #{params.to_json}...\"", "data", "=", "JSON", ".", "parse", "(", "RestClient", ".", "get", "(", "\"#{url}/v1/images\"", ",", ":params", "=>", "params", ")", ")", "[", "'images'", "]", "@log", ".", "trace", "\"Listing done.\"", "data", "end" ]
Retrieves a list of public images with specified filter. If no filter is specified - all images are returned.
[ "Retrieves", "a", "list", "of", "public", "images", "with", "specified", "filter", ".", "If", "no", "filter", "is", "specified", "-", "all", "images", "are", "returned", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/openstack/openstack-plugin.rb#L121-L126
train
snltd/wavefront-sdk
lib/wavefront-sdk/alert.rb
Wavefront.Alert.versions
def versions(id) wf_alert_id?(id) resp = api.get([id, 'history'].uri_concat) versions = resp.response.items.map(&:version) resp.response[:items] = versions resp end
ruby
def versions(id) wf_alert_id?(id) resp = api.get([id, 'history'].uri_concat) versions = resp.response.items.map(&:version) resp.response[:items] = versions resp end
[ "def", "versions", "(", "id", ")", "wf_alert_id?", "(", "id", ")", "resp", "=", "api", ".", "get", "(", "[", "id", ",", "'history'", "]", ".", "uri_concat", ")", "versions", "=", "resp", ".", "response", ".", "items", ".", "map", "(", "&", ":version", ")", "resp", ".", "response", "[", ":items", "]", "=", "versions", "resp", "end" ]
Gets all the versions of the given alert @param id [String] ID of the alert @reutrn [Wavefront::Resonse] where items is an array of integers
[ "Gets", "all", "the", "versions", "of", "the", "given", "alert" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/alert.rb#L80-L87
train
huerlisi/i18n_rails_helpers
lib/i18n_rails_helpers/model_helpers.rb
I18nRailsHelpers.ModelHelpers.define_enum_t_methods
def define_enum_t_methods defined_enums.each do |enum_attr, values| self.class.send(:define_method, "#{enum_attr}_t") { t_enum(enum_attr) } self.class.send(:define_method, "#{enum_attr.pluralize}_t") do t_enum_values(enum_attr, values) end end end
ruby
def define_enum_t_methods defined_enums.each do |enum_attr, values| self.class.send(:define_method, "#{enum_attr}_t") { t_enum(enum_attr) } self.class.send(:define_method, "#{enum_attr.pluralize}_t") do t_enum_values(enum_attr, values) end end end
[ "def", "define_enum_t_methods", "defined_enums", ".", "each", "do", "|", "enum_attr", ",", "values", "|", "self", ".", "class", ".", "send", "(", ":define_method", ",", "\"#{enum_attr}_t\"", ")", "{", "t_enum", "(", "enum_attr", ")", "}", "self", ".", "class", ".", "send", "(", ":define_method", ",", "\"#{enum_attr.pluralize}_t\"", ")", "do", "t_enum_values", "(", "enum_attr", ",", "values", ")", "end", "end", "end" ]
enum attrubute_t and attributes_t return translated enum values Example: in the Client model enum gender: { undefined: 0, female: 1, male: 2 } in use Client.first.gender # => 'female' Client.first.gender_t # => 'Frau' Client.first.genders_t # => { undefined: 'Nicht definiert', female: 'Frau', male: 'Mann' } Requires: locale key: activerecord.attributes.#{model_name}.#{enum}.#{enum_value_key} eg.: activerecord.attributes.client.genders.female # => 'Frau'
[ "enum", "attrubute_t", "and", "attributes_t", "return", "translated", "enum", "values" ]
4faa6d84ebb4465798246d2bb6d6e353a21d5de8
https://github.com/huerlisi/i18n_rails_helpers/blob/4faa6d84ebb4465798246d2bb6d6e353a21d5de8/lib/i18n_rails_helpers/model_helpers.rb#L17-L24
train
snltd/wavefront-sdk
lib/wavefront-sdk/support/mixins.rb
Wavefront.Mixins.parse_time
def parse_time(time, in_ms = false) return relative_time(time, in_ms) if time =~ /^[\-+]/ ParseTime.new(time, in_ms).parse! end
ruby
def parse_time(time, in_ms = false) return relative_time(time, in_ms) if time =~ /^[\-+]/ ParseTime.new(time, in_ms).parse! end
[ "def", "parse_time", "(", "time", ",", "in_ms", "=", "false", ")", "return", "relative_time", "(", "time", ",", "in_ms", ")", "if", "time", "=~", "/", "\\-", "/", "ParseTime", ".", "new", "(", "time", ",", "in_ms", ")", ".", "parse!", "end" ]
Return a time as an integer, however it might come in. @param time [Integer, String, Time] timestamp @param in_ms [Boolean] whether to return epoch milliseconds. Passing in an integer timestamp returns itself, regardless of this value @return [Integer] epoch time in seconds @raise Wavefront::InvalidTimestamp
[ "Return", "a", "time", "as", "an", "integer", "however", "it", "might", "come", "in", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/support/mixins.rb#L23-L26
train
snltd/wavefront-sdk
lib/wavefront-sdk/support/mixins.rb
Wavefront.Mixins.relative_time
def relative_time(time, in_ms = false, ref = Time.now) ref = in_ms ? ref.to_datetime.strftime('%Q') : ref.to_time ref.to_i + parse_relative_time(time, in_ms) end
ruby
def relative_time(time, in_ms = false, ref = Time.now) ref = in_ms ? ref.to_datetime.strftime('%Q') : ref.to_time ref.to_i + parse_relative_time(time, in_ms) end
[ "def", "relative_time", "(", "time", ",", "in_ms", "=", "false", ",", "ref", "=", "Time", ".", "now", ")", "ref", "=", "in_ms", "?", "ref", ".", "to_datetime", ".", "strftime", "(", "'%Q'", ")", ":", "ref", ".", "to_time", "ref", ".", "to_i", "+", "parse_relative_time", "(", "time", ",", "in_ms", ")", "end" ]
Return a timestamp described by the given string. That is, '+5m' is five minutes in the future, and '-.1h' is half an hour ago. @param time [String] relative time string. Must begin with + or -, followed by a number, finished with a lower-case time unit identifier. See #time_multiplier @param in_ms [Boolean] whether to return epoch milliseconds. Passing in an integer timestamp returns itself, regardless of this value @param ref [Time, DateTime] calculate time relative to this point. Primarily for easier testing. Defaults to "now". @return [Integer] integer timestamp @raise [InvalidRelativeTime] if t does not meet requirements
[ "Return", "a", "timestamp", "described", "by", "the", "given", "string", ".", "That", "is", "+", "5m", "is", "five", "minutes", "in", "the", "future", "and", "-", ".", "1h", "is", "half", "an", "hour", "ago", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/support/mixins.rb#L43-L46
train
snltd/wavefront-sdk
lib/wavefront-sdk/support/mixins.rb
Wavefront.Mixins.time_multiplier
def time_multiplier(suffix) u = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800, y: 31_536_000 } return u[suffix.to_sym] if u.key?(suffix.to_sym) raise Wavefront::Exception::InvalidTimeUnit end
ruby
def time_multiplier(suffix) u = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800, y: 31_536_000 } return u[suffix.to_sym] if u.key?(suffix.to_sym) raise Wavefront::Exception::InvalidTimeUnit end
[ "def", "time_multiplier", "(", "suffix", ")", "u", "=", "{", "s", ":", "1", ",", "m", ":", "60", ",", "h", ":", "3600", ",", "d", ":", "86_400", ",", "w", ":", "604_800", ",", "y", ":", "31_536_000", "}", "return", "u", "[", "suffix", ".", "to_sym", "]", "if", "u", ".", "key?", "(", "suffix", ".", "to_sym", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidTimeUnit", "end" ]
naively return the number of seconds from the given multiplier. This makes absolutely no attempt to compensate for any kind of daylight savings or calendar adjustment. A day is always going to 60 seconds x 60 minutes x 24 hours, and a year will always have 365 days. @param suffix [Symbol, String] @return [Integer] the number of seconds in one unit of the given suffix @raise InvalidTimeUnit if the suffix is unknown
[ "naively", "return", "the", "number", "of", "seconds", "from", "the", "given", "multiplier", ".", "This", "makes", "absolutely", "no", "attempt", "to", "compensate", "for", "any", "kind", "of", "daylight", "savings", "or", "calendar", "adjustment", ".", "A", "day", "is", "always", "going", "to", "60", "seconds", "x", "60", "minutes", "x", "24", "hours", "and", "a", "year", "will", "always", "have", "365", "days", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/support/mixins.rb#L84-L89
train
kayagoban/echochamber
lib/echochamber/agreement/client.rb
Echochamber.Client.create_agreement
def create_agreement(agreement) agreement_response = Echochamber::Request.create_agreement(agreement, token, agreement.user_id, agreement.user_email) agreement_response.fetch("agreementId") end
ruby
def create_agreement(agreement) agreement_response = Echochamber::Request.create_agreement(agreement, token, agreement.user_id, agreement.user_email) agreement_response.fetch("agreementId") end
[ "def", "create_agreement", "(", "agreement", ")", "agreement_response", "=", "Echochamber", "::", "Request", ".", "create_agreement", "(", "agreement", ",", "token", ",", "agreement", ".", "user_id", ",", "agreement", ".", "user_email", ")", "agreement_response", ".", "fetch", "(", "\"agreementId\"", ")", "end" ]
Creates an agreement @param agreement [Echochamber::Agreement] @return [String] Agreement ID
[ "Creates", "an", "agreement" ]
a3665c6b78928e3efa7ba578b899c31aa5c893a4
https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/agreement/client.rb#L9-L12
train
kayagoban/echochamber
lib/echochamber/agreement/client.rb
Echochamber.Client.agreement_documents
def agreement_documents(agreement_id, recipient_email, format, version_id=nil) result = Echochamber::Request.agreement_documents(token, agreement_id, recipient_email, format, version_id) end
ruby
def agreement_documents(agreement_id, recipient_email, format, version_id=nil) result = Echochamber::Request.agreement_documents(token, agreement_id, recipient_email, format, version_id) end
[ "def", "agreement_documents", "(", "agreement_id", ",", "recipient_email", ",", "format", ",", "version_id", "=", "nil", ")", "result", "=", "Echochamber", "::", "Request", ".", "agreement_documents", "(", "token", ",", "agreement_id", ",", "recipient_email", ",", "format", ",", "version_id", ")", "end" ]
All documents relating to an agreement @param agreement_id [String] (REQUIRED) @param recipient_email [String] The email address of the participant to be used to retrieve documents. (REQUIRED) @param format [String] Content format of the supported documents. It can have two possible values ORIGINAL or CONVERTED_PDF. (REQUIRED) @param version_id [String] Version of the agreement as provided by agreement_info(). If not provided, the latest version of the agreement is used. @return [Array] Documents relating to agreement.
[ "All", "documents", "relating", "to", "an", "agreement" ]
a3665c6b78928e3efa7ba578b899c31aa5c893a4
https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/agreement/client.rb#L55-L57
train
kayagoban/echochamber
lib/echochamber/agreement/client.rb
Echochamber.Client.agreement_document_file
def agreement_document_file(agreement_id, document_id, file_path=nil) response = Echochamber::Request.agreement_document_file(token, agreement_id, document_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
def agreement_document_file(agreement_id, document_id, file_path=nil) response = Echochamber::Request.agreement_document_file(token, agreement_id, document_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
[ "def", "agreement_document_file", "(", "agreement_id", ",", "document_id", ",", "file_path", "=", "nil", ")", "response", "=", "Echochamber", "::", "Request", ".", "agreement_document_file", "(", "token", ",", "agreement_id", ",", "document_id", ")", "unless", "file_path", ".", "nil?", "file", "=", "File", ".", "new", "(", "file_path", ",", "'wb'", ")", "file", ".", "write", "(", "response", ")", "file", ".", "close", "end", "response", "end" ]
Retrieve a document file from an agreement @param agreement_id [String] (REQUIRED) @param document_id [String] (REQUIRED) @param file_path [String] File path to save the document. If no file path is given, nothing is saved to disk. @return [String] Raw bytes from document file
[ "Retrieve", "a", "document", "file", "from", "an", "agreement" ]
a3665c6b78928e3efa7ba578b899c31aa5c893a4
https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/agreement/client.rb#L65-L73
train
kayagoban/echochamber
lib/echochamber/agreement/client.rb
Echochamber.Client.agreement_combined_pdf
def agreement_combined_pdf(agreement_id, file_path=nil, versionId=nil, participantEmail=nil, attachSupportingDocuments=true, auditReport=false) response = Echochamber::Request.agreement_combined_pdf(token, agreement_id, versionId, participantEmail, attachSupportingDocuments, auditReport) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
def agreement_combined_pdf(agreement_id, file_path=nil, versionId=nil, participantEmail=nil, attachSupportingDocuments=true, auditReport=false) response = Echochamber::Request.agreement_combined_pdf(token, agreement_id, versionId, participantEmail, attachSupportingDocuments, auditReport) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
[ "def", "agreement_combined_pdf", "(", "agreement_id", ",", "file_path", "=", "nil", ",", "versionId", "=", "nil", ",", "participantEmail", "=", "nil", ",", "attachSupportingDocuments", "=", "true", ",", "auditReport", "=", "false", ")", "response", "=", "Echochamber", "::", "Request", ".", "agreement_combined_pdf", "(", "token", ",", "agreement_id", ",", "versionId", ",", "participantEmail", ",", "attachSupportingDocuments", ",", "auditReport", ")", "unless", "file_path", ".", "nil?", "file", "=", "File", ".", "new", "(", "file_path", ",", "'wb'", ")", "file", ".", "write", "(", "response", ")", "file", ".", "close", "end", "response", "end" ]
Gets a single combined PDF document for the documents associated with an agreement. @param agreement_id [String] (REQUIRED) @param file_path [String] File path to save the document. If no file path is given, nothing is saved to disk. @param versionId [String] The version identifier of agreement as provided by get_agreement. If not provided then latest version will be used @param participantEmail [String] The email address of the participant to be used to retrieve documents. If none is given, the auth token will be used to determine the user @param attachSupportingDocuments [Boolean] When set to YES, attach corresponding supporting documents to the signed agreement PDF. Default value of this parameter is true. @param auditReport [Boolean] When set to YES, attach an audit report to the signed agreement PDF. Default value is false @return [String] Raw bytes from document file
[ "Gets", "a", "single", "combined", "PDF", "document", "for", "the", "documents", "associated", "with", "an", "agreement", "." ]
a3665c6b78928e3efa7ba578b899c31aa5c893a4
https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/agreement/client.rb#L92-L100
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_link_template?
def wf_link_template?(template) if template.is_a?(String) && template.start_with?('http://', 'https://') return true end raise Wavefront::Exception::InvalidLinkTemplate end
ruby
def wf_link_template?(template) if template.is_a?(String) && template.start_with?('http://', 'https://') return true end raise Wavefront::Exception::InvalidLinkTemplate end
[ "def", "wf_link_template?", "(", "template", ")", "if", "template", ".", "is_a?", "(", "String", ")", "&&", "template", ".", "start_with?", "(", "'http://'", ",", "'https://'", ")", "return", "true", "end", "raise", "Wavefront", "::", "Exception", "::", "InvalidLinkTemplate", "end" ]
Ensure the given argument is a valid external link template @return true if it is valid @raise Wavefront::Exception::InvalidTemplate if not
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "external", "link", "template" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L30-L37
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_name?
def wf_name?(name) return true if name.is_a?(String) && name.size < 1024 && name =~ /^\w+$/ raise Wavefront::Exception::InvalidName end
ruby
def wf_name?(name) return true if name.is_a?(String) && name.size < 1024 && name =~ /^\w+$/ raise Wavefront::Exception::InvalidName end
[ "def", "wf_name?", "(", "name", ")", "return", "true", "if", "name", ".", "is_a?", "(", "String", ")", "&&", "name", ".", "size", "<", "1024", "&&", "name", "=~", "/", "\\w", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidName", "end" ]
Ensure the given argument is a valid name, for instance for an event. Names can contain, AFAIK, word characters. @param name [String] the name to validate @return true if the name is valid raise Wavefront::Exception::InvalidName if name is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "name", "for", "instance", "for", "an", "event", ".", "Names", "can", "contain", "AFAIK", "word", "characters", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L64-L67
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_string?
def wf_string?(str) # # Only allows PCRE "word" characters, spaces, full-stops and # commas in tags and descriptions. This might be too restrictive, # but if it is, this is the only place we need to change it. # if str.is_a?(String) && str.size < 1024 && str =~ /^[\-\w \.,]*$/ return true end raise Wavefront::Exception::InvalidString end
ruby
def wf_string?(str) # # Only allows PCRE "word" characters, spaces, full-stops and # commas in tags and descriptions. This might be too restrictive, # but if it is, this is the only place we need to change it. # if str.is_a?(String) && str.size < 1024 && str =~ /^[\-\w \.,]*$/ return true end raise Wavefront::Exception::InvalidString end
[ "def", "wf_string?", "(", "str", ")", "if", "str", ".", "is_a?", "(", "String", ")", "&&", "str", ".", "size", "<", "1024", "&&", "str", "=~", "/", "\\-", "\\w", "\\.", "/", "return", "true", "end", "raise", "Wavefront", "::", "Exception", "::", "InvalidString", "end" ]
Ensure the given argument is a valid string, for a tag name. @param str [String] the string name to validate @return True if the string is valid @raise Wavefront::Exception::InvalidString if string is not valid.
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "string", "for", "a", "tag", "name", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L75-L86
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_ts?
def wf_ts?(timestamp) return true if timestamp.is_a?(Time) || timestamp.is_a?(Date) raise Wavefront::Exception::InvalidTimestamp end
ruby
def wf_ts?(timestamp) return true if timestamp.is_a?(Time) || timestamp.is_a?(Date) raise Wavefront::Exception::InvalidTimestamp end
[ "def", "wf_ts?", "(", "timestamp", ")", "return", "true", "if", "timestamp", ".", "is_a?", "(", "Time", ")", "||", "timestamp", ".", "is_a?", "(", "Date", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidTimestamp", "end" ]
Ensure the given argument is a valid timestamp @param timestamp [DateTime] the timestamp name to validate @return True if the value is valid @raise Wavefront::Exception::InvalidTimestamp
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "timestamp" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L94-L97
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_epoch?
def wf_epoch?(timestamp) return true if timestamp.is_a?(Numeric) raise Wavefront::Exception::InvalidTimestamp end
ruby
def wf_epoch?(timestamp) return true if timestamp.is_a?(Numeric) raise Wavefront::Exception::InvalidTimestamp end
[ "def", "wf_epoch?", "(", "timestamp", ")", "return", "true", "if", "timestamp", ".", "is_a?", "(", "Numeric", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidTimestamp", "end" ]
Ensure the given argument is a valid epoch timestamp. Again, no range checking. @param timestamp [String, Integer] @return True if the timestamp is valid @raise Wavefront::Exception::InvalidMaintenanceWindow
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "epoch", "timestamp", ".", "Again", "no", "range", "checking", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L120-L123
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_value?
def wf_value?(value) return true if value.is_a?(Numeric) raise Wavefront::Exception::InvalidMetricValue end
ruby
def wf_value?(value) return true if value.is_a?(Numeric) raise Wavefront::Exception::InvalidMetricValue end
[ "def", "wf_value?", "(", "value", ")", "return", "true", "if", "value", ".", "is_a?", "(", "Numeric", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidMetricValue", "end" ]
Ensure the given argument is a valid Wavefront value. Can be any form of Numeric, including standard notation. @param value [Numeric] the source name to validate @return True if the value is valid @raise Wavefront::Exception::InvalidValue if the value is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "Wavefront", "value", ".", "Can", "be", "any", "form", "of", "Numeric", "including", "standard", "notation", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L151-L154
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_version?
def wf_version?(version) version = version.to_i if version.is_a?(String) && version =~ /^\d+$/ return true if version.is_a?(Integer) && version.positive? raise Wavefront::Exception::InvalidVersion end
ruby
def wf_version?(version) version = version.to_i if version.is_a?(String) && version =~ /^\d+$/ return true if version.is_a?(Integer) && version.positive? raise Wavefront::Exception::InvalidVersion end
[ "def", "wf_version?", "(", "version", ")", "version", "=", "version", ".", "to_i", "if", "version", ".", "is_a?", "(", "String", ")", "&&", "version", "=~", "/", "\\d", "/", "return", "true", "if", "version", ".", "is_a?", "(", "Integer", ")", "&&", "version", ".", "positive?", "raise", "Wavefront", "::", "Exception", "::", "InvalidVersion", "end" ]
Ensure the given argument is a valid version number @param version [Integer] the version number to validate @return True if the version is valid @raise Wavefront::Exception::InvalidVersion if the alert ID is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "version", "number" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L163-L167
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_alert_id?
def wf_alert_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id.match(/^\d{13}$/) raise Wavefront::Exception::InvalidAlertId end
ruby
def wf_alert_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id.match(/^\d{13}$/) raise Wavefront::Exception::InvalidAlertId end
[ "def", "wf_alert_id?", "(", "id", ")", "id", "=", "id", ".", "to_s", "if", "id", ".", "is_a?", "(", "Numeric", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", ".", "match", "(", "/", "\\d", "/", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidAlertId", "end" ]
Ensure the given argument is a valid Wavefront alert ID. Alerts are identified by the epoch-nanosecond at which they were created. @param id [String] the alert ID to validate @return True if the alert ID is valid @raise Wavefront::Exception::InvalidAlertId if the alert ID is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "Wavefront", "alert", "ID", ".", "Alerts", "are", "identified", "by", "the", "epoch", "-", "nanosecond", "at", "which", "they", "were", "created", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L218-L222
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_dashboard_id?
def wf_dashboard_id?(id) return true if id.is_a?(String) && id.size < 256 && id.match(/^[\w\-]+$/) raise Wavefront::Exception::InvalidDashboardId end
ruby
def wf_dashboard_id?(id) return true if id.is_a?(String) && id.size < 256 && id.match(/^[\w\-]+$/) raise Wavefront::Exception::InvalidDashboardId end
[ "def", "wf_dashboard_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", ".", "size", "<", "256", "&&", "id", ".", "match", "(", "/", "\\w", "\\-", "/", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidDashboardId", "end" ]
There doesn't seem to be a public statement on what's allowed in a dashboard name. For now I'm going to assume up to 255 word characters. @param id [String] the dashboard ID to validate @return true if the dashboard ID is valid @raise Wavefront::Exception::InvalidDashboardID if the dashboard ID is not valid
[ "There", "doesn", "t", "seem", "to", "be", "a", "public", "statement", "on", "what", "s", "allowed", "in", "a", "dashboard", "name", ".", "For", "now", "I", "m", "going", "to", "assume", "up", "to", "255", "word", "characters", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L246-L249
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_derivedmetric_id?
def wf_derivedmetric_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id =~ /^\d{13}$/ raise Wavefront::Exception::InvalidDerivedMetricId end
ruby
def wf_derivedmetric_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id =~ /^\d{13}$/ raise Wavefront::Exception::InvalidDerivedMetricId end
[ "def", "wf_derivedmetric_id?", "(", "id", ")", "id", "=", "id", ".", "to_s", "if", "id", ".", "is_a?", "(", "Numeric", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "\\d", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidDerivedMetricId", "end" ]
Ensure the given argument is a valid derived metric ID. IDs are the millisecond epoch timestamp at which the derived metric was created. @param id [String, Integer] @return True if the ID is valid @raise Wavefront::Exception::InvalidDerivedMetricId
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "derived", "metric", "ID", ".", "IDs", "are", "the", "millisecond", "epoch", "timestamp", "at", "which", "the", "derived", "metric", "was", "created", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L259-L264
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_link_id?
def wf_link_id?(id) return true if id.is_a?(String) && id =~ /^\w{16}$/ raise Wavefront::Exception::InvalidExternalLinkId end
ruby
def wf_link_id?(id) return true if id.is_a?(String) && id =~ /^\w{16}$/ raise Wavefront::Exception::InvalidExternalLinkId end
[ "def", "wf_link_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "\\w", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidExternalLinkId", "end" ]
Ensure the given argument is a valid external Link ID @param id [String] the external link ID to validate @return True if the link ID is valid @raise Wavefront::Exception::InvalidExternalLinkId if the link ID is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "external", "Link", "ID" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L287-L290
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_maintenance_window_id?
def wf_maintenance_window_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id =~ /^\d{13}$/ raise Wavefront::Exception::InvalidMaintenanceWindowId end
ruby
def wf_maintenance_window_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id =~ /^\d{13}$/ raise Wavefront::Exception::InvalidMaintenanceWindowId end
[ "def", "wf_maintenance_window_id?", "(", "id", ")", "id", "=", "id", ".", "to_s", "if", "id", ".", "is_a?", "(", "Numeric", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "\\d", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidMaintenanceWindowId", "end" ]
Ensure the given argument is a valid maintenance window ID. IDs are the millisecond epoch timestamp at which the window was created. @param id [String, Integer] @return True if the ID is valid @raise Wavefront::Exception::InvalidMaintenanceWindowId
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "maintenance", "window", "ID", ".", "IDs", "are", "the", "millisecond", "epoch", "timestamp", "at", "which", "the", "window", "was", "created", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L300-L305
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_alert_severity?
def wf_alert_severity?(severity) return true if %w[INFO SMOKE WARN SEVERE].include?(severity) raise Wavefront::Exception::InvalidAlertSeverity end
ruby
def wf_alert_severity?(severity) return true if %w[INFO SMOKE WARN SEVERE].include?(severity) raise Wavefront::Exception::InvalidAlertSeverity end
[ "def", "wf_alert_severity?", "(", "severity", ")", "return", "true", "if", "%w[", "INFO", "SMOKE", "WARN", "SEVERE", "]", ".", "include?", "(", "severity", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidAlertSeverity", "end" ]
Ensure the given argument is a valid alert severity @param severity [String] severity @return true if valid @raise Wavefront::Exceptions::InvalidAlertSeverity if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "alert", "severity" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L313-L316
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_message_id?
def wf_message_id?(id) return true if id.is_a?(String) && id =~ /^\w+::\w+$/ raise Wavefront::Exception::InvalidMessageId end
ruby
def wf_message_id?(id) return true if id.is_a?(String) && id =~ /^\w+::\w+$/ raise Wavefront::Exception::InvalidMessageId end
[ "def", "wf_message_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "\\w", "\\w", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidMessageId", "end" ]
Ensure the given argument is a valid message ID @param id [String] message ID @return true if valid @raise Wavefront::Exceptions::InvalidMessageId if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "message", "ID" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L324-L327
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_granularity?
def wf_granularity?(granularity) return true if %w[d h m s].include?(granularity.to_s) raise Wavefront::Exception::InvalidGranularity end
ruby
def wf_granularity?(granularity) return true if %w[d h m s].include?(granularity.to_s) raise Wavefront::Exception::InvalidGranularity end
[ "def", "wf_granularity?", "(", "granularity", ")", "return", "true", "if", "%w[", "d", "h", "m", "s", "]", ".", "include?", "(", "granularity", ".", "to_s", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidGranularity", "end" ]
Ensure the given argument is a valid query granularity @param granularity [String] granularity @return true if valid @raise Wavefront::Exceptions::InvalidGranularity if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "query", "granularity" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L336-L339
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_savedsearch_id?
def wf_savedsearch_id?(id) return true if id.is_a?(String) && id =~ /^\w{8}$/ raise Wavefront::Exception::InvalidSavedSearchId end
ruby
def wf_savedsearch_id?(id) return true if id.is_a?(String) && id =~ /^\w{8}$/ raise Wavefront::Exception::InvalidSavedSearchId end
[ "def", "wf_savedsearch_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "\\w", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidSavedSearchId", "end" ]
Ensure the given argument is a valid saved search ID. @param id [String] saved search ID @return true if valid @raise Wavefront::Exceptions::InvalidSavedSearchId if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "saved", "search", "ID", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L347-L350
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_savedsearch_entity?
def wf_savedsearch_entity?(id) return true if %w[DASHBOARD ALERT MAINTENANCE_WINDOW NOTIFICANT EVENT SOURCE EXTERNAL_LINK AGENT CLOUD_INTEGRATION].include?(id) raise Wavefront::Exception::InvalidSavedSearchEntity end
ruby
def wf_savedsearch_entity?(id) return true if %w[DASHBOARD ALERT MAINTENANCE_WINDOW NOTIFICANT EVENT SOURCE EXTERNAL_LINK AGENT CLOUD_INTEGRATION].include?(id) raise Wavefront::Exception::InvalidSavedSearchEntity end
[ "def", "wf_savedsearch_entity?", "(", "id", ")", "return", "true", "if", "%w[", "DASHBOARD", "ALERT", "MAINTENANCE_WINDOW", "NOTIFICANT", "EVENT", "SOURCE", "EXTERNAL_LINK", "AGENT", "CLOUD_INTEGRATION", "]", ".", "include?", "(", "id", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidSavedSearchEntity", "end" ]
Ensure the given argument is a valid saved search entity type. @param id [String] entity type @return true if valid @raise Wavefront::Exceptions::InvalidSavedSearchEntity if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "saved", "search", "entity", "type", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L359-L364
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_source_id?
def wf_source_id?(source) if source.is_a?(String) && source.match(/^[\w\.\-]+$/) && source.size < 1024 return true end raise Wavefront::Exception::InvalidSourceId end
ruby
def wf_source_id?(source) if source.is_a?(String) && source.match(/^[\w\.\-]+$/) && source.size < 1024 return true end raise Wavefront::Exception::InvalidSourceId end
[ "def", "wf_source_id?", "(", "source", ")", "if", "source", ".", "is_a?", "(", "String", ")", "&&", "source", ".", "match", "(", "/", "\\w", "\\.", "\\-", "/", ")", "&&", "source", ".", "size", "<", "1024", "return", "true", "end", "raise", "Wavefront", "::", "Exception", "::", "InvalidSourceId", "end" ]
Ensure the given argument is a valid Wavefront source name @param source [String] the source name to validate @return True if the source name is valid @raise Wavefront::Exception::InvalidSourceId if the source name is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "Wavefront", "source", "name" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L373-L380
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_user_id?
def wf_user_id?(user) return true if user.is_a?(String) && user.length < 256 && !user.empty? raise Wavefront::Exception::InvalidUserId end
ruby
def wf_user_id?(user) return true if user.is_a?(String) && user.length < 256 && !user.empty? raise Wavefront::Exception::InvalidUserId end
[ "def", "wf_user_id?", "(", "user", ")", "return", "true", "if", "user", ".", "is_a?", "(", "String", ")", "&&", "user", ".", "length", "<", "256", "&&", "!", "user", ".", "empty?", "raise", "Wavefront", "::", "Exception", "::", "InvalidUserId", "end" ]
Ensure the given argument is a valid user. @param user [String] user identifier @return true if valid @raise Wavefront::Exceptions::InvalidUserId if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "user", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L388-L391
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_webhook_id?
def wf_webhook_id?(id) return true if id.is_a?(String) && id =~ /^[a-zA-Z0-9]{16}$/ raise Wavefront::Exception::InvalidWebhookId end
ruby
def wf_webhook_id?(id) return true if id.is_a?(String) && id =~ /^[a-zA-Z0-9]{16}$/ raise Wavefront::Exception::InvalidWebhookId end
[ "def", "wf_webhook_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidWebhookId", "end" ]
Ensure the given argument is a valid webhook ID. @param id [String] webhook ID @return true if valid @raise Wavefront::Exceptions::InvalidWebhook if not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "webhook", "ID", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L410-L413
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_distribution?
def wf_distribution?(dist) wf_metric_name?(dist[:path]) wf_distribution_values?(dist[:value]) wf_epoch?(dist[:ts]) if dist[:ts] wf_source_id?(dist[:source]) if dist[:source] wf_point_tags?(dist[:tags]) if dist[:tags] true end
ruby
def wf_distribution?(dist) wf_metric_name?(dist[:path]) wf_distribution_values?(dist[:value]) wf_epoch?(dist[:ts]) if dist[:ts] wf_source_id?(dist[:source]) if dist[:source] wf_point_tags?(dist[:tags]) if dist[:tags] true end
[ "def", "wf_distribution?", "(", "dist", ")", "wf_metric_name?", "(", "dist", "[", ":path", "]", ")", "wf_distribution_values?", "(", "dist", "[", ":value", "]", ")", "wf_epoch?", "(", "dist", "[", ":ts", "]", ")", "if", "dist", "[", ":ts", "]", "wf_source_id?", "(", "dist", "[", ":source", "]", ")", "if", "dist", "[", ":source", "]", "wf_point_tags?", "(", "dist", "[", ":tags", "]", ")", "if", "dist", "[", ":tags", "]", "true", "end" ]
Validate a distribution description @param dist [Hash] description of distribution @return true if valid @raise whichever exception is thrown first when validating each component of the distribution.
[ "Validate", "a", "distribution", "description" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L438-L445
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_distribution_values?
def wf_distribution_values?(vals) vals.each do |times, val| wf_distribution_count?(times) wf_value?(val) end true end
ruby
def wf_distribution_values?(vals) vals.each do |times, val| wf_distribution_count?(times) wf_value?(val) end true end
[ "def", "wf_distribution_values?", "(", "vals", ")", "vals", ".", "each", "do", "|", "times", ",", "val", "|", "wf_distribution_count?", "(", "times", ")", "wf_value?", "(", "val", ")", "end", "true", "end" ]
Validate an array of distribution values @param vals [Array[Array]] [count, value] @return true if valid @raise whichever exception is thrown first when validating each component of the distribution.
[ "Validate", "an", "array", "of", "distribution", "values" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L453-L459
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_notificant_id?
def wf_notificant_id?(id) return true if id.is_a?(String) && id =~ /^\w{16}$/ raise Wavefront::Exception::InvalidNotificantId end
ruby
def wf_notificant_id?(id) return true if id.is_a?(String) && id =~ /^\w{16}$/ raise Wavefront::Exception::InvalidNotificantId end
[ "def", "wf_notificant_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "\\w", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidNotificantId", "end" ]
Ensure the given argument is a valid Wavefront notificant ID. @param id [String] the notificant ID to validate @return True if the notificant ID is valid @raise Wavefront::Exception::InvalidNotificantId if the notificant ID is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "Wavefront", "notificant", "ID", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L468-L471
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_integration_id?
def wf_integration_id?(id) return true if id.is_a?(String) && id =~ /^[a-z0-9]+$/ raise Wavefront::Exception::InvalidIntegrationId end
ruby
def wf_integration_id?(id) return true if id.is_a?(String) && id =~ /^[a-z0-9]+$/ raise Wavefront::Exception::InvalidIntegrationId end
[ "def", "wf_integration_id?", "(", "id", ")", "return", "true", "if", "id", ".", "is_a?", "(", "String", ")", "&&", "id", "=~", "/", "/", "raise", "Wavefront", "::", "Exception", "::", "InvalidIntegrationId", "end" ]
Ensure the given argument is a valid Wavefront integration ID. These appear to be lower-case strings. @param id [String] the integration ID to validate @return True if the integration name is valid @raise Wavefront::Exception::InvalidIntegrationId if the integration ID is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "Wavefront", "integration", "ID", ".", "These", "appear", "to", "be", "lower", "-", "case", "strings", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L481-L484
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_distribution_interval?
def wf_distribution_interval?(interval) return true if %i[m h d].include?(interval) raise Wavefront::Exception::InvalidDistributionInterval end
ruby
def wf_distribution_interval?(interval) return true if %i[m h d].include?(interval) raise Wavefront::Exception::InvalidDistributionInterval end
[ "def", "wf_distribution_interval?", "(", "interval", ")", "return", "true", "if", "%i[", "m", "h", "d", "]", ".", "include?", "(", "interval", ")", "raise", "Wavefront", "::", "Exception", "::", "InvalidDistributionInterval", "end" ]
Ensure the given argument is a valid distribution interval. @param interval [Symbol] @raise Wavefront::Exception::InvalidDistributionInterval if the interval is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "distribution", "interval", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L491-L494
train
snltd/wavefront-sdk
lib/wavefront-sdk/validators.rb
Wavefront.Validators.wf_distribution_count?
def wf_distribution_count?(count) return true if count.is_a?(Integer) && count.positive? raise Wavefront::Exception::InvalidDistributionCount end
ruby
def wf_distribution_count?(count) return true if count.is_a?(Integer) && count.positive? raise Wavefront::Exception::InvalidDistributionCount end
[ "def", "wf_distribution_count?", "(", "count", ")", "return", "true", "if", "count", ".", "is_a?", "(", "Integer", ")", "&&", "count", ".", "positive?", "raise", "Wavefront", "::", "Exception", "::", "InvalidDistributionCount", "end" ]
Ensure the given argument is a valid distribution count. @param count [Numeric] @raise Wavefront::Exception::InvalidDistributionCount if the count is not valid
[ "Ensure", "the", "given", "argument", "is", "a", "valid", "distribution", "count", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/validators.rb#L501-L504
train
snltd/wavefront-sdk
lib/wavefront-sdk/query.rb
Wavefront.Query.response_shim
def response_shim(body, status) resp, err_msg = parsed_response(body) { response: resp, status: { result: status == 200 ? 'OK' : 'ERROR', message: err_msg, code: status } }.to_json end
ruby
def response_shim(body, status) resp, err_msg = parsed_response(body) { response: resp, status: { result: status == 200 ? 'OK' : 'ERROR', message: err_msg, code: status } }.to_json end
[ "def", "response_shim", "(", "body", ",", "status", ")", "resp", ",", "err_msg", "=", "parsed_response", "(", "body", ")", "{", "response", ":", "resp", ",", "status", ":", "{", "result", ":", "status", "==", "200", "?", "'OK'", ":", "'ERROR'", ",", "message", ":", "err_msg", ",", "code", ":", "status", "}", "}", ".", "to_json", "end" ]
Fake a response which looks like we get from all the other paths. The default response is a single array.
[ "Fake", "a", "response", "which", "looks", "like", "we", "get", "from", "all", "the", "other", "paths", ".", "The", "default", "response", "is", "a", "single", "array", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/query.rb#L79-L86
train
snltd/wavefront-sdk
lib/wavefront-sdk/query.rb
Wavefront.Query.parsed_response
def parsed_response(body) [JSON.parse(body), ''] rescue JSON::ParserError ['', body.match(/message='([^']+)'/).captures.first] end
ruby
def parsed_response(body) [JSON.parse(body), ''] rescue JSON::ParserError ['', body.match(/message='([^']+)'/).captures.first] end
[ "def", "parsed_response", "(", "body", ")", "[", "JSON", ".", "parse", "(", "body", ")", ",", "''", "]", "rescue", "JSON", "::", "ParserError", "[", "''", ",", "body", ".", "match", "(", "/", "/", ")", ".", "captures", ".", "first", "]", "end" ]
A bad query doesn't send back a JSON object. It sends back a string with an embedded message.
[ "A", "bad", "query", "doesn", "t", "send", "back", "a", "JSON", "object", ".", "It", "sends", "back", "a", "string", "with", "an", "embedded", "message", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/query.rb#L91-L95
train
snltd/wavefront-sdk
lib/wavefront-sdk/credentials.rb
Wavefront.Credentials.populate
def populate(raw) @config = Map(raw) @creds = Map(raw.select { |k, _v| %i[endpoint token].include?(k) }) @proxy = Map(raw.select { |k, _v| %i[proxy port].include?(k) }) @all = Map(raw.select do |k, _v| %i[proxy port endpoint token].include?(k) end) end
ruby
def populate(raw) @config = Map(raw) @creds = Map(raw.select { |k, _v| %i[endpoint token].include?(k) }) @proxy = Map(raw.select { |k, _v| %i[proxy port].include?(k) }) @all = Map(raw.select do |k, _v| %i[proxy port endpoint token].include?(k) end) end
[ "def", "populate", "(", "raw", ")", "@config", "=", "Map", "(", "raw", ")", "@creds", "=", "Map", "(", "raw", ".", "select", "{", "|", "k", ",", "_v", "|", "%i[", "endpoint", "token", "]", ".", "include?", "(", "k", ")", "}", ")", "@proxy", "=", "Map", "(", "raw", ".", "select", "{", "|", "k", ",", "_v", "|", "%i[", "proxy", "port", "]", ".", "include?", "(", "k", ")", "}", ")", "@all", "=", "Map", "(", "raw", ".", "select", "do", "|", "k", ",", "_v", "|", "%i[", "proxy", "port", "endpoint", "token", "]", ".", "include?", "(", "k", ")", "end", ")", "end" ]
Make the helper values. We use a Map so they're super-easy to access @param raw [Hash] the combined options from config file, command-line and env vars. @return void
[ "Make", "the", "helper", "values", ".", "We", "use", "a", "Map", "so", "they", "re", "super", "-", "easy", "to", "access" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/credentials.rb#L60-L67
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/helpers/guestfs-helper.rb
BoxGrinder.GuestFSHelper.log_hack
def log_hack read_stderr, write_stderr = IO.pipe fork do write_stderr.close read_stderr.each do |l| @log.trace "GFS: #{l.chomp.strip}" end read_stderr.close end old_stderr = STDERR.clone STDERR.reopen(write_stderr) STDERR.sync = true begin # Execute all tasks yield if block_given? ensure STDERR.reopen(old_stderr) end write_stderr.close read_stderr.close Process.wait end
ruby
def log_hack read_stderr, write_stderr = IO.pipe fork do write_stderr.close read_stderr.each do |l| @log.trace "GFS: #{l.chomp.strip}" end read_stderr.close end old_stderr = STDERR.clone STDERR.reopen(write_stderr) STDERR.sync = true begin # Execute all tasks yield if block_given? ensure STDERR.reopen(old_stderr) end write_stderr.close read_stderr.close Process.wait end
[ "def", "log_hack", "read_stderr", ",", "write_stderr", "=", "IO", ".", "pipe", "fork", "do", "write_stderr", ".", "close", "read_stderr", ".", "each", "do", "|", "l", "|", "@log", ".", "trace", "\"GFS: #{l.chomp.strip}\"", "end", "read_stderr", ".", "close", "end", "old_stderr", "=", "STDERR", ".", "clone", "STDERR", ".", "reopen", "(", "write_stderr", ")", "STDERR", ".", "sync", "=", "true", "begin", "yield", "if", "block_given?", "ensure", "STDERR", ".", "reopen", "(", "old_stderr", ")", "end", "write_stderr", ".", "close", "read_stderr", ".", "close", "Process", ".", "wait", "end" ]
If log callback aren't available we will fail to this, which sucks...
[ "If", "log", "callback", "aren", "t", "available", "we", "will", "fail", "to", "this", "which", "sucks", "..." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/guestfs-helper.rb#L81-L110
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/helpers/guestfs-helper.rb
BoxGrinder.GuestFSHelper.mount_partitions
def mount_partitions(device, mount_prefix = '') @log.trace "Mounting partitions..." partitions = mountable_partitions(device) mount_points = LinuxHelper.new(:log => @log).partition_mount_points(@appliance_config.hardware.partitions) # https://issues.jboss.org/browse/BGBUILD-307 # We don't want to mount swap partitions at all... mount_points.delete("swap") partitions.each_index { |i| mount_partition(partitions[i], mount_points[i], mount_prefix) } end
ruby
def mount_partitions(device, mount_prefix = '') @log.trace "Mounting partitions..." partitions = mountable_partitions(device) mount_points = LinuxHelper.new(:log => @log).partition_mount_points(@appliance_config.hardware.partitions) # https://issues.jboss.org/browse/BGBUILD-307 # We don't want to mount swap partitions at all... mount_points.delete("swap") partitions.each_index { |i| mount_partition(partitions[i], mount_points[i], mount_prefix) } end
[ "def", "mount_partitions", "(", "device", ",", "mount_prefix", "=", "''", ")", "@log", ".", "trace", "\"Mounting partitions...\"", "partitions", "=", "mountable_partitions", "(", "device", ")", "mount_points", "=", "LinuxHelper", ".", "new", "(", ":log", "=>", "@log", ")", ".", "partition_mount_points", "(", "@appliance_config", ".", "hardware", ".", "partitions", ")", "mount_points", ".", "delete", "(", "\"swap\"", ")", "partitions", ".", "each_index", "{", "|", "i", "|", "mount_partition", "(", "partitions", "[", "i", "]", ",", "mount_points", "[", "i", "]", ",", "mount_prefix", ")", "}", "end" ]
This mount partitions. We assume that the first partition is a root partition.
[ "This", "mount", "partitions", ".", "We", "assume", "that", "the", "first", "partition", "is", "a", "root", "partition", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/guestfs-helper.rb#L252-L261
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/helpers/guestfs-helper.rb
BoxGrinder.GuestFSHelper.umount_partitions
def umount_partitions(device) partitions = mountable_partitions(device) @log.trace "Unmounting partitions..." partitions.reverse.each { |part| umount_partition(part) } @log.trace "All partitions unmounted." end
ruby
def umount_partitions(device) partitions = mountable_partitions(device) @log.trace "Unmounting partitions..." partitions.reverse.each { |part| umount_partition(part) } @log.trace "All partitions unmounted." end
[ "def", "umount_partitions", "(", "device", ")", "partitions", "=", "mountable_partitions", "(", "device", ")", "@log", ".", "trace", "\"Unmounting partitions...\"", "partitions", ".", "reverse", ".", "each", "{", "|", "part", "|", "umount_partition", "(", "part", ")", "}", "@log", ".", "trace", "\"All partitions unmounted.\"", "end" ]
Unmounts partitions in reverse order.
[ "Unmounts", "partitions", "in", "reverse", "order", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/guestfs-helper.rb#L287-L293
train
snltd/wavefront-sdk
lib/wavefront-sdk/search.rb
Wavefront.Search.body
def body(query, options) ret = { limit: options[:limit] || 10, offset: options[:offset] || 0 } if query && !query.empty? ret[:query] = [query].flatten.map do |q| q.tap { |iq| iq[:matchingMethod] ||= 'CONTAINS' } end ret[:sort] = sort_field(options, query) end ret end
ruby
def body(query, options) ret = { limit: options[:limit] || 10, offset: options[:offset] || 0 } if query && !query.empty? ret[:query] = [query].flatten.map do |q| q.tap { |iq| iq[:matchingMethod] ||= 'CONTAINS' } end ret[:sort] = sort_field(options, query) end ret end
[ "def", "body", "(", "query", ",", "options", ")", "ret", "=", "{", "limit", ":", "options", "[", ":limit", "]", "||", "10", ",", "offset", ":", "options", "[", ":offset", "]", "||", "0", "}", "if", "query", "&&", "!", "query", ".", "empty?", "ret", "[", ":query", "]", "=", "[", "query", "]", ".", "flatten", ".", "map", "do", "|", "q", "|", "q", ".", "tap", "{", "|", "iq", "|", "iq", "[", ":matchingMethod", "]", "||=", "'CONTAINS'", "}", "end", "ret", "[", ":sort", "]", "=", "sort_field", "(", "options", ",", "query", ")", "end", "ret", "end" ]
Build a query body
[ "Build", "a", "query", "body" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/search.rb#L47-L60
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/delivery/elastichosts/elastichosts-plugin.rb
BoxGrinder.ElasticHostsPlugin.create_server
def create_server @log.info "Creating new server..." memory = ((is_cloudsigma? and @appliance_config.hardware.memory < 512) ? 512 : @appliance_config.hardware.memory) body = hash_to_request( 'name' => "#{@appliance_config.name}-#{@appliance_config.version}.#{@appliance_config.release}", 'cpu' => @appliance_config.hardware.cpus * 1000, # MHz 'smp' => 'auto', 'mem' => memory, 'persistent' => 'true', # hack 'ide:0:0' => @plugin_config['drive_uuid'], 'boot' => 'ide:0:0', 'nic:0:model' => 'e1000', 'nic:0:dhcp' => 'auto', 'vnc:ip' => 'auto', 'vnc:password' => (0...8).map { (('a'..'z').to_a + ('A'..'Z').to_a)[rand(52)] }.join # 8 character VNC password ) begin path = is_cloudsigma? ? '/servers/create' : '/servers/create/stopped' ret = response_to_hash(RestClient.post(api_url(path), body)) @log.info "Server was registered with '#{ret['name']}' name as '#{ret['server']}' UUID. Use web UI or API tools to start your server." rescue => e @log.error e.info raise PluginError, "An error occurred while creating the server, #{e.message}. See logs for more info." end end
ruby
def create_server @log.info "Creating new server..." memory = ((is_cloudsigma? and @appliance_config.hardware.memory < 512) ? 512 : @appliance_config.hardware.memory) body = hash_to_request( 'name' => "#{@appliance_config.name}-#{@appliance_config.version}.#{@appliance_config.release}", 'cpu' => @appliance_config.hardware.cpus * 1000, # MHz 'smp' => 'auto', 'mem' => memory, 'persistent' => 'true', # hack 'ide:0:0' => @plugin_config['drive_uuid'], 'boot' => 'ide:0:0', 'nic:0:model' => 'e1000', 'nic:0:dhcp' => 'auto', 'vnc:ip' => 'auto', 'vnc:password' => (0...8).map { (('a'..'z').to_a + ('A'..'Z').to_a)[rand(52)] }.join # 8 character VNC password ) begin path = is_cloudsigma? ? '/servers/create' : '/servers/create/stopped' ret = response_to_hash(RestClient.post(api_url(path), body)) @log.info "Server was registered with '#{ret['name']}' name as '#{ret['server']}' UUID. Use web UI or API tools to start your server." rescue => e @log.error e.info raise PluginError, "An error occurred while creating the server, #{e.message}. See logs for more info." end end
[ "def", "create_server", "@log", ".", "info", "\"Creating new server...\"", "memory", "=", "(", "(", "is_cloudsigma?", "and", "@appliance_config", ".", "hardware", ".", "memory", "<", "512", ")", "?", "512", ":", "@appliance_config", ".", "hardware", ".", "memory", ")", "body", "=", "hash_to_request", "(", "'name'", "=>", "\"#{@appliance_config.name}-#{@appliance_config.version}.#{@appliance_config.release}\"", ",", "'cpu'", "=>", "@appliance_config", ".", "hardware", ".", "cpus", "*", "1000", ",", "'smp'", "=>", "'auto'", ",", "'mem'", "=>", "memory", ",", "'persistent'", "=>", "'true'", ",", "'ide:0:0'", "=>", "@plugin_config", "[", "'drive_uuid'", "]", ",", "'boot'", "=>", "'ide:0:0'", ",", "'nic:0:model'", "=>", "'e1000'", ",", "'nic:0:dhcp'", "=>", "'auto'", ",", "'vnc:ip'", "=>", "'auto'", ",", "'vnc:password'", "=>", "(", "0", "...", "8", ")", ".", "map", "{", "(", "(", "'a'", "..", "'z'", ")", ".", "to_a", "+", "(", "'A'", "..", "'Z'", ")", ".", "to_a", ")", "[", "rand", "(", "52", ")", "]", "}", ".", "join", ")", "begin", "path", "=", "is_cloudsigma?", "?", "'/servers/create'", ":", "'/servers/create/stopped'", "ret", "=", "response_to_hash", "(", "RestClient", ".", "post", "(", "api_url", "(", "path", ")", ",", "body", ")", ")", "@log", ".", "info", "\"Server was registered with '#{ret['name']}' name as '#{ret['server']}' UUID. Use web UI or API tools to start your server.\"", "rescue", "=>", "e", "@log", ".", "error", "e", ".", "info", "raise", "PluginError", ",", "\"An error occurred while creating the server, #{e.message}. See logs for more info.\"", "end", "end" ]
Creates the server for previously uploaded disk
[ "Creates", "the", "server", "for", "previously", "uploaded", "disk" ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/elastichosts/elastichosts-plugin.rb#L182-L210
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/appliance.rb
BoxGrinder.Appliance.initialize_plugins
def initialize_plugins @plugin_chain = [] os_plugin, os_plugin_info = PluginManager.instance.initialize_plugin(:os, @appliance_config.os.name.to_sym) initialize_plugin(os_plugin, os_plugin_info) if platform_selected? platform_plugin, platform_plugin_info = PluginManager.instance.initialize_plugin(:platform, @config.platform) initialize_plugin(platform_plugin, platform_plugin_info) end if delivery_selected? delivery_plugin, delivery_plugin_info = PluginManager.instance.initialize_plugin(:delivery, @config.delivery) # Here we need to specify additionally the type of the plugin, as some delivery plugins # can have multiple types of delivery implemented. See s3-plugin.rb for example. initialize_plugin(delivery_plugin, delivery_plugin_info, :type => @config.delivery) end end
ruby
def initialize_plugins @plugin_chain = [] os_plugin, os_plugin_info = PluginManager.instance.initialize_plugin(:os, @appliance_config.os.name.to_sym) initialize_plugin(os_plugin, os_plugin_info) if platform_selected? platform_plugin, platform_plugin_info = PluginManager.instance.initialize_plugin(:platform, @config.platform) initialize_plugin(platform_plugin, platform_plugin_info) end if delivery_selected? delivery_plugin, delivery_plugin_info = PluginManager.instance.initialize_plugin(:delivery, @config.delivery) # Here we need to specify additionally the type of the plugin, as some delivery plugins # can have multiple types of delivery implemented. See s3-plugin.rb for example. initialize_plugin(delivery_plugin, delivery_plugin_info, :type => @config.delivery) end end
[ "def", "initialize_plugins", "@plugin_chain", "=", "[", "]", "os_plugin", ",", "os_plugin_info", "=", "PluginManager", ".", "instance", ".", "initialize_plugin", "(", ":os", ",", "@appliance_config", ".", "os", ".", "name", ".", "to_sym", ")", "initialize_plugin", "(", "os_plugin", ",", "os_plugin_info", ")", "if", "platform_selected?", "platform_plugin", ",", "platform_plugin_info", "=", "PluginManager", ".", "instance", ".", "initialize_plugin", "(", ":platform", ",", "@config", ".", "platform", ")", "initialize_plugin", "(", "platform_plugin", ",", "platform_plugin_info", ")", "end", "if", "delivery_selected?", "delivery_plugin", ",", "delivery_plugin_info", "=", "PluginManager", ".", "instance", ".", "initialize_plugin", "(", ":delivery", ",", "@config", ".", "delivery", ")", "initialize_plugin", "(", "delivery_plugin", ",", "delivery_plugin_info", ",", ":type", "=>", "@config", ".", "delivery", ")", "end", "end" ]
Here we initialize all required plugins and create a plugin chain. Initialization involves also plugin configuration validation for specified plugin type.
[ "Here", "we", "initialize", "all", "required", "plugins", "and", "create", "a", "plugin", "chain", ".", "Initialization", "involves", "also", "plugin", "configuration", "validation", "for", "specified", "plugin", "type", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/appliance.rb#L65-L82
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/appliance.rb
BoxGrinder.Appliance.initialize_plugin
def initialize_plugin(plugin, plugin_info, options = {}) options = { :log => @log }.merge(options) unless @plugin_chain.empty? options.merge!(:previous_plugin => @plugin_chain.last[:plugin]) end plugin.init(@config, @appliance_config, plugin_info, options) # Execute callbacks if implemented # # Order is very important [:after_init, :validate, :after_validate].each do |callback| plugin.send(callback) if plugin.respond_to?(callback) end param = nil # For operating system plugins we need to inject appliance definition. if plugin_info[:type] == :os param = @appliance_definition end @plugin_chain << {:plugin => plugin, :param => param} end
ruby
def initialize_plugin(plugin, plugin_info, options = {}) options = { :log => @log }.merge(options) unless @plugin_chain.empty? options.merge!(:previous_plugin => @plugin_chain.last[:plugin]) end plugin.init(@config, @appliance_config, plugin_info, options) # Execute callbacks if implemented # # Order is very important [:after_init, :validate, :after_validate].each do |callback| plugin.send(callback) if plugin.respond_to?(callback) end param = nil # For operating system plugins we need to inject appliance definition. if plugin_info[:type] == :os param = @appliance_definition end @plugin_chain << {:plugin => plugin, :param => param} end
[ "def", "initialize_plugin", "(", "plugin", ",", "plugin_info", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":log", "=>", "@log", "}", ".", "merge", "(", "options", ")", "unless", "@plugin_chain", ".", "empty?", "options", ".", "merge!", "(", ":previous_plugin", "=>", "@plugin_chain", ".", "last", "[", ":plugin", "]", ")", "end", "plugin", ".", "init", "(", "@config", ",", "@appliance_config", ",", "plugin_info", ",", "options", ")", "[", ":after_init", ",", ":validate", ",", ":after_validate", "]", ".", "each", "do", "|", "callback", "|", "plugin", ".", "send", "(", "callback", ")", "if", "plugin", ".", "respond_to?", "(", "callback", ")", "end", "param", "=", "nil", "if", "plugin_info", "[", ":type", "]", "==", ":os", "param", "=", "@appliance_definition", "end", "@plugin_chain", "<<", "{", ":plugin", "=>", "plugin", ",", ":param", "=>", "param", "}", "end" ]
Initializes the plugin by executing init, after_init, validate and after_validate methods. We can be sure only for init method because it is implemented internally in base-plugin.rb, for all other methods we need to check if they exist.
[ "Initializes", "the", "plugin", "by", "executing", "init", "after_init", "validate", "and", "after_validate", "methods", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/appliance.rb#L88-L114
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/appliance.rb
BoxGrinder.Appliance.create
def create @log.debug "Launching new build..." @log.trace "Used configuration: #{@config.to_yaml.gsub(/(\S*(key|account|cert|username|host|password)\S*).*:(.*)/, '\1' + ": <REDACTED>")}" # Let's load all plugins first PluginHelper.new(@config, :log => @log).load_plugins read_definition validate_definition initialize_plugins remove_old_builds if @config.force execute_plugin_chain self end
ruby
def create @log.debug "Launching new build..." @log.trace "Used configuration: #{@config.to_yaml.gsub(/(\S*(key|account|cert|username|host|password)\S*).*:(.*)/, '\1' + ": <REDACTED>")}" # Let's load all plugins first PluginHelper.new(@config, :log => @log).load_plugins read_definition validate_definition initialize_plugins remove_old_builds if @config.force execute_plugin_chain self end
[ "def", "create", "@log", ".", "debug", "\"Launching new build...\"", "@log", ".", "trace", "\"Used configuration: #{@config.to_yaml.gsub(/(\\S*(key|account|cert|username|host|password)\\S*).*:(.*)/, '\\1' + \": <REDACTED>\")}\"", "PluginHelper", ".", "new", "(", "@config", ",", ":log", "=>", "@log", ")", ".", "load_plugins", "read_definition", "validate_definition", "initialize_plugins", "remove_old_builds", "if", "@config", ".", "force", "execute_plugin_chain", "self", "end" ]
This creates the appliance by executing the plugin chain. Definition is read and validated. Afterwards a plugin chain is created and every plugin in the chain is initialized and validated. The next step is the execution of the plugin chain, step by step. Below you can find the whole process of bootstrapping a plugin. Call Scope ------------------------------------------ initialize required, internal init required, internal after_init optional, user implemented validate optional, user implemented after_validate optional, user implemented execute required, user implemented after_execute optional, user implemented
[ "This", "creates", "the", "appliance", "by", "executing", "the", "plugin", "chain", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/appliance.rb#L152-L167
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-capabilities.rb
BoxGrinder.LibvirtCapabilities.determine_capabilities
def determine_capabilities(conn, previous_plugin_info) plugin = get_plugin(previous_plugin_info) root = Nokogiri::XML.parse(conn.capabilities) guests = root.xpath("//guest/arch[@name='x86_64']/..") guests = guests.sort do |a, b| dom_maps = [a,b].map { |x| plugin.domain_map[xpath_first_intern(x, './/domain/@type')] } # Handle unknown mappings next resolve_unknowns(dom_maps) if dom_maps.include?(nil) # Compare according to domain ranking dom_rank = dom_maps.map { |m| m[:rank]}.reduce(:<=>) # Compare according to virtualisation ranking virt_rank = [a,b].enum_for(:each_with_index).map do |x, i| dom_maps[i][:domain].virt_map[xpath_first_intern(x, './/os_type')] end # Handle unknown mappings next resolve_unknowns(virt_rank) if virt_rank.include?(nil) # Domain rank first next dom_rank unless dom_rank == 0 # OS type rank second virt_rank.reduce(:<=>) end # Favourite! build_guest(guests.first) end
ruby
def determine_capabilities(conn, previous_plugin_info) plugin = get_plugin(previous_plugin_info) root = Nokogiri::XML.parse(conn.capabilities) guests = root.xpath("//guest/arch[@name='x86_64']/..") guests = guests.sort do |a, b| dom_maps = [a,b].map { |x| plugin.domain_map[xpath_first_intern(x, './/domain/@type')] } # Handle unknown mappings next resolve_unknowns(dom_maps) if dom_maps.include?(nil) # Compare according to domain ranking dom_rank = dom_maps.map { |m| m[:rank]}.reduce(:<=>) # Compare according to virtualisation ranking virt_rank = [a,b].enum_for(:each_with_index).map do |x, i| dom_maps[i][:domain].virt_map[xpath_first_intern(x, './/os_type')] end # Handle unknown mappings next resolve_unknowns(virt_rank) if virt_rank.include?(nil) # Domain rank first next dom_rank unless dom_rank == 0 # OS type rank second virt_rank.reduce(:<=>) end # Favourite! build_guest(guests.first) end
[ "def", "determine_capabilities", "(", "conn", ",", "previous_plugin_info", ")", "plugin", "=", "get_plugin", "(", "previous_plugin_info", ")", "root", "=", "Nokogiri", "::", "XML", ".", "parse", "(", "conn", ".", "capabilities", ")", "guests", "=", "root", ".", "xpath", "(", "\"//guest/arch[@name='x86_64']/..\"", ")", "guests", "=", "guests", ".", "sort", "do", "|", "a", ",", "b", "|", "dom_maps", "=", "[", "a", ",", "b", "]", ".", "map", "{", "|", "x", "|", "plugin", ".", "domain_map", "[", "xpath_first_intern", "(", "x", ",", "'.//domain/@type'", ")", "]", "}", "next", "resolve_unknowns", "(", "dom_maps", ")", "if", "dom_maps", ".", "include?", "(", "nil", ")", "dom_rank", "=", "dom_maps", ".", "map", "{", "|", "m", "|", "m", "[", ":rank", "]", "}", ".", "reduce", "(", ":<=>", ")", "virt_rank", "=", "[", "a", ",", "b", "]", ".", "enum_for", "(", ":each_with_index", ")", ".", "map", "do", "|", "x", ",", "i", "|", "dom_maps", "[", "i", "]", "[", ":domain", "]", ".", "virt_map", "[", "xpath_first_intern", "(", "x", ",", "'.//os_type'", ")", "]", "end", "next", "resolve_unknowns", "(", "virt_rank", ")", "if", "virt_rank", ".", "include?", "(", "nil", ")", "next", "dom_rank", "unless", "dom_rank", "==", "0", "virt_rank", ".", "reduce", "(", ":<=>", ")", "end", "build_guest", "(", "guests", ".", "first", ")", "end" ]
Connect to the remote machine and determine the best available settings
[ "Connect", "to", "the", "remote", "machine", "and", "determine", "the", "best", "available", "settings" ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-capabilities.rb#L95-L125
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-capabilities.rb
BoxGrinder.LibvirtCapabilities.get_plugin
def get_plugin(previous_plugin_info) if previous_plugin_info[:type] == :platform if PLUGINS.has_key?(previous_plugin_info[:name]) @log.debug("Using #{previous_plugin_info[:name]} mapping") return PLUGINS[previous_plugin_info[:name]] else @log.debug("This plugin does not know what mappings to choose, so will assume default values where user values are not provided.") end end @log.debug("Using default domain mappings.") PLUGINS[:default] end
ruby
def get_plugin(previous_plugin_info) if previous_plugin_info[:type] == :platform if PLUGINS.has_key?(previous_plugin_info[:name]) @log.debug("Using #{previous_plugin_info[:name]} mapping") return PLUGINS[previous_plugin_info[:name]] else @log.debug("This plugin does not know what mappings to choose, so will assume default values where user values are not provided.") end end @log.debug("Using default domain mappings.") PLUGINS[:default] end
[ "def", "get_plugin", "(", "previous_plugin_info", ")", "if", "previous_plugin_info", "[", ":type", "]", "==", ":platform", "if", "PLUGINS", ".", "has_key?", "(", "previous_plugin_info", "[", ":name", "]", ")", "@log", ".", "debug", "(", "\"Using #{previous_plugin_info[:name]} mapping\"", ")", "return", "PLUGINS", "[", "previous_plugin_info", "[", ":name", "]", "]", "else", "@log", ".", "debug", "(", "\"This plugin does not know what mappings to choose, so will assume default values where user values are not provided.\"", ")", "end", "end", "@log", ".", "debug", "(", "\"Using default domain mappings.\"", ")", "PLUGINS", "[", ":default", "]", "end" ]
At present we don't have enough meta-data to work with to easily generalise, so we have to assume defaults often. This is something to improve later.
[ "At", "present", "we", "don", "t", "have", "enough", "meta", "-", "data", "to", "work", "with", "to", "easily", "generalise", "so", "we", "have", "to", "assume", "defaults", "often", ".", "This", "is", "something", "to", "improve", "later", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-capabilities.rb#L151-L162
train
bitpay/spree-bitpay
app/controllers/spree/bitpay_controller.rb
Spree.BitpayController.pay_now
def pay_now order = current_order || raise(ActiveRecord::RecordNotFound) session[:order_number] = current_order.number invoice = order.place_bitpay_order notificationURL: bitpay_notification_url @invoice_iframe_url = "#{invoice['url']}&view=iframe" render json: @invoice_iframe_url end
ruby
def pay_now order = current_order || raise(ActiveRecord::RecordNotFound) session[:order_number] = current_order.number invoice = order.place_bitpay_order notificationURL: bitpay_notification_url @invoice_iframe_url = "#{invoice['url']}&view=iframe" render json: @invoice_iframe_url end
[ "def", "pay_now", "order", "=", "current_order", "||", "raise", "(", "ActiveRecord", "::", "RecordNotFound", ")", "session", "[", ":order_number", "]", "=", "current_order", ".", "number", "invoice", "=", "order", ".", "place_bitpay_order", "notificationURL", ":", "bitpay_notification_url", "@invoice_iframe_url", "=", "\"#{invoice['url']}&view=iframe\"", "render", "json", ":", "@invoice_iframe_url", "end" ]
Generates Bitpay Invoice and returns iframe view
[ "Generates", "Bitpay", "Invoice", "and", "returns", "iframe", "view" ]
581d97bdce29ea97bf923356640ffff6a7ef3b0b
https://github.com/bitpay/spree-bitpay/blob/581d97bdce29ea97bf923356640ffff6a7ef3b0b/app/controllers/spree/bitpay_controller.rb#L7-L13
train
bitpay/spree-bitpay
app/controllers/spree/bitpay_controller.rb
Spree.BitpayController.payment_sent
def payment_sent order_number = session[:order_number] session[:order_number] = nil order = Spree::Order.find_by_number(order_number) || raise(ActiveRecord::RecordNotFound) redirect_to spree.order_path(order), :notice => Spree.t(:order_processed_successfully) end
ruby
def payment_sent order_number = session[:order_number] session[:order_number] = nil order = Spree::Order.find_by_number(order_number) || raise(ActiveRecord::RecordNotFound) redirect_to spree.order_path(order), :notice => Spree.t(:order_processed_successfully) end
[ "def", "payment_sent", "order_number", "=", "session", "[", ":order_number", "]", "session", "[", ":order_number", "]", "=", "nil", "order", "=", "Spree", "::", "Order", ".", "find_by_number", "(", "order_number", ")", "||", "raise", "(", "ActiveRecord", "::", "RecordNotFound", ")", "redirect_to", "spree", ".", "order_path", "(", "order", ")", ",", ":notice", "=>", "Spree", ".", "t", "(", ":order_processed_successfully", ")", "end" ]
Fires on receipt of payment received window message
[ "Fires", "on", "receipt", "of", "payment", "received", "window", "message" ]
581d97bdce29ea97bf923356640ffff6a7ef3b0b
https://github.com/bitpay/spree-bitpay/blob/581d97bdce29ea97bf923356640ffff6a7ef3b0b/app/controllers/spree/bitpay_controller.rb#L39-L44
train
bitpay/spree-bitpay
app/controllers/spree/bitpay_controller.rb
Spree.BitpayController.notification
def notification begin posData = JSON.parse(params["posData"]) order_id = posData["orderID"] payment_id = posData["paymentID"] order = Spree::Order.find_by_number(order_id) || raise(ActiveRecord::RecordNotFound) begin order.process_bitpay_ipn payment_id head :ok rescue => exception logger.debug exception head :uprocessable_entity end rescue => error logger.error "Spree_Bitpay: Unprocessable notification received from #{request.remote_ip}: #{params.inspect}" head :unprocessable_entity end end
ruby
def notification begin posData = JSON.parse(params["posData"]) order_id = posData["orderID"] payment_id = posData["paymentID"] order = Spree::Order.find_by_number(order_id) || raise(ActiveRecord::RecordNotFound) begin order.process_bitpay_ipn payment_id head :ok rescue => exception logger.debug exception head :uprocessable_entity end rescue => error logger.error "Spree_Bitpay: Unprocessable notification received from #{request.remote_ip}: #{params.inspect}" head :unprocessable_entity end end
[ "def", "notification", "begin", "posData", "=", "JSON", ".", "parse", "(", "params", "[", "\"posData\"", "]", ")", "order_id", "=", "posData", "[", "\"orderID\"", "]", "payment_id", "=", "posData", "[", "\"paymentID\"", "]", "order", "=", "Spree", "::", "Order", ".", "find_by_number", "(", "order_id", ")", "||", "raise", "(", "ActiveRecord", "::", "RecordNotFound", ")", "begin", "order", ".", "process_bitpay_ipn", "payment_id", "head", ":ok", "rescue", "=>", "exception", "logger", ".", "debug", "exception", "head", ":uprocessable_entity", "end", "rescue", "=>", "error", "logger", ".", "error", "\"Spree_Bitpay: Unprocessable notification received from #{request.remote_ip}: #{params.inspect}\"", "head", ":unprocessable_entity", "end", "end" ]
Handle IPN from Bitpay server Receives incoming IPN message and retrieves official BitPay invoice for processing
[ "Handle", "IPN", "from", "Bitpay", "server", "Receives", "incoming", "IPN", "message", "and", "retrieves", "official", "BitPay", "invoice", "for", "processing" ]
581d97bdce29ea97bf923356640ffff6a7ef3b0b
https://github.com/bitpay/spree-bitpay/blob/581d97bdce29ea97bf923356640ffff6a7ef3b0b/app/controllers/spree/bitpay_controller.rb#L49-L69
train
bitpay/spree-bitpay
app/controllers/spree/bitpay_controller.rb
Spree.BitpayController.refresh
def refresh payment = Spree::Payment.find(params[:payment]) # Retrieve payment by ID old_state = payment.state payment.process_bitpay_ipn new_state = payment.reload.state notice = (new_state == old_state) ? Spree.t(:bitpay_payment_not_updated) : (Spree.t(:bitpay_payment_updated) + new_state.titlecase) redirect_to (request.referrer || root_path), notice: notice end
ruby
def refresh payment = Spree::Payment.find(params[:payment]) # Retrieve payment by ID old_state = payment.state payment.process_bitpay_ipn new_state = payment.reload.state notice = (new_state == old_state) ? Spree.t(:bitpay_payment_not_updated) : (Spree.t(:bitpay_payment_updated) + new_state.titlecase) redirect_to (request.referrer || root_path), notice: notice end
[ "def", "refresh", "payment", "=", "Spree", "::", "Payment", ".", "find", "(", "params", "[", ":payment", "]", ")", "old_state", "=", "payment", ".", "state", "payment", ".", "process_bitpay_ipn", "new_state", "=", "payment", ".", "reload", ".", "state", "notice", "=", "(", "new_state", "==", "old_state", ")", "?", "Spree", ".", "t", "(", ":bitpay_payment_not_updated", ")", ":", "(", "Spree", ".", "t", "(", ":bitpay_payment_updated", ")", "+", "new_state", ".", "titlecase", ")", "redirect_to", "(", "request", ".", "referrer", "||", "root_path", ")", ",", "notice", ":", "notice", "end" ]
Reprocess Invoice and update order status
[ "Reprocess", "Invoice", "and", "update", "order", "status" ]
581d97bdce29ea97bf923356640ffff6a7ef3b0b
https://github.com/bitpay/spree-bitpay/blob/581d97bdce29ea97bf923356640ffff6a7ef3b0b/app/controllers/spree/bitpay_controller.rb#L73-L80
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/platform/ec2/ec2-plugin.rb
BoxGrinder.EC2Plugin.add_ec2_user
def add_ec2_user(guestfs) @log.debug "Adding ec2-user user..." # We need to add ec2-user only when it doesn't exists # # https://issues.jboss.org/browse/BGBUILD-313 unless guestfs.fgrep("ec2-user", "/etc/passwd").empty? @log.debug("ec2-user already exists, skipping.") return end guestfs.sh("useradd ec2-user") guestfs.sh("echo -e 'ec2-user\tALL=(ALL)\tNOPASSWD: ALL' >> /etc/sudoers") @log.debug "User ec2-user added." end
ruby
def add_ec2_user(guestfs) @log.debug "Adding ec2-user user..." # We need to add ec2-user only when it doesn't exists # # https://issues.jboss.org/browse/BGBUILD-313 unless guestfs.fgrep("ec2-user", "/etc/passwd").empty? @log.debug("ec2-user already exists, skipping.") return end guestfs.sh("useradd ec2-user") guestfs.sh("echo -e 'ec2-user\tALL=(ALL)\tNOPASSWD: ALL' >> /etc/sudoers") @log.debug "User ec2-user added." end
[ "def", "add_ec2_user", "(", "guestfs", ")", "@log", ".", "debug", "\"Adding ec2-user user...\"", "unless", "guestfs", ".", "fgrep", "(", "\"ec2-user\"", ",", "\"/etc/passwd\"", ")", ".", "empty?", "@log", ".", "debug", "(", "\"ec2-user already exists, skipping.\"", ")", "return", "end", "guestfs", ".", "sh", "(", "\"useradd ec2-user\"", ")", "guestfs", ".", "sh", "(", "\"echo -e 'ec2-user\\tALL=(ALL)\\tNOPASSWD: ALL' >> /etc/sudoers\"", ")", "@log", ".", "debug", "\"User ec2-user added.\"", "end" ]
Adds ec2-user will full sudo access without password per Fedora security guidelines. We should not use root access on AMIs as it is not secure and prohibited by AWS. https://issues.jboss.org/browse/BGBUILD-110
[ "Adds", "ec2", "-", "user", "will", "full", "sudo", "access", "without", "password", "per", "Fedora", "security", "guidelines", ".", "We", "should", "not", "use", "root", "access", "on", "AMIs", "as", "it", "is", "not", "secure", "and", "prohibited", "by", "AWS", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/platform/ec2/ec2-plugin.rb#L159-L174
train
enkessler/cucumber_analytics
lib/cucumber_analytics/step.rb
CucumberAnalytics.Step.step_text
def step_text(options = {}) options = {:with_keywords => true, :with_arguments => true, :left_delimiter => self.left_delimiter, :right_delimiter => self.right_delimiter}.merge(options) final_step = [] step_text = '' step_text += "#{@keyword} " if options[:with_keywords] if options[:with_arguments] step_text += @base final_step << step_text final_step.concat(rebuild_block_text(@block)) if @block else step_text += stripped_step(@base, options[:left_delimiter], options[:right_delimiter]) final_step << step_text end final_step end
ruby
def step_text(options = {}) options = {:with_keywords => true, :with_arguments => true, :left_delimiter => self.left_delimiter, :right_delimiter => self.right_delimiter}.merge(options) final_step = [] step_text = '' step_text += "#{@keyword} " if options[:with_keywords] if options[:with_arguments] step_text += @base final_step << step_text final_step.concat(rebuild_block_text(@block)) if @block else step_text += stripped_step(@base, options[:left_delimiter], options[:right_delimiter]) final_step << step_text end final_step end
[ "def", "step_text", "(", "options", "=", "{", "}", ")", "options", "=", "{", ":with_keywords", "=>", "true", ",", ":with_arguments", "=>", "true", ",", ":left_delimiter", "=>", "self", ".", "left_delimiter", ",", ":right_delimiter", "=>", "self", ".", "right_delimiter", "}", ".", "merge", "(", "options", ")", "final_step", "=", "[", "]", "step_text", "=", "''", "step_text", "+=", "\"#{@keyword} \"", "if", "options", "[", ":with_keywords", "]", "if", "options", "[", ":with_arguments", "]", "step_text", "+=", "@base", "final_step", "<<", "step_text", "final_step", ".", "concat", "(", "rebuild_block_text", "(", "@block", ")", ")", "if", "@block", "else", "step_text", "+=", "stripped_step", "(", "@base", ",", "options", "[", ":left_delimiter", "]", ",", "options", "[", ":right_delimiter", "]", ")", "final_step", "<<", "step_text", "end", "final_step", "end" ]
Returns true if the two steps have the same text, minus any keywords and arguments, and false otherwise. Deprecated Returns the entire text of the step. Options can be set to selectively exclude certain portions of the text. *left_delimiter* and *right_delimiter* are used to determine which parts of the step are arguments. a_step = CucumberAnalytics::Step.new("Given *some* step with a block:\n|block line 1|\n|block line 2|") a_step.step_text #=> ['Given *some* step with a block:', '|block line 1|', '|block line 2|'] a_step.step_text(:with_keywords => false) #=> ['*some* step with a block:', '|block line 1|', '|block line 2|'] a_step.step_text(:with_arguments => false, :left_delimiter => '*', :right_delimiter => '*') #=> ['Given ** step with a block:'] a_step.step_text(:with_keywords => false, :with_arguments => false, :left_delimiter => '-', :right_delimiter => '-')) #=> ['*some* step with a block:']
[ "Returns", "true", "if", "the", "two", "steps", "have", "the", "same", "text", "minus", "any", "keywords", "and", "arguments", "and", "false", "otherwise", ".", "Deprecated" ]
a74642d30b3566fc11fb43c920518fea4587c6bd
https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/step.rb#L95-L116
train
enkessler/cucumber_analytics
lib/cucumber_analytics/step.rb
CucumberAnalytics.Step.scan_arguments
def scan_arguments(*how) if how.count == 1 pattern = how.first else left_delimiter = how[0] || self.left_delimiter right_delimiter = how[1] || self.right_delimiter return [] unless left_delimiter && right_delimiter pattern = Regexp.new(Regexp.escape(left_delimiter) + '(.*?)' + Regexp.escape(right_delimiter)) end @arguments = @base.scan(pattern).flatten end
ruby
def scan_arguments(*how) if how.count == 1 pattern = how.first else left_delimiter = how[0] || self.left_delimiter right_delimiter = how[1] || self.right_delimiter return [] unless left_delimiter && right_delimiter pattern = Regexp.new(Regexp.escape(left_delimiter) + '(.*?)' + Regexp.escape(right_delimiter)) end @arguments = @base.scan(pattern).flatten end
[ "def", "scan_arguments", "(", "*", "how", ")", "if", "how", ".", "count", "==", "1", "pattern", "=", "how", ".", "first", "else", "left_delimiter", "=", "how", "[", "0", "]", "||", "self", ".", "left_delimiter", "right_delimiter", "=", "how", "[", "1", "]", "||", "self", ".", "right_delimiter", "return", "[", "]", "unless", "left_delimiter", "&&", "right_delimiter", "pattern", "=", "Regexp", ".", "new", "(", "Regexp", ".", "escape", "(", "left_delimiter", ")", "+", "'(.*?)'", "+", "Regexp", ".", "escape", "(", "right_delimiter", ")", ")", "end", "@arguments", "=", "@base", ".", "scan", "(", "pattern", ")", ".", "flatten", "end" ]
Populates the step's arguments based on the step's text and some method of determining which parts of the text are arguments. Methods include using a regular expression and using the step's delimiters.
[ "Populates", "the", "step", "s", "arguments", "based", "on", "the", "step", "s", "text", "and", "some", "method", "of", "determining", "which", "parts", "of", "the", "text", "are", "arguments", ".", "Methods", "include", "using", "a", "regular", "expression", "and", "using", "the", "step", "s", "delimiters", "." ]
a74642d30b3566fc11fb43c920518fea4587c6bd
https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/step.rb#L121-L134
train
enkessler/cucumber_analytics
lib/cucumber_analytics/step.rb
CucumberAnalytics.Step.stripped_step
def stripped_step(step, left_delimiter, right_delimiter) unless left_delimiter.nil? || right_delimiter.nil? pattern = Regexp.new(Regexp.escape(left_delimiter) + '.*?' + Regexp.escape(right_delimiter)) step = step.gsub(pattern, left_delimiter + right_delimiter) end step end
ruby
def stripped_step(step, left_delimiter, right_delimiter) unless left_delimiter.nil? || right_delimiter.nil? pattern = Regexp.new(Regexp.escape(left_delimiter) + '.*?' + Regexp.escape(right_delimiter)) step = step.gsub(pattern, left_delimiter + right_delimiter) end step end
[ "def", "stripped_step", "(", "step", ",", "left_delimiter", ",", "right_delimiter", ")", "unless", "left_delimiter", ".", "nil?", "||", "right_delimiter", ".", "nil?", "pattern", "=", "Regexp", ".", "new", "(", "Regexp", ".", "escape", "(", "left_delimiter", ")", "+", "'.*?'", "+", "Regexp", ".", "escape", "(", "right_delimiter", ")", ")", "step", "=", "step", ".", "gsub", "(", "pattern", ",", "left_delimiter", "+", "right_delimiter", ")", "end", "step", "end" ]
Returns the step string minus any arguments based on the given delimiters.
[ "Returns", "the", "step", "string", "minus", "any", "arguments", "based", "on", "the", "given", "delimiters", "." ]
a74642d30b3566fc11fb43c920518fea4587c6bd
https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/step.rb#L189-L196
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb
BoxGrinder.RPMBasedOSPlugin.substitute_vars
def substitute_vars(str) return if str.nil? @appliance_config.variables.keys.each do |var| str = str.gsub("##{var}#", @appliance_config.variables[var]) end str end
ruby
def substitute_vars(str) return if str.nil? @appliance_config.variables.keys.each do |var| str = str.gsub("##{var}#", @appliance_config.variables[var]) end str end
[ "def", "substitute_vars", "(", "str", ")", "return", "if", "str", ".", "nil?", "@appliance_config", ".", "variables", ".", "keys", ".", "each", "do", "|", "var", "|", "str", "=", "str", ".", "gsub", "(", "\"##{var}#\"", ",", "@appliance_config", ".", "variables", "[", "var", "]", ")", "end", "str", "end" ]
Substitute variables in selected string.
[ "Substitute", "variables", "in", "selected", "string", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb#L53-L59
train
boxgrinder/boxgrinder-build
lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb
BoxGrinder.RPMBasedOSPlugin.install_files
def install_files(guestfs) @log.debug "Installing files specified in appliance definition file..." @appliance_config.files.each do |dir, files| @log.debug "Proceding files for '#{dir}' destination directory..." local_files = [] # Create the directory if it doesn't exists guestfs.mkdir_p(dir) unless guestfs.exists(dir) != 0 files.each do |f| if f.match(/^(http|ftp|https):\/\//) # Remote url provided @log.trace "Remote url detected: '#{f}'." # We have a remote file, try to download it using curl! guestfs.sh("cd #{dir} && curl -O -L #{f}") else @log.trace "Local path detected: '#{f}'." file_path = (f.match(/^\//) ? f : "#{File.dirname(@appliance_definition_file)}/#{f}") # TODO validate this earlier raise ValidationError, "File '#{f}' specified in files section of appliance definition file doesn't exists." unless File.exists?(file_path) local_files << f end end next if local_files.empty? @log.trace "Tarring files..." @exec_helper.execute("cd #{File.dirname(@appliance_definition_file)} && tar -cvf /tmp/bg_install_files.tar --wildcards #{local_files.join(' ')}") @log.trace "Files tarred." @log.trace "Uploading and unpacking..." guestfs.tar_in("/tmp/bg_install_files.tar", dir) @log.trace "Files uploaded." end @log.debug "Files installed." end
ruby
def install_files(guestfs) @log.debug "Installing files specified in appliance definition file..." @appliance_config.files.each do |dir, files| @log.debug "Proceding files for '#{dir}' destination directory..." local_files = [] # Create the directory if it doesn't exists guestfs.mkdir_p(dir) unless guestfs.exists(dir) != 0 files.each do |f| if f.match(/^(http|ftp|https):\/\//) # Remote url provided @log.trace "Remote url detected: '#{f}'." # We have a remote file, try to download it using curl! guestfs.sh("cd #{dir} && curl -O -L #{f}") else @log.trace "Local path detected: '#{f}'." file_path = (f.match(/^\//) ? f : "#{File.dirname(@appliance_definition_file)}/#{f}") # TODO validate this earlier raise ValidationError, "File '#{f}' specified in files section of appliance definition file doesn't exists." unless File.exists?(file_path) local_files << f end end next if local_files.empty? @log.trace "Tarring files..." @exec_helper.execute("cd #{File.dirname(@appliance_definition_file)} && tar -cvf /tmp/bg_install_files.tar --wildcards #{local_files.join(' ')}") @log.trace "Files tarred." @log.trace "Uploading and unpacking..." guestfs.tar_in("/tmp/bg_install_files.tar", dir) @log.trace "Files uploaded." end @log.debug "Files installed." end
[ "def", "install_files", "(", "guestfs", ")", "@log", ".", "debug", "\"Installing files specified in appliance definition file...\"", "@appliance_config", ".", "files", ".", "each", "do", "|", "dir", ",", "files", "|", "@log", ".", "debug", "\"Proceding files for '#{dir}' destination directory...\"", "local_files", "=", "[", "]", "guestfs", ".", "mkdir_p", "(", "dir", ")", "unless", "guestfs", ".", "exists", "(", "dir", ")", "!=", "0", "files", ".", "each", "do", "|", "f", "|", "if", "f", ".", "match", "(", "/", "\\/", "\\/", "/", ")", "@log", ".", "trace", "\"Remote url detected: '#{f}'.\"", "guestfs", ".", "sh", "(", "\"cd #{dir} && curl -O -L #{f}\"", ")", "else", "@log", ".", "trace", "\"Local path detected: '#{f}'.\"", "file_path", "=", "(", "f", ".", "match", "(", "/", "\\/", "/", ")", "?", "f", ":", "\"#{File.dirname(@appliance_definition_file)}/#{f}\"", ")", "raise", "ValidationError", ",", "\"File '#{f}' specified in files section of appliance definition file doesn't exists.\"", "unless", "File", ".", "exists?", "(", "file_path", ")", "local_files", "<<", "f", "end", "end", "next", "if", "local_files", ".", "empty?", "@log", ".", "trace", "\"Tarring files...\"", "@exec_helper", ".", "execute", "(", "\"cd #{File.dirname(@appliance_definition_file)} && tar -cvf /tmp/bg_install_files.tar --wildcards #{local_files.join(' ')}\"", ")", "@log", ".", "trace", "\"Files tarred.\"", "@log", ".", "trace", "\"Uploading and unpacking...\"", "guestfs", ".", "tar_in", "(", "\"/tmp/bg_install_files.tar\"", ",", "dir", ")", "@log", ".", "trace", "\"Files uploaded.\"", "end", "@log", ".", "debug", "\"Files installed.\"", "end" ]
Copies specified files into appliance. There are two types of paths: 1. remote - starting with http:// or https:// or ftp:// 2. local - all other. Please use relative paths. Relative means relative to the appliance definition file. Using absolute paths will cause creating whole directory structure in appliance, which is most probably not exactly what you want. https://issues.jboss.org/browse/BGBUILD-276
[ "Copies", "specified", "files", "into", "appliance", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb#L288-L331
train
kayagoban/echochamber
lib/echochamber/library_documents/client.rb
Echochamber.Client.get_library_document_file
def get_library_document_file(library_document_id, file_id, file_path=nil) response = Echochamber::Request.get_library_document_file(token, library_document_id, file_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
def get_library_document_file(library_document_id, file_id, file_path=nil) response = Echochamber::Request.get_library_document_file(token, library_document_id, file_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
[ "def", "get_library_document_file", "(", "library_document_id", ",", "file_id", ",", "file_path", "=", "nil", ")", "response", "=", "Echochamber", "::", "Request", ".", "get_library_document_file", "(", "token", ",", "library_document_id", ",", "file_id", ")", "unless", "file_path", ".", "nil?", "file", "=", "File", ".", "new", "(", "file_path", ",", "'wb'", ")", "file", ".", "write", "(", "response", ")", "file", ".", "close", "end", "response", "end" ]
Retrieves library document file data @param library_document_id (REQUIRED) @param file_id [String] (REQUIRED) @param file_path [String] File path for saving the document. If none is given, nothing will be saved to disk. @return [String] Raw library document file data
[ "Retrieves", "library", "document", "file", "data" ]
a3665c6b78928e3efa7ba578b899c31aa5c893a4
https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/library_documents/client.rb#L36-L44
train