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
gbiczo/oxcelix
lib/oxcelix/sheet.rb
Oxcelix.Sheet.to_m
def to_m(*attrs) m=Matrix.build(self.row_size, self.column_size){nil} self.each_with_index do |x, row, col| if attrs.size == 0 || attrs.nil? m[row, col] = x.value end end return m end
ruby
def to_m(*attrs) m=Matrix.build(self.row_size, self.column_size){nil} self.each_with_index do |x, row, col| if attrs.size == 0 || attrs.nil? m[row, col] = x.value end end return m end
[ "def", "to_m", "(", "*", "attrs", ")", "m", "=", "Matrix", ".", "build", "(", "self", ".", "row_size", ",", "self", ".", "column_size", ")", "{", "nil", "}", "self", ".", "each_with_index", "do", "|", "x", ",", "row", ",", "col", "|", "if", "attrs", ".", "size", "==", "0", "||", "attrs", ".", "nil?", "m", "[", "row", ",", "col", "]", "=", "x", ".", "value", "end", "end", "return", "m", "end" ]
The to_m method returns a simple Matrix object filled with the raw values of the original Sheet object. @return [Matrix] a collection of string values (the former #Cell::value)
[ "The", "to_m", "method", "returns", "a", "simple", "Matrix", "object", "filled", "with", "the", "raw", "values", "of", "the", "original", "Sheet", "object", "." ]
144378e62c5288781db53345ec9d400dc7a70dc3
https://github.com/gbiczo/oxcelix/blob/144378e62c5288781db53345ec9d400dc7a70dc3/lib/oxcelix/sheet.rb#L32-L40
train
loco2/lolsoap
lib/lolsoap/envelope.rb
LolSoap.Envelope.body
def body(klass = Builder) builder = klass.new(body_content, input_body_content_type) yield builder if block_given? builder end
ruby
def body(klass = Builder) builder = klass.new(body_content, input_body_content_type) yield builder if block_given? builder end
[ "def", "body", "(", "klass", "=", "Builder", ")", "builder", "=", "klass", ".", "new", "(", "body_content", ",", "input_body_content_type", ")", "yield", "builder", "if", "block_given?", "builder", "end" ]
Build the body of the envelope @example env.body do |b| b.some 'data' end
[ "Build", "the", "body", "of", "the", "envelope" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/envelope.rb#L28-L32
train
loco2/lolsoap
lib/lolsoap/envelope.rb
LolSoap.Envelope.header
def header(klass = Builder) builder = klass.new(header_content, input_header_content_type) yield builder if block_given? builder end
ruby
def header(klass = Builder) builder = klass.new(header_content, input_header_content_type) yield builder if block_given? builder end
[ "def", "header", "(", "klass", "=", "Builder", ")", "builder", "=", "klass", ".", "new", "(", "header_content", ",", "input_header_content_type", ")", "yield", "builder", "if", "block_given?", "builder", "end" ]
Build the header of the envelope
[ "Build", "the", "header", "of", "the", "envelope" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/envelope.rb#L35-L39
train
orta/gh_inspector
lib/gh_inspector/inspector.rb
GhInspector.Inspector.search_exception
def search_exception(exception, delegate = nil) query = ExceptionHound.new(exception).query search_query(query, delegate) end
ruby
def search_exception(exception, delegate = nil) query = ExceptionHound.new(exception).query search_query(query, delegate) end
[ "def", "search_exception", "(", "exception", ",", "delegate", "=", "nil", ")", "query", "=", "ExceptionHound", ".", "new", "(", "exception", ")", ".", "query", "search_query", "(", "query", ",", "delegate", ")", "end" ]
Init function with "orta", "project" Will do some magic to try and pull out a reasonable search query for an exception, then searches with that
[ "Init", "function", "with", "orta", "project", "Will", "do", "some", "magic", "to", "try", "and", "pull", "out", "a", "reasonable", "search", "query", "for", "an", "exception", "then", "searches", "with", "that" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/inspector.rb#L60-L63
train
orta/gh_inspector
lib/gh_inspector/inspector.rb
GhInspector.Inspector.search_query
def search_query(query, delegate = nil) delegate ||= Evidence.new sidekick.search(query, delegate) end
ruby
def search_query(query, delegate = nil) delegate ||= Evidence.new sidekick.search(query, delegate) end
[ "def", "search_query", "(", "query", ",", "delegate", "=", "nil", ")", "delegate", "||=", "Evidence", ".", "new", "sidekick", ".", "search", "(", "query", ",", "delegate", ")", "end" ]
Queries for an specific search string
[ "Queries", "for", "an", "specific", "search", "string" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/inspector.rb#L66-L69
train
loco2/lolsoap
lib/lolsoap/wsdl.rb
LolSoap.WSDL.type
def type(namespace, name) if @allow_abstract_types @types.fetch([namespace, name]) { abstract_type(namespace, name) } else @types.fetch([namespace, name]) { NullType.new } end end
ruby
def type(namespace, name) if @allow_abstract_types @types.fetch([namespace, name]) { abstract_type(namespace, name) } else @types.fetch([namespace, name]) { NullType.new } end end
[ "def", "type", "(", "namespace", ",", "name", ")", "if", "@allow_abstract_types", "@types", ".", "fetch", "(", "[", "namespace", ",", "name", "]", ")", "{", "abstract_type", "(", "namespace", ",", "name", ")", "}", "else", "@types", ".", "fetch", "(", "[", "namespace", ",", "name", "]", ")", "{", "NullType", ".", "new", "}", "end", "end" ]
Get a single type, or a NullType if the type doesn't exist
[ "Get", "a", "single", "type", "or", "a", "NullType", "if", "the", "type", "doesn", "t", "exist" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/wsdl.rb#L54-L60
train
loco2/lolsoap
lib/lolsoap/response.rb
LolSoap.Response.fault
def fault @fault ||= begin node = doc.at_xpath('/soap:Envelope/soap:Body/soap:Fault', 'soap' => soap_namespace) Fault.new(request, node) if node end end
ruby
def fault @fault ||= begin node = doc.at_xpath('/soap:Envelope/soap:Body/soap:Fault', 'soap' => soap_namespace) Fault.new(request, node) if node end end
[ "def", "fault", "@fault", "||=", "begin", "node", "=", "doc", ".", "at_xpath", "(", "'/soap:Envelope/soap:Body/soap:Fault'", ",", "'soap'", "=>", "soap_namespace", ")", "Fault", ".", "new", "(", "request", ",", "node", ")", "if", "node", "end", "end" ]
SOAP fault, if any
[ "SOAP", "fault", "if", "any" ]
499d6db0c2f8c1b20aaa872a50442cdee90599dc
https://github.com/loco2/lolsoap/blob/499d6db0c2f8c1b20aaa872a50442cdee90599dc/lib/lolsoap/response.rb#L47-L52
train
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.search
def search(query, delegate) validate_delegate(delegate) delegate.inspector_started_query(query, inspector) url = url_for_request query begin results = get_api_results(url) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e delegate.inspector_could_not_create_report(e, query, inspector) return end report = parse_results query, results # TODO: progress callback if report.issues.any? if self.using_deprecated_method delegate.inspector_successfully_recieved_report(report, inspector) else delegate.inspector_successfully_received_report(report, inspector) end else # rubocop:disable Style/IfInsideElse if self.using_deprecated_method delegate.inspector_recieved_empty_report(report, inspector) else delegate.inspector_received_empty_report(report, inspector) end # rubocop:enable Style/IfInsideElse end report end
ruby
def search(query, delegate) validate_delegate(delegate) delegate.inspector_started_query(query, inspector) url = url_for_request query begin results = get_api_results(url) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e delegate.inspector_could_not_create_report(e, query, inspector) return end report = parse_results query, results # TODO: progress callback if report.issues.any? if self.using_deprecated_method delegate.inspector_successfully_recieved_report(report, inspector) else delegate.inspector_successfully_received_report(report, inspector) end else # rubocop:disable Style/IfInsideElse if self.using_deprecated_method delegate.inspector_recieved_empty_report(report, inspector) else delegate.inspector_received_empty_report(report, inspector) end # rubocop:enable Style/IfInsideElse end report end
[ "def", "search", "(", "query", ",", "delegate", ")", "validate_delegate", "(", "delegate", ")", "delegate", ".", "inspector_started_query", "(", "query", ",", "inspector", ")", "url", "=", "url_for_request", "query", "begin", "results", "=", "get_api_results", "(", "url", ")", "rescue", "Timeout", "::", "Error", ",", "Errno", "::", "EINVAL", ",", "Errno", "::", "ECONNRESET", ",", "EOFError", ",", "Net", "::", "HTTPBadResponse", ",", "Net", "::", "HTTPHeaderSyntaxError", ",", "Net", "::", "ProtocolError", "=>", "e", "delegate", ".", "inspector_could_not_create_report", "(", "e", ",", "query", ",", "inspector", ")", "return", "end", "report", "=", "parse_results", "query", ",", "results", "if", "report", ".", "issues", ".", "any?", "if", "self", ".", "using_deprecated_method", "delegate", ".", "inspector_successfully_recieved_report", "(", "report", ",", "inspector", ")", "else", "delegate", ".", "inspector_successfully_received_report", "(", "report", ",", "inspector", ")", "end", "else", "if", "self", ".", "using_deprecated_method", "delegate", ".", "inspector_recieved_empty_report", "(", "report", ",", "inspector", ")", "else", "delegate", ".", "inspector_received_empty_report", "(", "report", ",", "inspector", ")", "end", "end", "report", "end" ]
Searches for a query, with a UI delegate
[ "Searches", "for", "a", "query", "with", "a", "UI", "delegate" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L21-L55
train
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.url_for_request
def url_for_request(query, sort_by: nil, order: nil) url = "https://api.github.com/search/issues?q=" url += ERB::Util.url_encode(query) url += "+repo:#{repo_owner}/#{repo_name}" url += "&sort=#{sort_by}" if sort_by url += "&order=#{order}" if order url end
ruby
def url_for_request(query, sort_by: nil, order: nil) url = "https://api.github.com/search/issues?q=" url += ERB::Util.url_encode(query) url += "+repo:#{repo_owner}/#{repo_name}" url += "&sort=#{sort_by}" if sort_by url += "&order=#{order}" if order url end
[ "def", "url_for_request", "(", "query", ",", "sort_by", ":", "nil", ",", "order", ":", "nil", ")", "url", "=", "\"https://api.github.com/search/issues?q=\"", "url", "+=", "ERB", "::", "Util", ".", "url_encode", "(", "query", ")", "url", "+=", "\"+repo:#{repo_owner}/#{repo_name}\"", "url", "+=", "\"&sort=#{sort_by}\"", "if", "sort_by", "url", "+=", "\"&order=#{order}\"", "if", "order", "url", "end" ]
Generates a URL for the request
[ "Generates", "a", "URL", "for", "the", "request" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L66-L74
train
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.get_api_results
def get_api_results(url) uri = URI.parse(url) puts "URL: #{url}" if self.verbose http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) JSON.parse(response.body) end
ruby
def get_api_results(url) uri = URI.parse(url) puts "URL: #{url}" if self.verbose http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) JSON.parse(response.body) end
[ "def", "get_api_results", "(", "url", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "puts", "\"URL: #{url}\"", "if", "self", ".", "verbose", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ")", "response", "=", "http", ".", "request", "(", "request", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Gets the search results
[ "Gets", "the", "search", "results" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L77-L87
train
orta/gh_inspector
lib/gh_inspector/sidekick.rb
GhInspector.Sidekick.parse_results
def parse_results(query, results) report = InspectionReport.new report.url = "https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓" report.query = query report.total_results = results['total_count'] report.issues = results['items'].map { |item| Issue.new(item) } report end
ruby
def parse_results(query, results) report = InspectionReport.new report.url = "https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓" report.query = query report.total_results = results['total_count'] report.issues = results['items'].map { |item| Issue.new(item) } report end
[ "def", "parse_results", "(", "query", ",", "results", ")", "report", "=", "InspectionReport", ".", "new", "report", ".", "url", "=", "\"https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓\"", "report", ".", "query", "=", "query", "report", ".", "total_results", "=", "results", "[", "'total_count'", "]", "report", ".", "issues", "=", "results", "[", "'items'", "]", ".", "map", "{", "|", "item", "|", "Issue", ".", "new", "(", "item", ")", "}", "report", "end" ]
Converts a GitHub search JSON into a InspectionReport
[ "Converts", "a", "GitHub", "search", "JSON", "into", "a", "InspectionReport" ]
f65c3c85a9bb1ad92ee595b6df122957d20cdac8
https://github.com/orta/gh_inspector/blob/f65c3c85a9bb1ad92ee595b6df122957d20cdac8/lib/gh_inspector/sidekick.rb#L90-L97
train
KatanaCode/blogit
app/helpers/blogit/comments_helper.rb
Blogit.CommentsHelper.name_for_comment
def name_for_comment(comment) if comment.website? link_to(comment.name, comment.website, class: "blogit_comment__name_link") else comment.name end + " " + t('wrote', scope: "blogit.comments") end
ruby
def name_for_comment(comment) if comment.website? link_to(comment.name, comment.website, class: "blogit_comment__name_link") else comment.name end + " " + t('wrote', scope: "blogit.comments") end
[ "def", "name_for_comment", "(", "comment", ")", "if", "comment", ".", "website?", "link_to", "(", "comment", ".", "name", ",", "comment", ".", "website", ",", "class", ":", "\"blogit_comment__name_link\"", ")", "else", "comment", ".", "name", "end", "+", "\" \"", "+", "t", "(", "'wrote'", ",", "scope", ":", "\"blogit.comments\"", ")", "end" ]
The commenter's name for a Comment. When the Comment has a website, includes an html link containing their name. Otherwise, just shows the name as a String. comment - A {Blogit::Comment} Returns a String containing the commenter's name.
[ "The", "commenter", "s", "name", "for", "a", "Comment", ".", "When", "the", "Comment", "has", "a", "website", "includes", "an", "html", "link", "containing", "their", "name", ".", "Otherwise", "just", "shows", "the", "name", "as", "a", "String", "." ]
93e3830bacc542970e41cee94d5d8fbb6fdefc3c
https://github.com/KatanaCode/blogit/blob/93e3830bacc542970e41cee94d5d8fbb6fdefc3c/app/helpers/blogit/comments_helper.rb#L11-L17
train
state-machines/state_machines-graphviz
lib/state_machines/graphviz/monkeypatch.rb
StateMachines.Machine.draw
def draw(graph_options = {}) name = graph_options.delete(:name) || "#{owner_class.name}_#{self.name}" draw_options = {:human_name => false} draw_options[:human_name] = graph_options.delete(:human_names) if graph_options.include?(:human_names) graph = Graph.new(name, graph_options) # Add nodes / edges states.by_priority.each { |state| state.draw(graph, draw_options) } events.each { |event| event.draw(graph, self, draw_options) } # Output result graph.output graph end
ruby
def draw(graph_options = {}) name = graph_options.delete(:name) || "#{owner_class.name}_#{self.name}" draw_options = {:human_name => false} draw_options[:human_name] = graph_options.delete(:human_names) if graph_options.include?(:human_names) graph = Graph.new(name, graph_options) # Add nodes / edges states.by_priority.each { |state| state.draw(graph, draw_options) } events.each { |event| event.draw(graph, self, draw_options) } # Output result graph.output graph end
[ "def", "draw", "(", "graph_options", "=", "{", "}", ")", "name", "=", "graph_options", ".", "delete", "(", ":name", ")", "||", "\"#{owner_class.name}_#{self.name}\"", "draw_options", "=", "{", ":human_name", "=>", "false", "}", "draw_options", "[", ":human_name", "]", "=", "graph_options", ".", "delete", "(", ":human_names", ")", "if", "graph_options", ".", "include?", "(", ":human_names", ")", "graph", "=", "Graph", ".", "new", "(", "name", ",", "graph_options", ")", "states", ".", "by_priority", ".", "each", "{", "|", "state", "|", "state", ".", "draw", "(", "graph", ",", "draw_options", ")", "}", "events", ".", "each", "{", "|", "event", "|", "event", ".", "draw", "(", "graph", ",", "self", ",", "draw_options", ")", "}", "graph", ".", "output", "graph", "end" ]
Draws a directed graph of the machine for visualizing the various events, states, and their transitions. This requires both the Ruby graphviz gem and the graphviz library be installed on the system. Configuration options: * <tt>:name</tt> - The name of the file to write to (without the file extension). Default is "#{owner_class.name}_#{name}" * <tt>:path</tt> - The path to write the graph file to. Default is the current directory ("."). * <tt>:format</tt> - The image format to generate the graph in. Default is "png'. * <tt>:font</tt> - The name of the font to draw state names in. Default is "Arial". * <tt>:orientation</tt> - The direction of the graph ("portrait" or "landscape"). Default is "portrait". * <tt>:human_names</tt> - Whether to use human state / event names for node labels on the graph instead of the internal name. Default is false.
[ "Draws", "a", "directed", "graph", "of", "the", "machine", "for", "visualizing", "the", "various", "events", "states", "and", "their", "transitions", "." ]
3c61a39aaee3e804d72bbf97cfa55006506cfef2
https://github.com/state-machines/state_machines-graphviz/blob/3c61a39aaee3e804d72bbf97cfa55006506cfef2/lib/state_machines/graphviz/monkeypatch.rb#L56-L70
train
KatanaCode/blogit
app/helpers/blogit/application_helper.rb
Blogit.ApplicationHelper.div_tag_with_default_class
def div_tag_with_default_class(default_class, content_or_options, options, &block) if block_given? options = content_or_options content = capture(&block) else content = content_or_options end options[:class] = Array(options[:class]) + [default_class] content_tag(:div, content, options) end
ruby
def div_tag_with_default_class(default_class, content_or_options, options, &block) if block_given? options = content_or_options content = capture(&block) else content = content_or_options end options[:class] = Array(options[:class]) + [default_class] content_tag(:div, content, options) end
[ "def", "div_tag_with_default_class", "(", "default_class", ",", "content_or_options", ",", "options", ",", "&", "block", ")", "if", "block_given?", "options", "=", "content_or_options", "content", "=", "capture", "(", "&", "block", ")", "else", "content", "=", "content_or_options", "end", "options", "[", ":class", "]", "=", "Array", "(", "options", "[", ":class", "]", ")", "+", "[", "default_class", "]", "content_tag", "(", ":div", ",", "content", ",", "options", ")", "end" ]
Creates an HTML div with a default class value added default_class - The CSS class name to add to the div content_or_options - The content to include in the div when not using a block. The options Hash when using a block options - The options when not using a block block - A block that returns HTML content to include in the div Returns an HTML safe String
[ "Creates", "an", "HTML", "div", "with", "a", "default", "class", "value", "added" ]
93e3830bacc542970e41cee94d5d8fbb6fdefc3c
https://github.com/KatanaCode/blogit/blob/93e3830bacc542970e41cee94d5d8fbb6fdefc3c/app/helpers/blogit/application_helper.rb#L82-L91
train
ronin/payu
lib/payu/pos.rb
Payu.Pos.validate_options!
def validate_options! raise PosInvalid.new('Missing pos_id parameter') if pos_id.nil? || pos_id == 0 raise PosInvalid.new('Missing pos_auth_key parameter') if pos_auth_key.nil? || pos_auth_key == '' raise PosInvalid.new('Missing key1 parameter') if key1.nil? || key1 == '' raise PosInvalid.new('Missing key2 parameter') if key2.nil? || key2 == '' raise PosInvalid.new("Invalid variant parameter, expected one of these: #{TYPES.join(', ')}") unless TYPES.include?(variant) raise PosInvalid.new("Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}") unless ENCODINGS.include?(encoding) end
ruby
def validate_options! raise PosInvalid.new('Missing pos_id parameter') if pos_id.nil? || pos_id == 0 raise PosInvalid.new('Missing pos_auth_key parameter') if pos_auth_key.nil? || pos_auth_key == '' raise PosInvalid.new('Missing key1 parameter') if key1.nil? || key1 == '' raise PosInvalid.new('Missing key2 parameter') if key2.nil? || key2 == '' raise PosInvalid.new("Invalid variant parameter, expected one of these: #{TYPES.join(', ')}") unless TYPES.include?(variant) raise PosInvalid.new("Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}") unless ENCODINGS.include?(encoding) end
[ "def", "validate_options!", "raise", "PosInvalid", ".", "new", "(", "'Missing pos_id parameter'", ")", "if", "pos_id", ".", "nil?", "||", "pos_id", "==", "0", "raise", "PosInvalid", ".", "new", "(", "'Missing pos_auth_key parameter'", ")", "if", "pos_auth_key", ".", "nil?", "||", "pos_auth_key", "==", "''", "raise", "PosInvalid", ".", "new", "(", "'Missing key1 parameter'", ")", "if", "key1", ".", "nil?", "||", "key1", "==", "''", "raise", "PosInvalid", ".", "new", "(", "'Missing key2 parameter'", ")", "if", "key2", ".", "nil?", "||", "key2", "==", "''", "raise", "PosInvalid", ".", "new", "(", "\"Invalid variant parameter, expected one of these: #{TYPES.join(', ')}\"", ")", "unless", "TYPES", ".", "include?", "(", "variant", ")", "raise", "PosInvalid", ".", "new", "(", "\"Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}\"", ")", "unless", "ENCODINGS", ".", "include?", "(", "encoding", ")", "end" ]
Creates new Pos instance @param [Hash] options options hash @return [Object] Pos object
[ "Creates", "new", "Pos", "instance" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/pos.rb#L30-L37
train
ronin/payu
lib/payu/pos.rb
Payu.Pos.new_transaction
def new_transaction(options = {}) options = options.dup options.merge!({ :pos_id => @pos_id, :pos_auth_key => @pos_auth_key, :gateway_url => options[:gateway_url] || @gateway_url, :key1 => @key1, :encoding => encoding, :variant => variant }) if !options.has_key?(:add_signature) options[:add_signature] = add_signature? end if !options.has_key?(:pay_type) options[:pay_type] = test_payment? ? 't' : nil end Transaction.new(options) end
ruby
def new_transaction(options = {}) options = options.dup options.merge!({ :pos_id => @pos_id, :pos_auth_key => @pos_auth_key, :gateway_url => options[:gateway_url] || @gateway_url, :key1 => @key1, :encoding => encoding, :variant => variant }) if !options.has_key?(:add_signature) options[:add_signature] = add_signature? end if !options.has_key?(:pay_type) options[:pay_type] = test_payment? ? 't' : nil end Transaction.new(options) end
[ "def", "new_transaction", "(", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "options", ".", "merge!", "(", "{", ":pos_id", "=>", "@pos_id", ",", ":pos_auth_key", "=>", "@pos_auth_key", ",", ":gateway_url", "=>", "options", "[", ":gateway_url", "]", "||", "@gateway_url", ",", ":key1", "=>", "@key1", ",", ":encoding", "=>", "encoding", ",", ":variant", "=>", "variant", "}", ")", "if", "!", "options", ".", "has_key?", "(", ":add_signature", ")", "options", "[", ":add_signature", "]", "=", "add_signature?", "end", "if", "!", "options", ".", "has_key?", "(", ":pay_type", ")", "options", "[", ":pay_type", "]", "=", "test_payment?", "?", "'t'", ":", "nil", "end", "Transaction", ".", "new", "(", "options", ")", "end" ]
Creates new transaction @param [Hash] options options hash for new transaction @return [Object] Transaction object
[ "Creates", "new", "transaction" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/pos.rb#L42-L63
train
ronin/payu
lib/payu/helpers.rb
Payu.Helpers.payu_hidden_fields
def payu_hidden_fields(transaction) html = "" %w(pos_id pos_auth_key pay_type session_id amount amount_netto desc order_id desc2 trsDesc first_name last_name street street_hn street_an city post_code country email phone language client_ip js payback_login sig ts ).each do |field| value = transaction.send(field) html << hidden_field_tag(field, value) unless value.blank? end html.html_safe end
ruby
def payu_hidden_fields(transaction) html = "" %w(pos_id pos_auth_key pay_type session_id amount amount_netto desc order_id desc2 trsDesc first_name last_name street street_hn street_an city post_code country email phone language client_ip js payback_login sig ts ).each do |field| value = transaction.send(field) html << hidden_field_tag(field, value) unless value.blank? end html.html_safe end
[ "def", "payu_hidden_fields", "(", "transaction", ")", "html", "=", "\"\"", "%w(", "pos_id", "pos_auth_key", "pay_type", "session_id", "amount", "amount_netto", "desc", "order_id", "desc2", "trsDesc", "first_name", "last_name", "street", "street_hn", "street_an", "city", "post_code", "country", "email", "phone", "language", "client_ip", "js", "payback_login", "sig", "ts", ")", ".", "each", "do", "|", "field", "|", "value", "=", "transaction", ".", "send", "(", "field", ")", "html", "<<", "hidden_field_tag", "(", "field", ",", "value", ")", "unless", "value", ".", "blank?", "end", "html", ".", "html_safe", "end" ]
Generates form fields for specified transaction object
[ "Generates", "form", "fields", "for", "specified", "transaction", "object" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/helpers.rb#L6-L19
train
ronin/payu
lib/payu/helpers.rb
Payu.Helpers.payu_verify_params
def payu_verify_params(params) pos_id = params['pos_id'] pos = Payu[pos_id] Signature.verify!( params['sig'], params['pos_id'], params['session_id'], params['ts'], pos.key2 ) end
ruby
def payu_verify_params(params) pos_id = params['pos_id'] pos = Payu[pos_id] Signature.verify!( params['sig'], params['pos_id'], params['session_id'], params['ts'], pos.key2 ) end
[ "def", "payu_verify_params", "(", "params", ")", "pos_id", "=", "params", "[", "'pos_id'", "]", "pos", "=", "Payu", "[", "pos_id", "]", "Signature", ".", "verify!", "(", "params", "[", "'sig'", "]", ",", "params", "[", "'pos_id'", "]", ",", "params", "[", "'session_id'", "]", ",", "params", "[", "'ts'", "]", ",", "pos", ".", "key2", ")", "end" ]
Verifies signature of passed parameters from Payu request
[ "Verifies", "signature", "of", "passed", "parameters", "from", "Payu", "request" ]
62971c5b2ae61a68ef92e39244ea03fd9e575830
https://github.com/ronin/payu/blob/62971c5b2ae61a68ef92e39244ea03fd9e575830/lib/payu/helpers.rb#L22-L33
train
smartsheet-platform/smartsheet-ruby-sdk
lib/smartsheet/general_request.rb
Smartsheet.GeneralRequest.request
def request(method:, url_path:, body: nil, params: {}, header_overrides: {}) spec = body.nil? ? {} : {body_type: :json} endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, body: body, params: params ) client.make_request(endpoint_spec, request_spec) end
ruby
def request(method:, url_path:, body: nil, params: {}, header_overrides: {}) spec = body.nil? ? {} : {body_type: :json} endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, body: body, params: params ) client.make_request(endpoint_spec, request_spec) end
[ "def", "request", "(", "method", ":", ",", "url_path", ":", ",", "body", ":", "nil", ",", "params", ":", "{", "}", ",", "header_overrides", ":", "{", "}", ")", "spec", "=", "body", ".", "nil?", "?", "{", "}", ":", "{", "body_type", ":", ":json", "}", "endpoint_spec", "=", "Smartsheet", "::", "API", "::", "EndpointSpec", ".", "new", "(", "method", ",", "[", "url_path", "]", ",", "**", "spec", ")", "request_spec", "=", "Smartsheet", "::", "API", "::", "RequestSpec", ".", "new", "(", "header_overrides", ":", "header_overrides", ",", "body", ":", "body", ",", "params", ":", "params", ")", "client", ".", "make_request", "(", "endpoint_spec", ",", "request_spec", ")", "end" ]
Create a custom request using a provided method and URL path @example Make a GET request to 'https://api.smartsheet.com/2.0/sheets/list' client.request(method: :get, url_path: 'sheets/list')
[ "Create", "a", "custom", "request", "using", "a", "provided", "method", "and", "URL", "path" ]
fb8bcaed1e5c382299b1299376128b196c3b92ed
https://github.com/smartsheet-platform/smartsheet-ruby-sdk/blob/fb8bcaed1e5c382299b1299376128b196c3b92ed/lib/smartsheet/general_request.rb#L8-L17
train
smartsheet-platform/smartsheet-ruby-sdk
lib/smartsheet/general_request.rb
Smartsheet.GeneralRequest.request_with_file
def request_with_file( method:, url_path:, file:, file_length:, filename:, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::ObjectFileSpec.new(file, filename, file_length, content_type) ) client.make_request(endpoint_spec, request_spec) end
ruby
def request_with_file( method:, url_path:, file:, file_length:, filename:, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::ObjectFileSpec.new(file, filename, file_length, content_type) ) client.make_request(endpoint_spec, request_spec) end
[ "def", "request_with_file", "(", "method", ":", ",", "url_path", ":", ",", "file", ":", ",", "file_length", ":", ",", "filename", ":", ",", "content_type", ":", "''", ",", "params", ":", "{", "}", ",", "header_overrides", ":", "{", "}", ")", "endpoint_spec", "=", "Smartsheet", "::", "API", "::", "EndpointSpec", ".", "new", "(", "method", ",", "[", "url_path", "]", ",", "body_type", ":", ":file", ")", "request_spec", "=", "Smartsheet", "::", "API", "::", "RequestSpec", ".", "new", "(", "header_overrides", ":", "header_overrides", ",", "params", ":", "params", ",", "file_spec", ":", "Smartsheet", "::", "API", "::", "ObjectFileSpec", ".", "new", "(", "file", ",", "filename", ",", "file_length", ",", "content_type", ")", ")", "client", ".", "make_request", "(", "endpoint_spec", ",", "request_spec", ")", "end" ]
Create a custom request using a provided method, URL path, and file details @example Make a POST request to 'https://api.smartsheet.com/2.0/sheets/1/attachments' with a file client.request_with_file( method: :get, url_path: 'sheets/1/attachments', file: File.open('my-file.docx'), file_length: 1000, filename: 'my-uploaded-file.docx', content_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' )
[ "Create", "a", "custom", "request", "using", "a", "provided", "method", "URL", "path", "and", "file", "details" ]
fb8bcaed1e5c382299b1299376128b196c3b92ed
https://github.com/smartsheet-platform/smartsheet-ruby-sdk/blob/fb8bcaed1e5c382299b1299376128b196c3b92ed/lib/smartsheet/general_request.rb#L29-L46
train
smartsheet-platform/smartsheet-ruby-sdk
lib/smartsheet/general_request.rb
Smartsheet.GeneralRequest.request_with_file_from_path
def request_with_file_from_path( method:, url_path:, path:, filename: nil, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::PathFileSpec.new(path, filename, content_type) ) client.make_request(endpoint_spec, request_spec) end
ruby
def request_with_file_from_path( method:, url_path:, path:, filename: nil, content_type: '', params: {}, header_overrides: {} ) endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file) request_spec = Smartsheet::API::RequestSpec.new( header_overrides: header_overrides, params: params, file_spec: Smartsheet::API::PathFileSpec.new(path, filename, content_type) ) client.make_request(endpoint_spec, request_spec) end
[ "def", "request_with_file_from_path", "(", "method", ":", ",", "url_path", ":", ",", "path", ":", ",", "filename", ":", "nil", ",", "content_type", ":", "''", ",", "params", ":", "{", "}", ",", "header_overrides", ":", "{", "}", ")", "endpoint_spec", "=", "Smartsheet", "::", "API", "::", "EndpointSpec", ".", "new", "(", "method", ",", "[", "url_path", "]", ",", "body_type", ":", ":file", ")", "request_spec", "=", "Smartsheet", "::", "API", "::", "RequestSpec", ".", "new", "(", "header_overrides", ":", "header_overrides", ",", "params", ":", "params", ",", "file_spec", ":", "Smartsheet", "::", "API", "::", "PathFileSpec", ".", "new", "(", "path", ",", "filename", ",", "content_type", ")", ")", "client", ".", "make_request", "(", "endpoint_spec", ",", "request_spec", ")", "end" ]
Create a custom request using a provided method, URL path, and filepath details @example Make a POST request to 'https://api.smartsheet.com/2.0/sheets/1/attachments' with a file client.request_with_file_from_path( method: :get, url_path: 'sheets/1/attachments', path: './my-file.docx', filename: 'my-uploaded-file.docx', content_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' )
[ "Create", "a", "custom", "request", "using", "a", "provided", "method", "URL", "path", "and", "filepath", "details" ]
fb8bcaed1e5c382299b1299376128b196c3b92ed
https://github.com/smartsheet-platform/smartsheet-ruby-sdk/blob/fb8bcaed1e5c382299b1299376128b196c3b92ed/lib/smartsheet/general_request.rb#L57-L73
train
octopress/ink
lib/octopress-ink.rb
Octopress.Ink.list
def list(options={}) site = Octopress.site(options) Plugins.register options = {'minimal'=>true} if options.empty? message = "Octopress Ink - v#{VERSION}\n" if plugins.size > 0 plugins.each do |plugin| message += plugin.list(options) end else message += "You have no plugins installed." end puts message end
ruby
def list(options={}) site = Octopress.site(options) Plugins.register options = {'minimal'=>true} if options.empty? message = "Octopress Ink - v#{VERSION}\n" if plugins.size > 0 plugins.each do |plugin| message += plugin.list(options) end else message += "You have no plugins installed." end puts message end
[ "def", "list", "(", "options", "=", "{", "}", ")", "site", "=", "Octopress", ".", "site", "(", "options", ")", "Plugins", ".", "register", "options", "=", "{", "'minimal'", "=>", "true", "}", "if", "options", ".", "empty?", "message", "=", "\"Octopress Ink - v#{VERSION}\\n\"", "if", "plugins", ".", "size", ">", "0", "plugins", ".", "each", "do", "|", "plugin", "|", "message", "+=", "plugin", ".", "list", "(", "options", ")", "end", "else", "message", "+=", "\"You have no plugins installed.\"", "end", "puts", "message", "end" ]
Prints a list of plugins and details options - a Hash of options from the `list` command Note: if options are empty, this will display a list of plugin names, slugs, versions, and descriptions, but no assets, i.e. 'minimal' info.
[ "Prints", "a", "list", "of", "plugins", "and", "details" ]
7a3a796b63d361f6f60bf516dba099664e11fd80
https://github.com/octopress/ink/blob/7a3a796b63d361f6f60bf516dba099664e11fd80/lib/octopress-ink.rb#L132-L146
train
octopress/ink
lib/octopress-ink.rb
Octopress.Ink.copy_doc
def copy_doc(source, dest, permalink=nil) contents = File.open(source).read # Convert H1 to title and add permalink in YAML front-matter # contents.sub!(/^# (.*)$/, "#{doc_yaml('\1', permalink).strip}") FileUtils.mkdir_p File.dirname(dest) File.open(dest, 'w') {|f| f.write(contents) } puts "Updated #{dest} from #{source}" end
ruby
def copy_doc(source, dest, permalink=nil) contents = File.open(source).read # Convert H1 to title and add permalink in YAML front-matter # contents.sub!(/^# (.*)$/, "#{doc_yaml('\1', permalink).strip}") FileUtils.mkdir_p File.dirname(dest) File.open(dest, 'w') {|f| f.write(contents) } puts "Updated #{dest} from #{source}" end
[ "def", "copy_doc", "(", "source", ",", "dest", ",", "permalink", "=", "nil", ")", "contents", "=", "File", ".", "open", "(", "source", ")", ".", "read", "contents", ".", "sub!", "(", "/", "/", ",", "\"#{doc_yaml('\\1', permalink).strip}\"", ")", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "dest", ")", "File", ".", "open", "(", "dest", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "contents", ")", "}", "puts", "\"Updated #{dest} from #{source}\"", "end" ]
Makes it easy for Ink plugins to copy README and CHANGELOG files to doc folder to be used as a documentation asset file Usage: In rakefile require 'octopress-ink' then add task calling Octopress::Ink.copy_doc for each file
[ "Makes", "it", "easy", "for", "Ink", "plugins", "to", "copy", "README", "and", "CHANGELOG", "files", "to", "doc", "folder", "to", "be", "used", "as", "a", "documentation", "asset", "file" ]
7a3a796b63d361f6f60bf516dba099664e11fd80
https://github.com/octopress/ink/blob/7a3a796b63d361f6f60bf516dba099664e11fd80/lib/octopress-ink.rb#L216-L226
train
pusher-community/pusher-websocket-ruby
spec/spec_helper.rb
PusherClient.Socket.connect
def connect(async = false) @connection_thread = Thread.new do @connection = TestConnection.new @global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'})) end @connection_thread.run @connection_thread.join unless async return self end
ruby
def connect(async = false) @connection_thread = Thread.new do @connection = TestConnection.new @global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'})) end @connection_thread.run @connection_thread.join unless async return self end
[ "def", "connect", "(", "async", "=", "false", ")", "@connection_thread", "=", "Thread", ".", "new", "do", "@connection", "=", "TestConnection", ".", "new", "@global_channel", ".", "dispatch", "(", "'pusher:connection_established'", ",", "JSON", ".", "dump", "(", "{", "'socket_id'", "=>", "'123abc'", "}", ")", ")", "end", "@connection_thread", ".", "run", "@connection_thread", ".", "join", "unless", "async", "return", "self", "end" ]
Simulate a connection being established
[ "Simulate", "a", "connection", "being", "established" ]
205e57f97e7c0dd27a5cbff3b91040b0967c3b9c
https://github.com/pusher-community/pusher-websocket-ruby/blob/205e57f97e7c0dd27a5cbff3b91040b0967c3b9c/spec/spec_helper.rb#L25-L33
train
pusher-community/pusher-websocket-ruby
lib/pusher-client/socket.rb
PusherClient.Socket.authorize
def authorize(channel, callback) if is_private_channel(channel.name) auth_data = get_private_auth(channel) elsif is_presence_channel(channel.name) auth_data = get_presence_auth(channel) end # could both be nil if didn't require auth callback.call(channel, auth_data, channel.user_data) end
ruby
def authorize(channel, callback) if is_private_channel(channel.name) auth_data = get_private_auth(channel) elsif is_presence_channel(channel.name) auth_data = get_presence_auth(channel) end # could both be nil if didn't require auth callback.call(channel, auth_data, channel.user_data) end
[ "def", "authorize", "(", "channel", ",", "callback", ")", "if", "is_private_channel", "(", "channel", ".", "name", ")", "auth_data", "=", "get_private_auth", "(", "channel", ")", "elsif", "is_presence_channel", "(", "channel", ".", "name", ")", "auth_data", "=", "get_presence_auth", "(", "channel", ")", "end", "callback", ".", "call", "(", "channel", ",", "auth_data", ",", "channel", ".", "user_data", ")", "end" ]
auth for private and presence
[ "auth", "for", "private", "and", "presence" ]
205e57f97e7c0dd27a5cbff3b91040b0967c3b9c
https://github.com/pusher-community/pusher-websocket-ruby/blob/205e57f97e7c0dd27a5cbff3b91040b0967c3b9c/lib/pusher-client/socket.rb#L133-L141
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.console
def console client_setup({}, true, true) puts "Console Connected to #{@client.url}" puts "HINT: The @client object is available to you\n\n" rescue puts "WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\n\n" ensure require 'pry' Pry.config.prompt = proc { '> ' } Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable! Pry.plugins['byebug'] && Pry.plugins['byebug'].disable! Pry.start(OneviewSDK::Console.new(@client)) end
ruby
def console client_setup({}, true, true) puts "Console Connected to #{@client.url}" puts "HINT: The @client object is available to you\n\n" rescue puts "WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\n\n" ensure require 'pry' Pry.config.prompt = proc { '> ' } Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable! Pry.plugins['byebug'] && Pry.plugins['byebug'].disable! Pry.start(OneviewSDK::Console.new(@client)) end
[ "def", "console", "client_setup", "(", "{", "}", ",", "true", ",", "true", ")", "puts", "\"Console Connected to #{@client.url}\"", "puts", "\"HINT: The @client object is available to you\\n\\n\"", "rescue", "puts", "\"WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\\n\\n\"", "ensure", "require", "'pry'", "Pry", ".", "config", ".", "prompt", "=", "proc", "{", "'> '", "}", "Pry", ".", "plugins", "[", "'stack_explorer'", "]", "&&", "Pry", ".", "plugins", "[", "'stack_explorer'", "]", ".", "disable!", "Pry", ".", "plugins", "[", "'byebug'", "]", "&&", "Pry", ".", "plugins", "[", "'byebug'", "]", ".", "disable!", "Pry", ".", "start", "(", "OneviewSDK", "::", "Console", ".", "new", "(", "@client", ")", ")", "end" ]
Open a Ruby console with a connection to OneView
[ "Open", "a", "Ruby", "console", "with", "a", "connection", "to", "OneView" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L84-L96
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.env
def env data = {} OneviewSDK::ENV_VARS.each { |k| data[k] = ENV[k] } if @options['format'] == 'human' data.each do |key, value| value = "'#{value}'" if value && !%w[true false].include?(value) printf "%-#{data.keys.max_by(&:length).length}s = %s\n", key, value || 'nil' end else output(parse_hash(data, true)) end end
ruby
def env data = {} OneviewSDK::ENV_VARS.each { |k| data[k] = ENV[k] } if @options['format'] == 'human' data.each do |key, value| value = "'#{value}'" if value && !%w[true false].include?(value) printf "%-#{data.keys.max_by(&:length).length}s = %s\n", key, value || 'nil' end else output(parse_hash(data, true)) end end
[ "def", "env", "data", "=", "{", "}", "OneviewSDK", "::", "ENV_VARS", ".", "each", "{", "|", "k", "|", "data", "[", "k", "]", "=", "ENV", "[", "k", "]", "}", "if", "@options", "[", "'format'", "]", "==", "'human'", "data", ".", "each", "do", "|", "key", ",", "value", "|", "value", "=", "\"'#{value}'\"", "if", "value", "&&", "!", "%w[", "true", "false", "]", ".", "include?", "(", "value", ")", "printf", "\"%-#{data.keys.max_by(&:length).length}s = %s\\n\"", ",", "key", ",", "value", "||", "'nil'", "end", "else", "output", "(", "parse_hash", "(", "data", ",", "true", ")", ")", "end", "end" ]
Show environment variables for oneview-sdk-ruby
[ "Show", "environment", "variables", "for", "oneview", "-", "sdk", "-", "ruby" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L115-L126
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.show
def show(type, name) resource_class = parse_type(type) client_setup matches = resource_class.find_by(@client, name: name) fail_nice 'Not Found' if matches.empty? data = matches.first.data if options['attribute'] data = select_attributes(options['attribute'], data) end output data end
ruby
def show(type, name) resource_class = parse_type(type) client_setup matches = resource_class.find_by(@client, name: name) fail_nice 'Not Found' if matches.empty? data = matches.first.data if options['attribute'] data = select_attributes(options['attribute'], data) end output data end
[ "def", "show", "(", "type", ",", "name", ")", "resource_class", "=", "parse_type", "(", "type", ")", "client_setup", "matches", "=", "resource_class", ".", "find_by", "(", "@client", ",", "name", ":", "name", ")", "fail_nice", "'Not Found'", "if", "matches", ".", "empty?", "data", "=", "matches", ".", "first", ".", "data", "if", "options", "[", "'attribute'", "]", "data", "=", "select_attributes", "(", "options", "[", "'attribute'", "]", ",", "data", ")", "end", "output", "data", "end" ]
Show resource details
[ "Show", "resource", "details" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L176-L186
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.rest
def rest(method, uri) log_level = @options['log_level'] == :warn ? :error : @options['log_level'].to_sym # Default to :error client_setup('log_level' => log_level) uri_copy = uri.dup uri_copy.prepend('/') unless uri_copy.start_with?('/') if @options['data'] begin data = { body: JSON.parse(@options['data']) } rescue JSON::ParserError => e fail_nice("Failed to parse data as JSON\n#{e.message}") end end data ||= {} response = @client.rest_api(method, uri_copy, data) if response.code.to_i.between?(200, 299) case @options['format'] when 'yaml' puts JSON.parse(response.body).to_yaml when 'json' puts JSON.pretty_generate(JSON.parse(response.body)) else # raw puts response.body end else body = JSON.pretty_generate(JSON.parse(response.body)) rescue response.body fail_nice("Request failed: #{response.inspect}\nHeaders: #{response.to_hash}\nBody: #{body}") end rescue OneviewSDK::InvalidRequest => e fail_nice(e.message) end
ruby
def rest(method, uri) log_level = @options['log_level'] == :warn ? :error : @options['log_level'].to_sym # Default to :error client_setup('log_level' => log_level) uri_copy = uri.dup uri_copy.prepend('/') unless uri_copy.start_with?('/') if @options['data'] begin data = { body: JSON.parse(@options['data']) } rescue JSON::ParserError => e fail_nice("Failed to parse data as JSON\n#{e.message}") end end data ||= {} response = @client.rest_api(method, uri_copy, data) if response.code.to_i.between?(200, 299) case @options['format'] when 'yaml' puts JSON.parse(response.body).to_yaml when 'json' puts JSON.pretty_generate(JSON.parse(response.body)) else # raw puts response.body end else body = JSON.pretty_generate(JSON.parse(response.body)) rescue response.body fail_nice("Request failed: #{response.inspect}\nHeaders: #{response.to_hash}\nBody: #{body}") end rescue OneviewSDK::InvalidRequest => e fail_nice(e.message) end
[ "def", "rest", "(", "method", ",", "uri", ")", "log_level", "=", "@options", "[", "'log_level'", "]", "==", ":warn", "?", ":error", ":", "@options", "[", "'log_level'", "]", ".", "to_sym", "client_setup", "(", "'log_level'", "=>", "log_level", ")", "uri_copy", "=", "uri", ".", "dup", "uri_copy", ".", "prepend", "(", "'/'", ")", "unless", "uri_copy", ".", "start_with?", "(", "'/'", ")", "if", "@options", "[", "'data'", "]", "begin", "data", "=", "{", "body", ":", "JSON", ".", "parse", "(", "@options", "[", "'data'", "]", ")", "}", "rescue", "JSON", "::", "ParserError", "=>", "e", "fail_nice", "(", "\"Failed to parse data as JSON\\n#{e.message}\"", ")", "end", "end", "data", "||=", "{", "}", "response", "=", "@client", ".", "rest_api", "(", "method", ",", "uri_copy", ",", "data", ")", "if", "response", ".", "code", ".", "to_i", ".", "between?", "(", "200", ",", "299", ")", "case", "@options", "[", "'format'", "]", "when", "'yaml'", "puts", "JSON", ".", "parse", "(", "response", ".", "body", ")", ".", "to_yaml", "when", "'json'", "puts", "JSON", ".", "pretty_generate", "(", "JSON", ".", "parse", "(", "response", ".", "body", ")", ")", "else", "puts", "response", ".", "body", "end", "else", "body", "=", "JSON", ".", "pretty_generate", "(", "JSON", ".", "parse", "(", "response", ".", "body", ")", ")", "rescue", "response", ".", "body", "fail_nice", "(", "\"Request failed: #{response.inspect}\\nHeaders: #{response.to_hash}\\nBody: #{body}\"", ")", "end", "rescue", "OneviewSDK", "::", "InvalidRequest", "=>", "e", "fail_nice", "(", "e", ".", "message", ")", "end" ]
Make REST call to the OneView API
[ "Make", "REST", "call", "to", "the", "OneView", "API" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L238-L267
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.update
def update(type, name) resource_class = parse_type(type) client_setup fail_nice 'Must set the hash or json option' unless @options['hash'] || @options['json'] fail_nice 'Must set the hash OR json option. Not both' if @options['hash'] && @options['json'] begin data = @options['hash'] || JSON.parse(@options['json']) rescue JSON::ParserError => e fail_nice("Failed to parse json\n#{e.message}") end matches = resource_class.find_by(@client, name: name) fail_nice 'Not Found' if matches.empty? resource = matches.first begin resource.update(data) puts 'Updated Successfully!' rescue StandardError => e fail_nice "Failed to update #{resource.class.name.split('::').last} '#{name}': #{e}" end end
ruby
def update(type, name) resource_class = parse_type(type) client_setup fail_nice 'Must set the hash or json option' unless @options['hash'] || @options['json'] fail_nice 'Must set the hash OR json option. Not both' if @options['hash'] && @options['json'] begin data = @options['hash'] || JSON.parse(@options['json']) rescue JSON::ParserError => e fail_nice("Failed to parse json\n#{e.message}") end matches = resource_class.find_by(@client, name: name) fail_nice 'Not Found' if matches.empty? resource = matches.first begin resource.update(data) puts 'Updated Successfully!' rescue StandardError => e fail_nice "Failed to update #{resource.class.name.split('::').last} '#{name}': #{e}" end end
[ "def", "update", "(", "type", ",", "name", ")", "resource_class", "=", "parse_type", "(", "type", ")", "client_setup", "fail_nice", "'Must set the hash or json option'", "unless", "@options", "[", "'hash'", "]", "||", "@options", "[", "'json'", "]", "fail_nice", "'Must set the hash OR json option. Not both'", "if", "@options", "[", "'hash'", "]", "&&", "@options", "[", "'json'", "]", "begin", "data", "=", "@options", "[", "'hash'", "]", "||", "JSON", ".", "parse", "(", "@options", "[", "'json'", "]", ")", "rescue", "JSON", "::", "ParserError", "=>", "e", "fail_nice", "(", "\"Failed to parse json\\n#{e.message}\"", ")", "end", "matches", "=", "resource_class", ".", "find_by", "(", "@client", ",", "name", ":", "name", ")", "fail_nice", "'Not Found'", "if", "matches", ".", "empty?", "resource", "=", "matches", ".", "first", "begin", "resource", ".", "update", "(", "data", ")", "puts", "'Updated Successfully!'", "rescue", "StandardError", "=>", "e", "fail_nice", "\"Failed to update #{resource.class.name.split('::').last} '#{name}': #{e}\"", "end", "end" ]
Update resource by name
[ "Update", "resource", "by", "name" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L280-L299
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.delete
def delete(type, name) resource_class = parse_type(type) client_setup matches = resource_class.find_by(@client, name: name) fail_nice('Not Found', 2) if matches.empty? resource = matches.first return unless options['force'] || agree("Delete '#{name}'? [Y/N] ") begin resource.delete puts 'Deleted Successfully!' rescue StandardError => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{name}': #{e}" end end
ruby
def delete(type, name) resource_class = parse_type(type) client_setup matches = resource_class.find_by(@client, name: name) fail_nice('Not Found', 2) if matches.empty? resource = matches.first return unless options['force'] || agree("Delete '#{name}'? [Y/N] ") begin resource.delete puts 'Deleted Successfully!' rescue StandardError => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{name}': #{e}" end end
[ "def", "delete", "(", "type", ",", "name", ")", "resource_class", "=", "parse_type", "(", "type", ")", "client_setup", "matches", "=", "resource_class", ".", "find_by", "(", "@client", ",", "name", ":", "name", ")", "fail_nice", "(", "'Not Found'", ",", "2", ")", "if", "matches", ".", "empty?", "resource", "=", "matches", ".", "first", "return", "unless", "options", "[", "'force'", "]", "||", "agree", "(", "\"Delete '#{name}'? [Y/N] \"", ")", "begin", "resource", ".", "delete", "puts", "'Deleted Successfully!'", "rescue", "StandardError", "=>", "e", "fail_nice", "\"Failed to delete #{resource.class.name.split('::').last} '#{name}': #{e}\"", "end", "end" ]
Delete resource by name
[ "Delete", "resource", "by", "name" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L307-L320
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.delete_from_file
def delete_from_file(file_path) client_setup resource = OneviewSDK::Resource.from_file(@client, file_path) fail_nice("#{resource.class.name.split('::').last} '#{resource[:name] || resource[:uri]}' Not Found", 2) unless resource.retrieve! return unless options['force'] || agree("Delete '#{resource[:name]}'? [Y/N] ") begin resource.delete puts 'Deleted Successfully!' rescue StandardError => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}" end rescue IncompleteResource => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}" rescue SystemCallError => e # File open errors fail_nice e end
ruby
def delete_from_file(file_path) client_setup resource = OneviewSDK::Resource.from_file(@client, file_path) fail_nice("#{resource.class.name.split('::').last} '#{resource[:name] || resource[:uri]}' Not Found", 2) unless resource.retrieve! return unless options['force'] || agree("Delete '#{resource[:name]}'? [Y/N] ") begin resource.delete puts 'Deleted Successfully!' rescue StandardError => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}" end rescue IncompleteResource => e fail_nice "Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}" rescue SystemCallError => e # File open errors fail_nice e end
[ "def", "delete_from_file", "(", "file_path", ")", "client_setup", "resource", "=", "OneviewSDK", "::", "Resource", ".", "from_file", "(", "@client", ",", "file_path", ")", "fail_nice", "(", "\"#{resource.class.name.split('::').last} '#{resource[:name] || resource[:uri]}' Not Found\"", ",", "2", ")", "unless", "resource", ".", "retrieve!", "return", "unless", "options", "[", "'force'", "]", "||", "agree", "(", "\"Delete '#{resource[:name]}'? [Y/N] \"", ")", "begin", "resource", ".", "delete", "puts", "'Deleted Successfully!'", "rescue", "StandardError", "=>", "e", "fail_nice", "\"Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}\"", "end", "rescue", "IncompleteResource", "=>", "e", "fail_nice", "\"Failed to delete #{resource.class.name.split('::').last} '#{resource[:name]}': #{e}\"", "rescue", "SystemCallError", "=>", "e", "fail_nice", "e", "end" ]
Delete resource defined in file
[ "Delete", "resource", "defined", "in", "file" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L328-L343
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.to_file
def to_file(type, name) file = File.expand_path(options['path']) resource_class = parse_type(type) client_setup resource = resource_class.find_by(@client, name: name).first fail_nice "#{resource_class.name.split('::').last} '#{name}' not found" unless resource resource.to_file(file, options['format']) puts "Output to #{file}" rescue SystemCallError => e fail_nice "Failed to create file! (You may need to create the necessary directories). Message: #{e}" end
ruby
def to_file(type, name) file = File.expand_path(options['path']) resource_class = parse_type(type) client_setup resource = resource_class.find_by(@client, name: name).first fail_nice "#{resource_class.name.split('::').last} '#{name}' not found" unless resource resource.to_file(file, options['format']) puts "Output to #{file}" rescue SystemCallError => e fail_nice "Failed to create file! (You may need to create the necessary directories). Message: #{e}" end
[ "def", "to_file", "(", "type", ",", "name", ")", "file", "=", "File", ".", "expand_path", "(", "options", "[", "'path'", "]", ")", "resource_class", "=", "parse_type", "(", "type", ")", "client_setup", "resource", "=", "resource_class", ".", "find_by", "(", "@client", ",", "name", ":", "name", ")", ".", "first", "fail_nice", "\"#{resource_class.name.split('::').last} '#{name}' not found\"", "unless", "resource", "resource", ".", "to_file", "(", "file", ",", "options", "[", "'format'", "]", ")", "puts", "\"Output to #{file}\"", "rescue", "SystemCallError", "=>", "e", "fail_nice", "\"Failed to create file! (You may need to create the necessary directories). Message: #{e}\"", "end" ]
Save resource details to file
[ "Save", "resource", "details", "to", "file" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L398-L408
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.cert
def cert(type, url = ENV['ONEVIEWSDK_URL']) case type.downcase when 'check' fail_nice 'Must specify a url' unless url puts "Checking certificate for '#{url}' ..." if OneviewSDK::SSLHelper.check_cert(url) puts 'Certificate is valid!' else fail_nice 'Certificate Validation Failed!' end when 'import' fail_nice 'Must specify a url' unless url puts "Importing certificate for '#{url}' into '#{OneviewSDK::SSLHelper::CERT_STORE}'..." OneviewSDK::SSLHelper.install_cert(url) when 'list' if File.file?(OneviewSDK::SSLHelper::CERT_STORE) puts File.read(OneviewSDK::SSLHelper::CERT_STORE) else puts 'No certs imported!' end else fail_nice "Invalid action '#{type}'. Valid actions are [check, import, list]" end rescue StandardError => e fail_nice e.message end
ruby
def cert(type, url = ENV['ONEVIEWSDK_URL']) case type.downcase when 'check' fail_nice 'Must specify a url' unless url puts "Checking certificate for '#{url}' ..." if OneviewSDK::SSLHelper.check_cert(url) puts 'Certificate is valid!' else fail_nice 'Certificate Validation Failed!' end when 'import' fail_nice 'Must specify a url' unless url puts "Importing certificate for '#{url}' into '#{OneviewSDK::SSLHelper::CERT_STORE}'..." OneviewSDK::SSLHelper.install_cert(url) when 'list' if File.file?(OneviewSDK::SSLHelper::CERT_STORE) puts File.read(OneviewSDK::SSLHelper::CERT_STORE) else puts 'No certs imported!' end else fail_nice "Invalid action '#{type}'. Valid actions are [check, import, list]" end rescue StandardError => e fail_nice e.message end
[ "def", "cert", "(", "type", ",", "url", "=", "ENV", "[", "'ONEVIEWSDK_URL'", "]", ")", "case", "type", ".", "downcase", "when", "'check'", "fail_nice", "'Must specify a url'", "unless", "url", "puts", "\"Checking certificate for '#{url}' ...\"", "if", "OneviewSDK", "::", "SSLHelper", ".", "check_cert", "(", "url", ")", "puts", "'Certificate is valid!'", "else", "fail_nice", "'Certificate Validation Failed!'", "end", "when", "'import'", "fail_nice", "'Must specify a url'", "unless", "url", "puts", "\"Importing certificate for '#{url}' into '#{OneviewSDK::SSLHelper::CERT_STORE}'...\"", "OneviewSDK", "::", "SSLHelper", ".", "install_cert", "(", "url", ")", "when", "'list'", "if", "File", ".", "file?", "(", "OneviewSDK", "::", "SSLHelper", "::", "CERT_STORE", ")", "puts", "File", ".", "read", "(", "OneviewSDK", "::", "SSLHelper", "::", "CERT_STORE", ")", "else", "puts", "'No certs imported!'", "end", "else", "fail_nice", "\"Invalid action '#{type}'. Valid actions are [check, import, list]\"", "end", "rescue", "StandardError", "=>", "e", "fail_nice", "e", ".", "message", "end" ]
Check, import, or list OneView certs
[ "Check", "import", "or", "list", "OneView", "certs" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L412-L436
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.scmb
def scmb client_setup connection = OneviewSDK::SCMB.new_connection(@client) q = OneviewSDK::SCMB.new_queue(connection, @options['route']) puts 'Subscribing to OneView messages. To exit, press Ctrl + c' q.subscribe(block: true) do |_delivery_info, _properties, payload| data = JSON.parse(payload) rescue payload puts "\n#{'=' * 50}\n\nReceived message with payload:" @options['format'] == 'raw' ? puts(payload) : output(data) end end
ruby
def scmb client_setup connection = OneviewSDK::SCMB.new_connection(@client) q = OneviewSDK::SCMB.new_queue(connection, @options['route']) puts 'Subscribing to OneView messages. To exit, press Ctrl + c' q.subscribe(block: true) do |_delivery_info, _properties, payload| data = JSON.parse(payload) rescue payload puts "\n#{'=' * 50}\n\nReceived message with payload:" @options['format'] == 'raw' ? puts(payload) : output(data) end end
[ "def", "scmb", "client_setup", "connection", "=", "OneviewSDK", "::", "SCMB", ".", "new_connection", "(", "@client", ")", "q", "=", "OneviewSDK", "::", "SCMB", ".", "new_queue", "(", "connection", ",", "@options", "[", "'route'", "]", ")", "puts", "'Subscribing to OneView messages. To exit, press Ctrl + c'", "q", ".", "subscribe", "(", "block", ":", "true", ")", "do", "|", "_delivery_info", ",", "_properties", ",", "payload", "|", "data", "=", "JSON", ".", "parse", "(", "payload", ")", "rescue", "payload", "puts", "\"\\n#{'=' * 50}\\n\\nReceived message with payload:\"", "@options", "[", "'format'", "]", "==", "'raw'", "?", "puts", "(", "payload", ")", ":", "output", "(", "data", ")", "end", "end" ]
Subscribe to the OneView SCMB
[ "Subscribe", "to", "the", "OneView", "SCMB" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L453-L463
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.parse_type
def parse_type(type) api_ver = (@options['api_version'] || ENV['ONEVIEWSDK_API_VERSION'] || OneviewSDK.api_version).to_i unless OneviewSDK::SUPPORTED_API_VERSIONS.include?(api_ver) # Find and use the best available match for the desired API version (round down to nearest) valid_api_ver = OneviewSDK::SUPPORTED_API_VERSIONS.select { |x| x <= api_ver }.max || OneviewSDK::SUPPORTED_API_VERSIONS.min puts "WARNING: Module API version #{api_ver} is not supported. Using #{valid_api_ver}" api_ver = valid_api_ver end variant = @options['variant'] || ENV['ONEVIEWSDK_VARIANT'] variant ||= OneviewSDK::API300.variant if api_ver == 300 if variant && !SUPPORTED_VARIANTS.include?(variant) fail_nice "Variant '#{variant}' is not supported. Try one of #{SUPPORTED_VARIANTS}" end r = OneviewSDK.resource_named(type, api_ver, variant) # Try default API version as last resort r ||= OneviewSDK.resource_named(type, OneviewSDK.api_version, variant) unless api_ver == OneviewSDK.api_version return r if r && r.respond_to?(:find_by) valid_classes = [] api_module = OneviewSDK.const_get("API#{api_ver}") api_module = api_module.const_get(variant.to_s) unless api_ver.to_i == 200 api_module.constants.each do |c| klass = api_module.const_get(c) next unless klass.is_a?(Class) && klass.respond_to?(:find_by) valid_classes.push(klass.name.split('::').last) end vc = valid_classes.sort_by!(&:downcase).join("\n ") var = variant ? " (variant #{variant})" : '' fail_nice("Invalid resource type: '#{type}'. Valid options for API version #{api_ver}#{var} are:\n #{vc}") end
ruby
def parse_type(type) api_ver = (@options['api_version'] || ENV['ONEVIEWSDK_API_VERSION'] || OneviewSDK.api_version).to_i unless OneviewSDK::SUPPORTED_API_VERSIONS.include?(api_ver) # Find and use the best available match for the desired API version (round down to nearest) valid_api_ver = OneviewSDK::SUPPORTED_API_VERSIONS.select { |x| x <= api_ver }.max || OneviewSDK::SUPPORTED_API_VERSIONS.min puts "WARNING: Module API version #{api_ver} is not supported. Using #{valid_api_ver}" api_ver = valid_api_ver end variant = @options['variant'] || ENV['ONEVIEWSDK_VARIANT'] variant ||= OneviewSDK::API300.variant if api_ver == 300 if variant && !SUPPORTED_VARIANTS.include?(variant) fail_nice "Variant '#{variant}' is not supported. Try one of #{SUPPORTED_VARIANTS}" end r = OneviewSDK.resource_named(type, api_ver, variant) # Try default API version as last resort r ||= OneviewSDK.resource_named(type, OneviewSDK.api_version, variant) unless api_ver == OneviewSDK.api_version return r if r && r.respond_to?(:find_by) valid_classes = [] api_module = OneviewSDK.const_get("API#{api_ver}") api_module = api_module.const_get(variant.to_s) unless api_ver.to_i == 200 api_module.constants.each do |c| klass = api_module.const_get(c) next unless klass.is_a?(Class) && klass.respond_to?(:find_by) valid_classes.push(klass.name.split('::').last) end vc = valid_classes.sort_by!(&:downcase).join("\n ") var = variant ? " (variant #{variant})" : '' fail_nice("Invalid resource type: '#{type}'. Valid options for API version #{api_ver}#{var} are:\n #{vc}") end
[ "def", "parse_type", "(", "type", ")", "api_ver", "=", "(", "@options", "[", "'api_version'", "]", "||", "ENV", "[", "'ONEVIEWSDK_API_VERSION'", "]", "||", "OneviewSDK", ".", "api_version", ")", ".", "to_i", "unless", "OneviewSDK", "::", "SUPPORTED_API_VERSIONS", ".", "include?", "(", "api_ver", ")", "valid_api_ver", "=", "OneviewSDK", "::", "SUPPORTED_API_VERSIONS", ".", "select", "{", "|", "x", "|", "x", "<=", "api_ver", "}", ".", "max", "||", "OneviewSDK", "::", "SUPPORTED_API_VERSIONS", ".", "min", "puts", "\"WARNING: Module API version #{api_ver} is not supported. Using #{valid_api_ver}\"", "api_ver", "=", "valid_api_ver", "end", "variant", "=", "@options", "[", "'variant'", "]", "||", "ENV", "[", "'ONEVIEWSDK_VARIANT'", "]", "variant", "||=", "OneviewSDK", "::", "API300", ".", "variant", "if", "api_ver", "==", "300", "if", "variant", "&&", "!", "SUPPORTED_VARIANTS", ".", "include?", "(", "variant", ")", "fail_nice", "\"Variant '#{variant}' is not supported. Try one of #{SUPPORTED_VARIANTS}\"", "end", "r", "=", "OneviewSDK", ".", "resource_named", "(", "type", ",", "api_ver", ",", "variant", ")", "r", "||=", "OneviewSDK", ".", "resource_named", "(", "type", ",", "OneviewSDK", ".", "api_version", ",", "variant", ")", "unless", "api_ver", "==", "OneviewSDK", ".", "api_version", "return", "r", "if", "r", "&&", "r", ".", "respond_to?", "(", ":find_by", ")", "valid_classes", "=", "[", "]", "api_module", "=", "OneviewSDK", ".", "const_get", "(", "\"API#{api_ver}\"", ")", "api_module", "=", "api_module", ".", "const_get", "(", "variant", ".", "to_s", ")", "unless", "api_ver", ".", "to_i", "==", "200", "api_module", ".", "constants", ".", "each", "do", "|", "c", "|", "klass", "=", "api_module", ".", "const_get", "(", "c", ")", "next", "unless", "klass", ".", "is_a?", "(", "Class", ")", "&&", "klass", ".", "respond_to?", "(", ":find_by", ")", "valid_classes", ".", "push", "(", "klass", ".", "name", ".", "split", "(", "'::'", ")", ".", "last", ")", "end", "vc", "=", "valid_classes", ".", "sort_by!", "(", "&", ":downcase", ")", ".", "join", "(", "\"\\n \"", ")", "var", "=", "variant", "?", "\" (variant #{variant})\"", ":", "''", "fail_nice", "(", "\"Invalid resource type: '#{type}'. Valid options for API version #{api_ver}#{var} are:\\n #{vc}\"", ")", "end" ]
Get resource class from given string
[ "Get", "resource", "class", "from", "given", "string" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L487-L515
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.select_attributes
def select_attributes(attributes, data = {}) attributes = attributes.split(',').map(&:strip).reject(&:empty?).map { |a| a.split('.') } if attributes.is_a?(String) r_data = data.is_a?(Hash) ? data : data.data temp = {} attributes.each do |attr| temp_level = temp attr = [attr] if attr.is_a?(String) attr.each_with_index do |a, index| # Safely retrieving and setting nested keys is not as easy, so loop to build a nested Hash structure for the result if index == attr.size - 1 # Use r_data.dig(*attr) if we ever drop support for Ruby < 2.3 temp_level[a] = [*attr].reduce(r_data) { |m, k| m && m[k] } rescue nil else temp_level[a] ||= {} temp_level = temp_level[a] end end end temp end
ruby
def select_attributes(attributes, data = {}) attributes = attributes.split(',').map(&:strip).reject(&:empty?).map { |a| a.split('.') } if attributes.is_a?(String) r_data = data.is_a?(Hash) ? data : data.data temp = {} attributes.each do |attr| temp_level = temp attr = [attr] if attr.is_a?(String) attr.each_with_index do |a, index| # Safely retrieving and setting nested keys is not as easy, so loop to build a nested Hash structure for the result if index == attr.size - 1 # Use r_data.dig(*attr) if we ever drop support for Ruby < 2.3 temp_level[a] = [*attr].reduce(r_data) { |m, k| m && m[k] } rescue nil else temp_level[a] ||= {} temp_level = temp_level[a] end end end temp end
[ "def", "select_attributes", "(", "attributes", ",", "data", "=", "{", "}", ")", "attributes", "=", "attributes", ".", "split", "(", "','", ")", ".", "map", "(", "&", ":strip", ")", ".", "reject", "(", "&", ":empty?", ")", ".", "map", "{", "|", "a", "|", "a", ".", "split", "(", "'.'", ")", "}", "if", "attributes", ".", "is_a?", "(", "String", ")", "r_data", "=", "data", ".", "is_a?", "(", "Hash", ")", "?", "data", ":", "data", ".", "data", "temp", "=", "{", "}", "attributes", ".", "each", "do", "|", "attr", "|", "temp_level", "=", "temp", "attr", "=", "[", "attr", "]", "if", "attr", ".", "is_a?", "(", "String", ")", "attr", ".", "each_with_index", "do", "|", "a", ",", "index", "|", "if", "index", "==", "attr", ".", "size", "-", "1", "temp_level", "[", "a", "]", "=", "[", "*", "attr", "]", ".", "reduce", "(", "r_data", ")", "{", "|", "m", ",", "k", "|", "m", "&&", "m", "[", "k", "]", "}", "rescue", "nil", "else", "temp_level", "[", "a", "]", "||=", "{", "}", "temp_level", "=", "temp_level", "[", "a", "]", "end", "end", "end", "temp", "end" ]
Select a subset of attributes from a given resource @param attributes [String, Array<Array<String>>] Comma-separated string or array of array of strings The reason it's a nested array is to allow retrieval of nested keys. For example, the following 2 attribute params will return the same result: - [['key1'], ['key2', 'subKey3']] - 'key1,key2.subKey3' @param data [Hash, OneviewSDK::Resource] @return [Hash] A Hash is returned. For example: { 'key1' => 'val1', 'key2' => { 'subKey3' => 'val2' } }
[ "Select", "a", "subset", "of", "attributes", "from", "a", "given", "resource" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L556-L575
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/cli.rb
OneviewSDK.Cli.select_attributes_from_multiple
def select_attributes_from_multiple(attributes, data = []) attributes = attributes.split(',').map(&:strip).reject(&:empty?).map { |a| a.split('.') } if attributes.is_a?(String) result = [] data.each do |r| result.push(r['name'] => select_attributes(attributes, r)) end result end
ruby
def select_attributes_from_multiple(attributes, data = []) attributes = attributes.split(',').map(&:strip).reject(&:empty?).map { |a| a.split('.') } if attributes.is_a?(String) result = [] data.each do |r| result.push(r['name'] => select_attributes(attributes, r)) end result end
[ "def", "select_attributes_from_multiple", "(", "attributes", ",", "data", "=", "[", "]", ")", "attributes", "=", "attributes", ".", "split", "(", "','", ")", ".", "map", "(", "&", ":strip", ")", ".", "reject", "(", "&", ":empty?", ")", ".", "map", "{", "|", "a", "|", "a", ".", "split", "(", "'.'", ")", "}", "if", "attributes", ".", "is_a?", "(", "String", ")", "result", "=", "[", "]", "data", ".", "each", "do", "|", "r", "|", "result", ".", "push", "(", "r", "[", "'name'", "]", "=>", "select_attributes", "(", "attributes", ",", "r", ")", ")", "end", "result", "end" ]
Select a subset of attributes from a given set of resources @param attributes [String, Array<Array<String>>] Comma-separated string or array of array of strings The reason it's a nested array is to allow retrieval of nested keys. For example, the following 2 attribute params will return the same result: - [['key1'], ['key2', 'subKey3']] - 'key1,key2.subKey3' @param data [Array<Hash>, Array<OneviewSDK::Resource>] @return [Array<Hash>] An Array of Hashes is returned. For example: [ { 'resource_name1' => { 'key1' => 'val1', 'key2' => { 'subKey3' => 'val2' } } }, { 'resource_name2' => { 'key1' => 'val3', 'key2' => { 'subKey3' => 'val4' } } }, ]
[ "Select", "a", "subset", "of", "attributes", "from", "a", "given", "set", "of", "resources" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/cli.rb#L589-L596
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/client.rb
OneviewSDK.Client.get_all
def get_all(type, api_ver = @api_version, variant = nil) klass = OneviewSDK.resource_named(type, api_ver, variant) raise TypeError, "Invalid resource type '#{type}'. OneviewSDK::API#{api_ver} does not contain a class like it." unless klass klass.get_all(self) end
ruby
def get_all(type, api_ver = @api_version, variant = nil) klass = OneviewSDK.resource_named(type, api_ver, variant) raise TypeError, "Invalid resource type '#{type}'. OneviewSDK::API#{api_ver} does not contain a class like it." unless klass klass.get_all(self) end
[ "def", "get_all", "(", "type", ",", "api_ver", "=", "@api_version", ",", "variant", "=", "nil", ")", "klass", "=", "OneviewSDK", ".", "resource_named", "(", "type", ",", "api_ver", ",", "variant", ")", "raise", "TypeError", ",", "\"Invalid resource type '#{type}'. OneviewSDK::API#{api_ver} does not contain a class like it.\"", "unless", "klass", "klass", ".", "get_all", "(", "self", ")", "end" ]
Get array of all resources of a specified type @param [String] type Resource type @param [Integer] api_ver API module version to fetch resources from @param [String] variant API module variant to fetch resource from @return [Array<Resource>] Results @example Get all Ethernet Networks networks = @client.get_all('EthernetNetworks') synergy_networks = @client.get_all('EthernetNetworks', 300, 'Synergy') @raise [TypeError] if the type is invalid
[ "Get", "array", "of", "all", "resources", "of", "a", "specified", "type" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/client.rb#L119-L123
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/client.rb
OneviewSDK.Client.wait_for
def wait_for(task_uri) raise ArgumentError, 'Must specify a task_uri!' if task_uri.nil? || task_uri.empty? loop do task_uri.gsub!(%r{https:(.*)\/rest}, '/rest') task = rest_get(task_uri) body = JSON.parse(task.body) case body['taskState'].downcase when 'completed' return body when 'warning' @logger.warn "Task ended with warning status. Details: #{JSON.pretty_generate(body['taskErrors']) rescue body}" return body when 'error', 'killed', 'terminated' msg = "Task ended with bad state: '#{body['taskState']}'.\nResponse: " msg += body['taskErrors'] ? JSON.pretty_generate(body['taskErrors']) : JSON.pretty_generate(body) raise TaskError, msg else print '.' if @print_wait_dots sleep 10 end end end
ruby
def wait_for(task_uri) raise ArgumentError, 'Must specify a task_uri!' if task_uri.nil? || task_uri.empty? loop do task_uri.gsub!(%r{https:(.*)\/rest}, '/rest') task = rest_get(task_uri) body = JSON.parse(task.body) case body['taskState'].downcase when 'completed' return body when 'warning' @logger.warn "Task ended with warning status. Details: #{JSON.pretty_generate(body['taskErrors']) rescue body}" return body when 'error', 'killed', 'terminated' msg = "Task ended with bad state: '#{body['taskState']}'.\nResponse: " msg += body['taskErrors'] ? JSON.pretty_generate(body['taskErrors']) : JSON.pretty_generate(body) raise TaskError, msg else print '.' if @print_wait_dots sleep 10 end end end
[ "def", "wait_for", "(", "task_uri", ")", "raise", "ArgumentError", ",", "'Must specify a task_uri!'", "if", "task_uri", ".", "nil?", "||", "task_uri", ".", "empty?", "loop", "do", "task_uri", ".", "gsub!", "(", "%r{", "\\/", "}", ",", "'/rest'", ")", "task", "=", "rest_get", "(", "task_uri", ")", "body", "=", "JSON", ".", "parse", "(", "task", ".", "body", ")", "case", "body", "[", "'taskState'", "]", ".", "downcase", "when", "'completed'", "return", "body", "when", "'warning'", "@logger", ".", "warn", "\"Task ended with warning status. Details: #{JSON.pretty_generate(body['taskErrors']) rescue body}\"", "return", "body", "when", "'error'", ",", "'killed'", ",", "'terminated'", "msg", "=", "\"Task ended with bad state: '#{body['taskState']}'.\\nResponse: \"", "msg", "+=", "body", "[", "'taskErrors'", "]", "?", "JSON", ".", "pretty_generate", "(", "body", "[", "'taskErrors'", "]", ")", ":", "JSON", ".", "pretty_generate", "(", "body", ")", "raise", "TaskError", ",", "msg", "else", "print", "'.'", "if", "@print_wait_dots", "sleep", "10", "end", "end", "end" ]
Wait for a task to complete @param [String] task_uri @raise [OneviewSDK::TaskError] if the task resulted in an error or early termination. @return [Hash] if the task completed successfully, return the task details
[ "Wait", "for", "a", "task", "to", "complete" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/client.rb#L129-L150
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/client.rb
OneviewSDK.Client.appliance_api_version
def appliance_api_version options = { 'Content-Type' => :none, 'X-API-Version' => :none, 'auth' => :none } response = rest_api(:get, '/rest/version', options) version = response_handler(response)['currentVersion'] raise ConnectionError, "Couldn't get API version" unless version version = version.to_i if version.class != Integer version rescue ConnectionError @logger.warn "Failed to get OneView max api version. Using default (#{OneviewSDK::DEFAULT_API_VERSION})" OneviewSDK::DEFAULT_API_VERSION end
ruby
def appliance_api_version options = { 'Content-Type' => :none, 'X-API-Version' => :none, 'auth' => :none } response = rest_api(:get, '/rest/version', options) version = response_handler(response)['currentVersion'] raise ConnectionError, "Couldn't get API version" unless version version = version.to_i if version.class != Integer version rescue ConnectionError @logger.warn "Failed to get OneView max api version. Using default (#{OneviewSDK::DEFAULT_API_VERSION})" OneviewSDK::DEFAULT_API_VERSION end
[ "def", "appliance_api_version", "options", "=", "{", "'Content-Type'", "=>", ":none", ",", "'X-API-Version'", "=>", ":none", ",", "'auth'", "=>", ":none", "}", "response", "=", "rest_api", "(", ":get", ",", "'/rest/version'", ",", "options", ")", "version", "=", "response_handler", "(", "response", ")", "[", "'currentVersion'", "]", "raise", "ConnectionError", ",", "\"Couldn't get API version\"", "unless", "version", "version", "=", "version", ".", "to_i", "if", "version", ".", "class", "!=", "Integer", "version", "rescue", "ConnectionError", "@logger", ".", "warn", "\"Failed to get OneView max api version. Using default (#{OneviewSDK::DEFAULT_API_VERSION})\"", "OneviewSDK", "::", "DEFAULT_API_VERSION", "end" ]
Get current api version from the OneView appliance
[ "Get", "current", "api", "version", "from", "the", "OneView", "appliance" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/client.rb#L189-L199
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/client.rb
OneviewSDK.Client.login
def login(retries = 2) options = { 'body' => { 'userName' => @user, 'password' => @password, 'authLoginDomain' => @domain } } response = rest_post('/rest/login-sessions', options) body = response_handler(response) return body['sessionID'] if body['sessionID'] raise ConnectionError, "\nERROR! Couldn't log into OneView server at #{@url}. Response: #{response}\n#{response.body}" rescue StandardError => e raise e unless retries > 0 @logger.debug 'Failed to log in to OneView. Retrying...' return login(retries - 1) end
ruby
def login(retries = 2) options = { 'body' => { 'userName' => @user, 'password' => @password, 'authLoginDomain' => @domain } } response = rest_post('/rest/login-sessions', options) body = response_handler(response) return body['sessionID'] if body['sessionID'] raise ConnectionError, "\nERROR! Couldn't log into OneView server at #{@url}. Response: #{response}\n#{response.body}" rescue StandardError => e raise e unless retries > 0 @logger.debug 'Failed to log in to OneView. Retrying...' return login(retries - 1) end
[ "def", "login", "(", "retries", "=", "2", ")", "options", "=", "{", "'body'", "=>", "{", "'userName'", "=>", "@user", ",", "'password'", "=>", "@password", ",", "'authLoginDomain'", "=>", "@domain", "}", "}", "response", "=", "rest_post", "(", "'/rest/login-sessions'", ",", "options", ")", "body", "=", "response_handler", "(", "response", ")", "return", "body", "[", "'sessionID'", "]", "if", "body", "[", "'sessionID'", "]", "raise", "ConnectionError", ",", "\"\\nERROR! Couldn't log into OneView server at #{@url}. Response: #{response}\\n#{response.body}\"", "rescue", "StandardError", "=>", "e", "raise", "e", "unless", "retries", ">", "0", "@logger", ".", "debug", "'Failed to log in to OneView. Retrying...'", "return", "login", "(", "retries", "-", "1", ")", "end" ]
Log in to OneView appliance and return the session token
[ "Log", "in", "to", "OneView", "appliance", "and", "return", "the", "session", "token" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/client.rb#L202-L218
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/rest.rb
OneviewSDK.Rest.rest_api
def rest_api(type, path, options = {}, api_ver = @api_version, redirect_limit = 3) @logger.debug "Making :#{type} rest call to #{@url}#{path}" raise InvalidRequest, 'Must specify path' unless path uri = URI.parse(Addressable::URI.escape(@url + path)) http = build_http_object(uri) request = build_request(type, uri, options.dup, api_ver) response = http.request(request) @logger.debug " Response: Code=#{response.code}. Headers=#{response.to_hash}\n Body=#{response.body}" if response.class <= Net::HTTPRedirection && redirect_limit > 0 && response['location'] @logger.debug "Redirecting to #{response['location']}" return rest_api(type, response['location'], options, api_ver, redirect_limit - 1) end response rescue OpenSSL::SSL::SSLError => e msg = 'SSL verification failed for request. Please either:' msg += "\n 1. Install the certificate into your system's cert store" msg += ". Using cert store: #{ENV['SSL_CERT_FILE']}" if ENV['SSL_CERT_FILE'] msg += "\n 2. Run oneview-sdk-ruby cert import #{@url}" msg += "\n 3. Set the :ssl_enabled option to false for your client (NOT RECOMMENDED)" @logger.error msg raise e end
ruby
def rest_api(type, path, options = {}, api_ver = @api_version, redirect_limit = 3) @logger.debug "Making :#{type} rest call to #{@url}#{path}" raise InvalidRequest, 'Must specify path' unless path uri = URI.parse(Addressable::URI.escape(@url + path)) http = build_http_object(uri) request = build_request(type, uri, options.dup, api_ver) response = http.request(request) @logger.debug " Response: Code=#{response.code}. Headers=#{response.to_hash}\n Body=#{response.body}" if response.class <= Net::HTTPRedirection && redirect_limit > 0 && response['location'] @logger.debug "Redirecting to #{response['location']}" return rest_api(type, response['location'], options, api_ver, redirect_limit - 1) end response rescue OpenSSL::SSL::SSLError => e msg = 'SSL verification failed for request. Please either:' msg += "\n 1. Install the certificate into your system's cert store" msg += ". Using cert store: #{ENV['SSL_CERT_FILE']}" if ENV['SSL_CERT_FILE'] msg += "\n 2. Run oneview-sdk-ruby cert import #{@url}" msg += "\n 3. Set the :ssl_enabled option to false for your client (NOT RECOMMENDED)" @logger.error msg raise e end
[ "def", "rest_api", "(", "type", ",", "path", ",", "options", "=", "{", "}", ",", "api_ver", "=", "@api_version", ",", "redirect_limit", "=", "3", ")", "@logger", ".", "debug", "\"Making :#{type} rest call to #{@url}#{path}\"", "raise", "InvalidRequest", ",", "'Must specify path'", "unless", "path", "uri", "=", "URI", ".", "parse", "(", "Addressable", "::", "URI", ".", "escape", "(", "@url", "+", "path", ")", ")", "http", "=", "build_http_object", "(", "uri", ")", "request", "=", "build_request", "(", "type", ",", "uri", ",", "options", ".", "dup", ",", "api_ver", ")", "response", "=", "http", ".", "request", "(", "request", ")", "@logger", ".", "debug", "\" Response: Code=#{response.code}. Headers=#{response.to_hash}\\n Body=#{response.body}\"", "if", "response", ".", "class", "<=", "Net", "::", "HTTPRedirection", "&&", "redirect_limit", ">", "0", "&&", "response", "[", "'location'", "]", "@logger", ".", "debug", "\"Redirecting to #{response['location']}\"", "return", "rest_api", "(", "type", ",", "response", "[", "'location'", "]", ",", "options", ",", "api_ver", ",", "redirect_limit", "-", "1", ")", "end", "response", "rescue", "OpenSSL", "::", "SSL", "::", "SSLError", "=>", "e", "msg", "=", "'SSL verification failed for request. Please either:'", "msg", "+=", "\"\\n 1. Install the certificate into your system's cert store\"", "msg", "+=", "\". Using cert store: #{ENV['SSL_CERT_FILE']}\"", "if", "ENV", "[", "'SSL_CERT_FILE'", "]", "msg", "+=", "\"\\n 2. Run oneview-sdk-ruby cert import #{@url}\"", "msg", "+=", "\"\\n 3. Set the :ssl_enabled option to false for your client (NOT RECOMMENDED)\"", "@logger", ".", "error", "msg", "raise", "e", "end" ]
in seconds, 5 minutes Makes a restful API request to OneView @param [Symbol] type The rest method/type Options: [:get, :post, :delete, :patch, :put] @param [String] path The path for the request. Usually starts with "/rest/" @param [Hash] options The options for the request @option options [String] :body Hash to be converted into json and set as the request body @option options [String] :Content-Type ('application/json') Set to nil or :none to have this option removed @option options [Integer] :X-API-Version (client.api_version) API version to use for this request @option options [Integer] :auth (client.token) Authentication token to use for this request @param [Integer] api_ver The api version to use when interracting with this resource @param [Integer] redirect_limit Number of redirects it is allowed to follow @raise [OpenSSL::SSL::SSLError] if SSL validation of OneView instance's certificate failed @return [NetHTTPResponse] Response object
[ "in", "seconds", "5", "minutes", "Makes", "a", "restful", "API", "request", "to", "OneView" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/rest.rb#L36-L57
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/rest.rb
OneviewSDK.Rest.upload_file
def upload_file(file_path, path, options = {}, timeout = READ_TIMEOUT) raise NotFound, "ERROR: File '#{file_path}' not found!" unless File.file?(file_path) options = Hash[options.map { |k, v| [k.to_s, v] }] body_params = options['body'] || {} headers_params = options['header'] || {} headers = { 'Content-Type' => 'multipart/form-data', 'X-Api-Version' => @api_version.to_s, 'auth' => @token } headers.merge!(headers_params) File.open(file_path) do |file| name_to_show = options['file_name'] || File.basename(file_path) body_params['file'] = UploadIO.new(file, 'application/octet-stream', name_to_show) uri = URI.parse(Addressable::URI.escape(@url + path)) http_request = build_http_object(uri) http_request.read_timeout = timeout req = Net::HTTP::Post::Multipart.new( uri.path, body_params, headers ) http_request.start do |http| begin response = http.request(req) return response_handler(response) rescue Net::ReadTimeout raise "The connection was closed because the timeout of #{timeout} seconds has expired."\ 'You can specify the timeout in seconds by passing the timeout on the method call.'\ 'Interrupted file uploads may result in corrupted file remaining in the appliance.'\ 'HPE recommends checking the appliance for corrupted file and removing it.' end end end end
ruby
def upload_file(file_path, path, options = {}, timeout = READ_TIMEOUT) raise NotFound, "ERROR: File '#{file_path}' not found!" unless File.file?(file_path) options = Hash[options.map { |k, v| [k.to_s, v] }] body_params = options['body'] || {} headers_params = options['header'] || {} headers = { 'Content-Type' => 'multipart/form-data', 'X-Api-Version' => @api_version.to_s, 'auth' => @token } headers.merge!(headers_params) File.open(file_path) do |file| name_to_show = options['file_name'] || File.basename(file_path) body_params['file'] = UploadIO.new(file, 'application/octet-stream', name_to_show) uri = URI.parse(Addressable::URI.escape(@url + path)) http_request = build_http_object(uri) http_request.read_timeout = timeout req = Net::HTTP::Post::Multipart.new( uri.path, body_params, headers ) http_request.start do |http| begin response = http.request(req) return response_handler(response) rescue Net::ReadTimeout raise "The connection was closed because the timeout of #{timeout} seconds has expired."\ 'You can specify the timeout in seconds by passing the timeout on the method call.'\ 'Interrupted file uploads may result in corrupted file remaining in the appliance.'\ 'HPE recommends checking the appliance for corrupted file and removing it.' end end end end
[ "def", "upload_file", "(", "file_path", ",", "path", ",", "options", "=", "{", "}", ",", "timeout", "=", "READ_TIMEOUT", ")", "raise", "NotFound", ",", "\"ERROR: File '#{file_path}' not found!\"", "unless", "File", ".", "file?", "(", "file_path", ")", "options", "=", "Hash", "[", "options", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", "]", "}", "]", "body_params", "=", "options", "[", "'body'", "]", "||", "{", "}", "headers_params", "=", "options", "[", "'header'", "]", "||", "{", "}", "headers", "=", "{", "'Content-Type'", "=>", "'multipart/form-data'", ",", "'X-Api-Version'", "=>", "@api_version", ".", "to_s", ",", "'auth'", "=>", "@token", "}", "headers", ".", "merge!", "(", "headers_params", ")", "File", ".", "open", "(", "file_path", ")", "do", "|", "file", "|", "name_to_show", "=", "options", "[", "'file_name'", "]", "||", "File", ".", "basename", "(", "file_path", ")", "body_params", "[", "'file'", "]", "=", "UploadIO", ".", "new", "(", "file", ",", "'application/octet-stream'", ",", "name_to_show", ")", "uri", "=", "URI", ".", "parse", "(", "Addressable", "::", "URI", ".", "escape", "(", "@url", "+", "path", ")", ")", "http_request", "=", "build_http_object", "(", "uri", ")", "http_request", ".", "read_timeout", "=", "timeout", "req", "=", "Net", "::", "HTTP", "::", "Post", "::", "Multipart", ".", "new", "(", "uri", ".", "path", ",", "body_params", ",", "headers", ")", "http_request", ".", "start", "do", "|", "http", "|", "begin", "response", "=", "http", ".", "request", "(", "req", ")", "return", "response_handler", "(", "response", ")", "rescue", "Net", "::", "ReadTimeout", "raise", "\"The connection was closed because the timeout of #{timeout} seconds has expired.\"", "'You can specify the timeout in seconds by passing the timeout on the method call.'", "'Interrupted file uploads may result in corrupted file remaining in the appliance.'", "'HPE recommends checking the appliance for corrupted file and removing it.'", "end", "end", "end", "end" ]
Uploads a file to a specific uri @param [String] file_path @param [String] path The url path starting with "/" @param [Hash] options The options for the request. Default is {}. @option options [String] :body Hash to be converted into json and set as the request body @option options [String] :header Hash to be converted into json and set as the request header @option options [String] :file_name String that defines the new file name @param [Integer] timeout The number of seconds to wait for completing the request. Default is 300. @return [Hash] The parsed JSON body of response
[ "Uploads", "a", "file", "to", "a", "specific", "uri" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/rest.rb#L132-L170
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/rest.rb
OneviewSDK.Rest.download_file
def download_file(path, local_drive_path) uri = URI.parse(Addressable::URI.escape(@url + path)) http_request = build_http_object(uri) req = build_request(:get, uri, {}, @api_version.to_s) http_request.start do |http| http.request(req) do |res| response_handler(res) unless res.code.to_i.between?(200, 204) File.open(local_drive_path, 'wb') do |file| res.read_body do |segment| file.write(segment) end end end end true end
ruby
def download_file(path, local_drive_path) uri = URI.parse(Addressable::URI.escape(@url + path)) http_request = build_http_object(uri) req = build_request(:get, uri, {}, @api_version.to_s) http_request.start do |http| http.request(req) do |res| response_handler(res) unless res.code.to_i.between?(200, 204) File.open(local_drive_path, 'wb') do |file| res.read_body do |segment| file.write(segment) end end end end true end
[ "def", "download_file", "(", "path", ",", "local_drive_path", ")", "uri", "=", "URI", ".", "parse", "(", "Addressable", "::", "URI", ".", "escape", "(", "@url", "+", "path", ")", ")", "http_request", "=", "build_http_object", "(", "uri", ")", "req", "=", "build_request", "(", ":get", ",", "uri", ",", "{", "}", ",", "@api_version", ".", "to_s", ")", "http_request", ".", "start", "do", "|", "http", "|", "http", ".", "request", "(", "req", ")", "do", "|", "res", "|", "response_handler", "(", "res", ")", "unless", "res", ".", "code", ".", "to_i", ".", "between?", "(", "200", ",", "204", ")", "File", ".", "open", "(", "local_drive_path", ",", "'wb'", ")", "do", "|", "file", "|", "res", ".", "read_body", "do", "|", "segment", "|", "file", ".", "write", "(", "segment", ")", "end", "end", "end", "end", "true", "end" ]
Download a file from a specific uri @param [String] path The url path starting with "/" @param [String] local_drive_path Path to save file downloaded @return [Boolean] if file was downloaded
[ "Download", "a", "file", "from", "a", "specific", "uri" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/rest.rb#L176-L192
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/rest.rb
OneviewSDK.Rest.response_handler
def response_handler(response, wait_on_task = true) case response.code.to_i when RESPONSE_CODE_OK # Synchronous read/query begin return JSON.parse(response.body) rescue JSON::ParserError => e @logger.warn "Failed to parse JSON response. #{e}" return response.body end when RESPONSE_CODE_CREATED # Synchronous add JSON.parse(response.body) when RESPONSE_CODE_ACCEPTED # Asynchronous add, update or delete return JSON.parse(response.body) unless wait_on_task @logger.debug "Waiting for task: response.header['location']" uri = response.header['location'] || JSON.parse(response.body)['uri'] # If task uri is not returned in header task = wait_for(uri) return true unless task['associatedResource'] && task['associatedResource']['resourceUri'] resource_data = rest_get(task['associatedResource']['resourceUri']) JSON.parse(resource_data.body) when RESPONSE_CODE_NO_CONTENT # Synchronous delete {} when RESPONSE_CODE_BAD_REQUEST BadRequest.raise! "400 BAD REQUEST #{response.body}", response when RESPONSE_CODE_UNAUTHORIZED Unauthorized.raise! "401 UNAUTHORIZED #{response.body}", response when RESPONSE_CODE_NOT_FOUND NotFound.raise! "404 NOT FOUND #{response.body}", response else RequestError.raise! "#{response.code} #{response.body}", response end end
ruby
def response_handler(response, wait_on_task = true) case response.code.to_i when RESPONSE_CODE_OK # Synchronous read/query begin return JSON.parse(response.body) rescue JSON::ParserError => e @logger.warn "Failed to parse JSON response. #{e}" return response.body end when RESPONSE_CODE_CREATED # Synchronous add JSON.parse(response.body) when RESPONSE_CODE_ACCEPTED # Asynchronous add, update or delete return JSON.parse(response.body) unless wait_on_task @logger.debug "Waiting for task: response.header['location']" uri = response.header['location'] || JSON.parse(response.body)['uri'] # If task uri is not returned in header task = wait_for(uri) return true unless task['associatedResource'] && task['associatedResource']['resourceUri'] resource_data = rest_get(task['associatedResource']['resourceUri']) JSON.parse(resource_data.body) when RESPONSE_CODE_NO_CONTENT # Synchronous delete {} when RESPONSE_CODE_BAD_REQUEST BadRequest.raise! "400 BAD REQUEST #{response.body}", response when RESPONSE_CODE_UNAUTHORIZED Unauthorized.raise! "401 UNAUTHORIZED #{response.body}", response when RESPONSE_CODE_NOT_FOUND NotFound.raise! "404 NOT FOUND #{response.body}", response else RequestError.raise! "#{response.code} #{response.body}", response end end
[ "def", "response_handler", "(", "response", ",", "wait_on_task", "=", "true", ")", "case", "response", ".", "code", ".", "to_i", "when", "RESPONSE_CODE_OK", "begin", "return", "JSON", ".", "parse", "(", "response", ".", "body", ")", "rescue", "JSON", "::", "ParserError", "=>", "e", "@logger", ".", "warn", "\"Failed to parse JSON response. #{e}\"", "return", "response", ".", "body", "end", "when", "RESPONSE_CODE_CREATED", "JSON", ".", "parse", "(", "response", ".", "body", ")", "when", "RESPONSE_CODE_ACCEPTED", "return", "JSON", ".", "parse", "(", "response", ".", "body", ")", "unless", "wait_on_task", "@logger", ".", "debug", "\"Waiting for task: response.header['location']\"", "uri", "=", "response", ".", "header", "[", "'location'", "]", "||", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "'uri'", "]", "task", "=", "wait_for", "(", "uri", ")", "return", "true", "unless", "task", "[", "'associatedResource'", "]", "&&", "task", "[", "'associatedResource'", "]", "[", "'resourceUri'", "]", "resource_data", "=", "rest_get", "(", "task", "[", "'associatedResource'", "]", "[", "'resourceUri'", "]", ")", "JSON", ".", "parse", "(", "resource_data", ".", "body", ")", "when", "RESPONSE_CODE_NO_CONTENT", "{", "}", "when", "RESPONSE_CODE_BAD_REQUEST", "BadRequest", ".", "raise!", "\"400 BAD REQUEST #{response.body}\"", ",", "response", "when", "RESPONSE_CODE_UNAUTHORIZED", "Unauthorized", ".", "raise!", "\"401 UNAUTHORIZED #{response.body}\"", ",", "response", "when", "RESPONSE_CODE_NOT_FOUND", "NotFound", ".", "raise!", "\"404 NOT FOUND #{response.body}\"", ",", "response", "else", "RequestError", ".", "raise!", "\"#{response.code} #{response.body}\"", ",", "response", "end", "end" ]
Handles the response from a rest call. If an asynchronous task was started, this waits for it to complete. @param [HTTPResponse] response HTTP response @param [Boolean] wait_on_task Wait on task (or just return task details) @raise [OneviewSDK::OneViewError] if the request failed or a task did not complete successfully @return [Hash] The parsed JSON body
[ "Handles", "the", "response", "from", "a", "rest", "call", ".", "If", "an", "asynchronous", "task", "was", "started", "this", "waits", "for", "it", "to", "complete", "." ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/rest.rb#L208-L238
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/rest.rb
OneviewSDK.Rest.build_http_object
def build_http_object(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' if @ssl_enabled http.cert_store = @cert_store if @cert_store else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.read_timeout = @timeout if @timeout # Timeout for a request http.open_timeout = @timeout if @timeout # Timeout for a connection http end
ruby
def build_http_object(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' if @ssl_enabled http.cert_store = @cert_store if @cert_store else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.read_timeout = @timeout if @timeout # Timeout for a request http.open_timeout = @timeout if @timeout # Timeout for a connection http end
[ "def", "build_http_object", "(", "uri", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "if", "uri", ".", "scheme", "==", "'https'", "if", "@ssl_enabled", "http", ".", "cert_store", "=", "@cert_store", "if", "@cert_store", "else", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "http", ".", "read_timeout", "=", "@timeout", "if", "@timeout", "http", ".", "open_timeout", "=", "@timeout", "if", "@timeout", "http", "end" ]
Builds a http object using the data given
[ "Builds", "a", "http", "object", "using", "the", "data", "given" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/rest.rb#L244-L254
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/rest.rb
OneviewSDK.Rest.build_request
def build_request(type, uri, options, api_ver) case type.downcase.to_sym when :get request = Net::HTTP::Get.new(uri.request_uri) when :post request = Net::HTTP::Post.new(uri.request_uri) when :put request = Net::HTTP::Put.new(uri.request_uri) when :patch request = Net::HTTP::Patch.new(uri.request_uri) when :delete request = Net::HTTP::Delete.new(uri.request_uri) else raise InvalidRequest, "Invalid rest method: #{type}. Valid methods are: get, post, put, patch, delete" end options['X-API-Version'] ||= api_ver options['auth'] ||= @token options['Content-Type'] ||= 'application/json' options.delete('Content-Type') if [:none, 'none', nil].include?(options['Content-Type']) options.delete('X-API-Version') if [:none, 'none', nil].include?(options['X-API-Version']) options.delete('auth') if [:none, 'none', nil].include?(options['auth']) options.each do |key, val| if key.to_s.downcase == 'body' request.body = val.to_json rescue val else request[key] = val end end @logger.debug " Options: #{options}" # Warning: This may include passwords and tokens request end
ruby
def build_request(type, uri, options, api_ver) case type.downcase.to_sym when :get request = Net::HTTP::Get.new(uri.request_uri) when :post request = Net::HTTP::Post.new(uri.request_uri) when :put request = Net::HTTP::Put.new(uri.request_uri) when :patch request = Net::HTTP::Patch.new(uri.request_uri) when :delete request = Net::HTTP::Delete.new(uri.request_uri) else raise InvalidRequest, "Invalid rest method: #{type}. Valid methods are: get, post, put, patch, delete" end options['X-API-Version'] ||= api_ver options['auth'] ||= @token options['Content-Type'] ||= 'application/json' options.delete('Content-Type') if [:none, 'none', nil].include?(options['Content-Type']) options.delete('X-API-Version') if [:none, 'none', nil].include?(options['X-API-Version']) options.delete('auth') if [:none, 'none', nil].include?(options['auth']) options.each do |key, val| if key.to_s.downcase == 'body' request.body = val.to_json rescue val else request[key] = val end end @logger.debug " Options: #{options}" # Warning: This may include passwords and tokens request end
[ "def", "build_request", "(", "type", ",", "uri", ",", "options", ",", "api_ver", ")", "case", "type", ".", "downcase", ".", "to_sym", "when", ":get", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ")", "when", ":post", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ")", "when", ":put", "request", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "uri", ".", "request_uri", ")", "when", ":patch", "request", "=", "Net", "::", "HTTP", "::", "Patch", ".", "new", "(", "uri", ".", "request_uri", ")", "when", ":delete", "request", "=", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "uri", ".", "request_uri", ")", "else", "raise", "InvalidRequest", ",", "\"Invalid rest method: #{type}. Valid methods are: get, post, put, patch, delete\"", "end", "options", "[", "'X-API-Version'", "]", "||=", "api_ver", "options", "[", "'auth'", "]", "||=", "@token", "options", "[", "'Content-Type'", "]", "||=", "'application/json'", "options", ".", "delete", "(", "'Content-Type'", ")", "if", "[", ":none", ",", "'none'", ",", "nil", "]", ".", "include?", "(", "options", "[", "'Content-Type'", "]", ")", "options", ".", "delete", "(", "'X-API-Version'", ")", "if", "[", ":none", ",", "'none'", ",", "nil", "]", ".", "include?", "(", "options", "[", "'X-API-Version'", "]", ")", "options", ".", "delete", "(", "'auth'", ")", "if", "[", ":none", ",", "'none'", ",", "nil", "]", ".", "include?", "(", "options", "[", "'auth'", "]", ")", "options", ".", "each", "do", "|", "key", ",", "val", "|", "if", "key", ".", "to_s", ".", "downcase", "==", "'body'", "request", ".", "body", "=", "val", ".", "to_json", "rescue", "val", "else", "request", "[", "key", "]", "=", "val", "end", "end", "@logger", ".", "debug", "\" Options: #{options}\"", "request", "end" ]
Builds a request object using the data given
[ "Builds", "a", "request", "object", "using", "the", "data", "given" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/rest.rb#L257-L290
train
antek-drzewiecki/wine_bouncer
lib/wine_bouncer/oauth2.rb
WineBouncer.OAuth2.doorkeeper_authorize!
def doorkeeper_authorize!(*scopes) scopes = Doorkeeper.configuration.default_scopes if scopes.empty? unless valid_doorkeeper_token?(*scopes) if !doorkeeper_token || !doorkeeper_token.accessible? error = Doorkeeper::OAuth::InvalidTokenResponse.from_access_token(doorkeeper_token) raise WineBouncer::Errors::OAuthUnauthorizedError, error else error = Doorkeeper::OAuth::ForbiddenTokenResponse.from_scopes(scopes) raise WineBouncer::Errors::OAuthForbiddenError, error end end end
ruby
def doorkeeper_authorize!(*scopes) scopes = Doorkeeper.configuration.default_scopes if scopes.empty? unless valid_doorkeeper_token?(*scopes) if !doorkeeper_token || !doorkeeper_token.accessible? error = Doorkeeper::OAuth::InvalidTokenResponse.from_access_token(doorkeeper_token) raise WineBouncer::Errors::OAuthUnauthorizedError, error else error = Doorkeeper::OAuth::ForbiddenTokenResponse.from_scopes(scopes) raise WineBouncer::Errors::OAuthForbiddenError, error end end end
[ "def", "doorkeeper_authorize!", "(", "*", "scopes", ")", "scopes", "=", "Doorkeeper", ".", "configuration", ".", "default_scopes", "if", "scopes", ".", "empty?", "unless", "valid_doorkeeper_token?", "(", "*", "scopes", ")", "if", "!", "doorkeeper_token", "||", "!", "doorkeeper_token", ".", "accessible?", "error", "=", "Doorkeeper", "::", "OAuth", "::", "InvalidTokenResponse", ".", "from_access_token", "(", "doorkeeper_token", ")", "raise", "WineBouncer", "::", "Errors", "::", "OAuthUnauthorizedError", ",", "error", "else", "error", "=", "Doorkeeper", "::", "OAuth", "::", "ForbiddenTokenResponse", ".", "from_scopes", "(", "scopes", ")", "raise", "WineBouncer", "::", "Errors", "::", "OAuthForbiddenError", ",", "error", "end", "end", "end" ]
This method handles the authorization, raises errors if authorization has failed.
[ "This", "method", "handles", "the", "authorization", "raises", "errors", "if", "authorization", "has", "failed", "." ]
01d3b0d302c10300f9a0437702997c4017b5f0bc
https://github.com/antek-drzewiecki/wine_bouncer/blob/01d3b0d302c10300f9a0437702997c4017b5f0bc/lib/wine_bouncer/oauth2.rb#L61-L72
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.exists?
def exists?(header = self.class::DEFAULT_REQUEST_HEADER) retrieval_keys = self.class::UNIQUE_IDENTIFIERS.reject { |k| @data[k].nil? } raise IncompleteResource, "Must set resource #{self.class::UNIQUE_IDENTIFIERS.join(' or ')} before trying to retrieve!" if retrieval_keys.empty? retrieval_keys.each do |k| results = self.class.find_by(@client, { k => @data[k] }, self.class::BASE_URI, header) return true if results.size == 1 end false end
ruby
def exists?(header = self.class::DEFAULT_REQUEST_HEADER) retrieval_keys = self.class::UNIQUE_IDENTIFIERS.reject { |k| @data[k].nil? } raise IncompleteResource, "Must set resource #{self.class::UNIQUE_IDENTIFIERS.join(' or ')} before trying to retrieve!" if retrieval_keys.empty? retrieval_keys.each do |k| results = self.class.find_by(@client, { k => @data[k] }, self.class::BASE_URI, header) return true if results.size == 1 end false end
[ "def", "exists?", "(", "header", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "retrieval_keys", "=", "self", ".", "class", "::", "UNIQUE_IDENTIFIERS", ".", "reject", "{", "|", "k", "|", "@data", "[", "k", "]", ".", "nil?", "}", "raise", "IncompleteResource", ",", "\"Must set resource #{self.class::UNIQUE_IDENTIFIERS.join(' or ')} before trying to retrieve!\"", "if", "retrieval_keys", ".", "empty?", "retrieval_keys", ".", "each", "do", "|", "k", "|", "results", "=", "self", ".", "class", ".", "find_by", "(", "@client", ",", "{", "k", "=>", "@data", "[", "k", "]", "}", ",", "self", ".", "class", "::", "BASE_URI", ",", "header", ")", "return", "true", "if", "results", ".", "size", "==", "1", "end", "false", "end" ]
Check if a resource exists @note one of the UNIQUE_IDENTIFIERS, e.g. name or uri, must be specified in the resource @param [Hash] header The header options for the request (key-value pairs) @return [Boolean] Whether or not resource exists
[ "Check", "if", "a", "resource", "exists" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L68-L76
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.deep_merge!
def deep_merge!(other_data, target_data = @data) raise 'Both arguments should be a object Hash' unless other_data.is_a?(Hash) && target_data.is_a?(Hash) other_data.each do |key, value| value_target = target_data[key.to_s] if value_target.is_a?(Hash) && value.is_a?(Hash) deep_merge!(value, value_target) else target_data[key.to_s] = value end end end
ruby
def deep_merge!(other_data, target_data = @data) raise 'Both arguments should be a object Hash' unless other_data.is_a?(Hash) && target_data.is_a?(Hash) other_data.each do |key, value| value_target = target_data[key.to_s] if value_target.is_a?(Hash) && value.is_a?(Hash) deep_merge!(value, value_target) else target_data[key.to_s] = value end end end
[ "def", "deep_merge!", "(", "other_data", ",", "target_data", "=", "@data", ")", "raise", "'Both arguments should be a object Hash'", "unless", "other_data", ".", "is_a?", "(", "Hash", ")", "&&", "target_data", ".", "is_a?", "(", "Hash", ")", "other_data", ".", "each", "do", "|", "key", ",", "value", "|", "value_target", "=", "target_data", "[", "key", ".", "to_s", "]", "if", "value_target", ".", "is_a?", "(", "Hash", ")", "&&", "value", ".", "is_a?", "(", "Hash", ")", "deep_merge!", "(", "value", ",", "value_target", ")", "else", "target_data", "[", "key", ".", "to_s", "]", "=", "value", "end", "end", "end" ]
Merges the first hash data structure with the second @note both arguments should be a Ruby Hash object. The second hash should have strings as a keys. This method will change the second argument. @raise [StandardError] if the arguments, or one them, is not a Hash object
[ "Merges", "the", "first", "hash", "data", "structure", "with", "the", "second" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L83-L93
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.set_all
def set_all(params = self.class::DEFAULT_REQUEST_HEADER) params = params.data if params.class <= Resource params = Hash[params.map { |(k, v)| [k.to_s, v] }] params.each { |key, value| set(key.to_s, value) } self end
ruby
def set_all(params = self.class::DEFAULT_REQUEST_HEADER) params = params.data if params.class <= Resource params = Hash[params.map { |(k, v)| [k.to_s, v] }] params.each { |key, value| set(key.to_s, value) } self end
[ "def", "set_all", "(", "params", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "params", "=", "params", ".", "data", "if", "params", ".", "class", "<=", "Resource", "params", "=", "Hash", "[", "params", ".", "map", "{", "|", "(", "k", ",", "v", ")", "|", "[", "k", ".", "to_s", ",", "v", "]", "}", "]", "params", ".", "each", "{", "|", "key", ",", "value", "|", "set", "(", "key", ".", "to_s", ",", "value", ")", "}", "self", "end" ]
Set the given hash of key-value pairs as resource data attributes @param [Hash, Resource] params The options for this resource (key-value pairs or resource object) @note All top-level keys will be converted to strings @return [Resource] self
[ "Set", "the", "given", "hash", "of", "key", "-", "value", "pairs", "as", "resource", "data", "attributes" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L99-L104
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.set
def set(key, value) method_name = "validate_#{key}" send(method_name.to_sym, value) if respond_to?(method_name.to_sym) @data[key.to_s] = value end
ruby
def set(key, value) method_name = "validate_#{key}" send(method_name.to_sym, value) if respond_to?(method_name.to_sym) @data[key.to_s] = value end
[ "def", "set", "(", "key", ",", "value", ")", "method_name", "=", "\"validate_#{key}\"", "send", "(", "method_name", ".", "to_sym", ",", "value", ")", "if", "respond_to?", "(", "method_name", ".", "to_sym", ")", "@data", "[", "key", ".", "to_s", "]", "=", "value", "end" ]
Set a resource attribute with the given value and call any validation method if necessary @param [String] key attribute name @param value value to assign to the given attribute @note Keys will be converted to strings
[ "Set", "a", "resource", "attribute", "with", "the", "given", "value", "and", "call", "any", "validation", "method", "if", "necessary" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L110-L114
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.create
def create(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client options = {}.merge(header).merge('body' => @data) response = @client.rest_post(self.class::BASE_URI, options, @api_version) body = @client.response_handler(response) set_all(body) self end
ruby
def create(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client options = {}.merge(header).merge('body' => @data) response = @client.rest_post(self.class::BASE_URI, options, @api_version) body = @client.response_handler(response) set_all(body) self end
[ "def", "create", "(", "header", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "ensure_client", "options", "=", "{", "}", ".", "merge", "(", "header", ")", ".", "merge", "(", "'body'", "=>", "@data", ")", "response", "=", "@client", ".", "rest_post", "(", "self", ".", "class", "::", "BASE_URI", ",", "options", ",", "@api_version", ")", "body", "=", "@client", ".", "response_handler", "(", "response", ")", "set_all", "(", "body", ")", "self", "end" ]
Create the resource on OneView using the current data @note Calls the refresh method to set additional data @param [Hash] header The header options for the request (key-value pairs) @raise [OneviewSDK::IncompleteResource] if the client is not set @raise [StandardError] if the resource creation fails @return [Resource] self
[ "Create", "the", "resource", "on", "OneView", "using", "the", "current", "data" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L172-L179
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.create!
def create!(header = self.class::DEFAULT_REQUEST_HEADER) temp = self.class.new(@client, @data) temp.delete(header) if temp.retrieve!(header) create(header) end
ruby
def create!(header = self.class::DEFAULT_REQUEST_HEADER) temp = self.class.new(@client, @data) temp.delete(header) if temp.retrieve!(header) create(header) end
[ "def", "create!", "(", "header", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "temp", "=", "self", ".", "class", ".", "new", "(", "@client", ",", "@data", ")", "temp", ".", "delete", "(", "header", ")", "if", "temp", ".", "retrieve!", "(", "header", ")", "create", "(", "header", ")", "end" ]
Delete the resource from OneView if it exists, then create it using the current data @note Calls refresh method to set additional data @param [Hash] header The header options for the request (key-value pairs) @raise [OneviewSDK::IncompleteResource] if the client is not set @raise [StandardError] if the resource creation fails @return [Resource] self
[ "Delete", "the", "resource", "from", "OneView", "if", "it", "exists", "then", "create", "it", "using", "the", "current", "data" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L187-L191
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.refresh
def refresh(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client && ensure_uri response = @client.rest_get(@data['uri'], header, @api_version) body = @client.response_handler(response) set_all(body) self end
ruby
def refresh(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client && ensure_uri response = @client.rest_get(@data['uri'], header, @api_version) body = @client.response_handler(response) set_all(body) self end
[ "def", "refresh", "(", "header", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "ensure_client", "&&", "ensure_uri", "response", "=", "@client", ".", "rest_get", "(", "@data", "[", "'uri'", "]", ",", "header", ",", "@api_version", ")", "body", "=", "@client", ".", "response_handler", "(", "response", ")", "set_all", "(", "body", ")", "self", "end" ]
Updates this object using the data that exists on OneView @note Will overwrite any data that differs from OneView @param [Hash] header The header options for the request (key-value pairs) @return [Resource] self
[ "Updates", "this", "object", "using", "the", "data", "that", "exists", "on", "OneView" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L197-L203
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.update
def update(attributes = {}, header = self.class::DEFAULT_REQUEST_HEADER) set_all(attributes) ensure_client && ensure_uri options = {}.merge(header).merge('body' => @data) response = @client.rest_put(@data['uri'], options, @api_version) @client.response_handler(response) self end
ruby
def update(attributes = {}, header = self.class::DEFAULT_REQUEST_HEADER) set_all(attributes) ensure_client && ensure_uri options = {}.merge(header).merge('body' => @data) response = @client.rest_put(@data['uri'], options, @api_version) @client.response_handler(response) self end
[ "def", "update", "(", "attributes", "=", "{", "}", ",", "header", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "set_all", "(", "attributes", ")", "ensure_client", "&&", "ensure_uri", "options", "=", "{", "}", ".", "merge", "(", "header", ")", ".", "merge", "(", "'body'", "=>", "@data", ")", "response", "=", "@client", ".", "rest_put", "(", "@data", "[", "'uri'", "]", ",", "options", ",", "@api_version", ")", "@client", ".", "response_handler", "(", "response", ")", "self", "end" ]
Set data and save to OneView @param [Hash] attributes The attributes to add/change for this resource (key-value pairs) @param [Hash] header The header options for the request (key-value pairs) @raise [OneviewSDK::IncompleteResource] if the client or uri is not set @raise [StandardError] if the resource save fails @return [Resource] self
[ "Set", "data", "and", "save", "to", "OneView" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L211-L218
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.delete
def delete(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client && ensure_uri response = @client.rest_delete(@data['uri'], header, @api_version) @client.response_handler(response) true end
ruby
def delete(header = self.class::DEFAULT_REQUEST_HEADER) ensure_client && ensure_uri response = @client.rest_delete(@data['uri'], header, @api_version) @client.response_handler(response) true end
[ "def", "delete", "(", "header", "=", "self", ".", "class", "::", "DEFAULT_REQUEST_HEADER", ")", "ensure_client", "&&", "ensure_uri", "response", "=", "@client", ".", "rest_delete", "(", "@data", "[", "'uri'", "]", ",", "header", ",", "@api_version", ")", "@client", ".", "response_handler", "(", "response", ")", "true", "end" ]
Delete resource from OneView @param [Hash] header The header options for the request (key-value pairs) @return [true] if resource was deleted successfully
[ "Delete", "resource", "from", "OneView" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L223-L228
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.to_file
def to_file(file_path, format = :json) format = :yml if %w[.yml .yaml].include? File.extname(file_path) temp_data = { type: self.class.name, api_version: @api_version, data: @data } case format.to_sym when :json File.open(file_path, 'w') { |f| f.write(JSON.pretty_generate(temp_data)) } when :yml, :yaml File.open(file_path, 'w') { |f| f.write(temp_data.to_yaml) } else raise InvalidFormat, "Invalid format: #{format}" end true end
ruby
def to_file(file_path, format = :json) format = :yml if %w[.yml .yaml].include? File.extname(file_path) temp_data = { type: self.class.name, api_version: @api_version, data: @data } case format.to_sym when :json File.open(file_path, 'w') { |f| f.write(JSON.pretty_generate(temp_data)) } when :yml, :yaml File.open(file_path, 'w') { |f| f.write(temp_data.to_yaml) } else raise InvalidFormat, "Invalid format: #{format}" end true end
[ "def", "to_file", "(", "file_path", ",", "format", "=", ":json", ")", "format", "=", ":yml", "if", "%w[", ".yml", ".yaml", "]", ".", "include?", "File", ".", "extname", "(", "file_path", ")", "temp_data", "=", "{", "type", ":", "self", ".", "class", ".", "name", ",", "api_version", ":", "@api_version", ",", "data", ":", "@data", "}", "case", "format", ".", "to_sym", "when", ":json", "File", ".", "open", "(", "file_path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "JSON", ".", "pretty_generate", "(", "temp_data", ")", ")", "}", "when", ":yml", ",", ":yaml", "File", ".", "open", "(", "file_path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "temp_data", ".", "to_yaml", ")", "}", "else", "raise", "InvalidFormat", ",", "\"Invalid format: #{format}\"", "end", "true", "end" ]
Save resource to json or yaml file @param [String] file_path The full path to the file @param [Symbol] format The format. Options: [:json, :yml, :yaml]. Defaults to .json @note If a .yml or .yaml file extension is given in the file_path, the format will be set automatically @return [True] The Resource was saved successfully
[ "Save", "resource", "to", "json", "or", "yaml", "file" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L235-L247
train
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource.rb
OneviewSDK.Resource.recursive_like?
def recursive_like?(other, data = @data) raise "Can't compare with object type: #{other.class}! Must respond_to :each" unless other.respond_to?(:each) other.each do |key, val| return false unless data && data.respond_to?(:[]) if val.is_a?(Hash) return false unless data.class == Hash && recursive_like?(val, data[key.to_s]) elsif val.is_a?(Array) && val.first.is_a?(Hash) data_array = data[key.to_s] || data[key.to_sym] return false unless data_array.is_a?(Array) val.each do |other_item| return false unless data_array.find { |data_item| recursive_like?(other_item, data_item) } end elsif val.to_s != data[key.to_s].to_s && val.to_s != data[key.to_sym].to_s return false end end true end
ruby
def recursive_like?(other, data = @data) raise "Can't compare with object type: #{other.class}! Must respond_to :each" unless other.respond_to?(:each) other.each do |key, val| return false unless data && data.respond_to?(:[]) if val.is_a?(Hash) return false unless data.class == Hash && recursive_like?(val, data[key.to_s]) elsif val.is_a?(Array) && val.first.is_a?(Hash) data_array = data[key.to_s] || data[key.to_sym] return false unless data_array.is_a?(Array) val.each do |other_item| return false unless data_array.find { |data_item| recursive_like?(other_item, data_item) } end elsif val.to_s != data[key.to_s].to_s && val.to_s != data[key.to_sym].to_s return false end end true end
[ "def", "recursive_like?", "(", "other", ",", "data", "=", "@data", ")", "raise", "\"Can't compare with object type: #{other.class}! Must respond_to :each\"", "unless", "other", ".", "respond_to?", "(", ":each", ")", "other", ".", "each", "do", "|", "key", ",", "val", "|", "return", "false", "unless", "data", "&&", "data", ".", "respond_to?", "(", ":[]", ")", "if", "val", ".", "is_a?", "(", "Hash", ")", "return", "false", "unless", "data", ".", "class", "==", "Hash", "&&", "recursive_like?", "(", "val", ",", "data", "[", "key", ".", "to_s", "]", ")", "elsif", "val", ".", "is_a?", "(", "Array", ")", "&&", "val", ".", "first", ".", "is_a?", "(", "Hash", ")", "data_array", "=", "data", "[", "key", ".", "to_s", "]", "||", "data", "[", "key", ".", "to_sym", "]", "return", "false", "unless", "data_array", ".", "is_a?", "(", "Array", ")", "val", ".", "each", "do", "|", "other_item", "|", "return", "false", "unless", "data_array", ".", "find", "{", "|", "data_item", "|", "recursive_like?", "(", "other_item", ",", "data_item", ")", "}", "end", "elsif", "val", ".", "to_s", "!=", "data", "[", "key", ".", "to_s", "]", ".", "to_s", "&&", "val", ".", "to_s", "!=", "data", "[", "key", ".", "to_sym", "]", ".", "to_s", "return", "false", "end", "end", "true", "end" ]
Recursive helper method for like? Allows comparison of nested hash structures
[ "Recursive", "helper", "method", "for", "like?", "Allows", "comparison", "of", "nested", "hash", "structures" ]
c2b12297927e3a5cb18e097d066b0732203bd177
https://github.com/HewlettPackard/oneview-sdk-ruby/blob/c2b12297927e3a5cb18e097d066b0732203bd177/lib/oneview-sdk/resource.rb#L399-L416
train
payu-india/payuindia
lib/payuindia.rb
PayuIndia.Notification.amount_ok?
def amount_ok?( order_amount, order_discount = BigDecimal.new( '0.0' ) ) BigDecimal.new( gross ) == order_amount && BigDecimal.new( discount.to_s ) == order_discount end
ruby
def amount_ok?( order_amount, order_discount = BigDecimal.new( '0.0' ) ) BigDecimal.new( gross ) == order_amount && BigDecimal.new( discount.to_s ) == order_discount end
[ "def", "amount_ok?", "(", "order_amount", ",", "order_discount", "=", "BigDecimal", ".", "new", "(", "'0.0'", ")", ")", "BigDecimal", ".", "new", "(", "gross", ")", "==", "order_amount", "&&", "BigDecimal", ".", "new", "(", "discount", ".", "to_s", ")", "==", "order_discount", "end" ]
Order amount should be equal to gross - discount
[ "Order", "amount", "should", "be", "equal", "to", "gross", "-", "discount" ]
66d887615f893fa073ebc7cefa53adfd24e0f68d
https://github.com/payu-india/payuindia/blob/66d887615f893fa073ebc7cefa53adfd24e0f68d/lib/payuindia.rb#L91-L93
train
payu-india/payuindia
lib/payuindia/action_view_helper.rb
PayuIndia.ActionViewHelper.payment_form_for_payu
def payment_form_for_payu(key, salt, options = {}) if !options.is_a?(Hash) || !key.is_a?(String) || !salt.is_a?(String) concat("Something Wrong! params order -> key (String), salt (String), options (Hash) ") nil else form_options = options.delete(:html) || {} service = PayuIndia::Helper.new(key, salt, options) result = [] result << form_tag(PayuIndia.service_url, form_options.merge(:method => :post)) result << hidden_field_tag('key', key) service.form_fields.each do |field, value| result << hidden_field_tag(field, value) end result << '<input type=submit value=" Pay with PayU ">' result << '</form>' result= result.join("\n") concat(result.respond_to?(:html_safe) ? result.html_safe : result) nil end end
ruby
def payment_form_for_payu(key, salt, options = {}) if !options.is_a?(Hash) || !key.is_a?(String) || !salt.is_a?(String) concat("Something Wrong! params order -> key (String), salt (String), options (Hash) ") nil else form_options = options.delete(:html) || {} service = PayuIndia::Helper.new(key, salt, options) result = [] result << form_tag(PayuIndia.service_url, form_options.merge(:method => :post)) result << hidden_field_tag('key', key) service.form_fields.each do |field, value| result << hidden_field_tag(field, value) end result << '<input type=submit value=" Pay with PayU ">' result << '</form>' result= result.join("\n") concat(result.respond_to?(:html_safe) ? result.html_safe : result) nil end end
[ "def", "payment_form_for_payu", "(", "key", ",", "salt", ",", "options", "=", "{", "}", ")", "if", "!", "options", ".", "is_a?", "(", "Hash", ")", "||", "!", "key", ".", "is_a?", "(", "String", ")", "||", "!", "salt", ".", "is_a?", "(", "String", ")", "concat", "(", "\"Something Wrong! params order -> key (String), salt (String), options (Hash) \"", ")", "nil", "else", "form_options", "=", "options", ".", "delete", "(", ":html", ")", "||", "{", "}", "service", "=", "PayuIndia", "::", "Helper", ".", "new", "(", "key", ",", "salt", ",", "options", ")", "result", "=", "[", "]", "result", "<<", "form_tag", "(", "PayuIndia", ".", "service_url", ",", "form_options", ".", "merge", "(", ":method", "=>", ":post", ")", ")", "result", "<<", "hidden_field_tag", "(", "'key'", ",", "key", ")", "service", ".", "form_fields", ".", "each", "do", "|", "field", ",", "value", "|", "result", "<<", "hidden_field_tag", "(", "field", ",", "value", ")", "end", "result", "<<", "'<input type=submit value=\" Pay with PayU \">'", "result", "<<", "'</form>'", "result", "=", "result", ".", "join", "(", "\"\\n\"", ")", "concat", "(", "result", ".", "respond_to?", "(", ":html_safe", ")", "?", "result", ".", "html_safe", ":", "result", ")", "nil", "end", "end" ]
This Helper creates form with all parameters added. <% payment_form_for_payu 'YOUR_KEY', 'YOUR_SALT', :txnid => @cart.id, :amount => @cart.total_price, :productinfo => 'Book', :firstname => 'abc', :email => '[email protected]', :phone => '1234567890', :surl => 'http://localhost:3000/payu_callback', :furl => 'http://localhost:3000/payu_callback', :html => { :id => 'payment-form' } %>
[ "This", "Helper", "creates", "form", "with", "all", "parameters", "added", "." ]
66d887615f893fa073ebc7cefa53adfd24e0f68d
https://github.com/payu-india/payuindia/blob/66d887615f893fa073ebc7cefa53adfd24e0f68d/lib/payuindia/action_view_helper.rb#L21-L45
train
sprinkle-tool/sprinkle
lib/sprinkle/package/rendering.rb
Sprinkle::Package.Rendering.template
def template(src, context=binding) eruby = Erubis::Eruby.new(src) eruby.result(context) rescue Object => e raise Sprinkle::Errors::TemplateError.new(e, src, context) end
ruby
def template(src, context=binding) eruby = Erubis::Eruby.new(src) eruby.result(context) rescue Object => e raise Sprinkle::Errors::TemplateError.new(e, src, context) end
[ "def", "template", "(", "src", ",", "context", "=", "binding", ")", "eruby", "=", "Erubis", "::", "Eruby", ".", "new", "(", "src", ")", "eruby", ".", "result", "(", "context", ")", "rescue", "Object", "=>", "e", "raise", "Sprinkle", "::", "Errors", "::", "TemplateError", ".", "new", "(", "e", ",", "src", ",", "context", ")", "end" ]
render src as ERB
[ "render", "src", "as", "ERB" ]
883594d2531d99ac6cac3bcbd1749cd57caf5a0c
https://github.com/sprinkle-tool/sprinkle/blob/883594d2531d99ac6cac3bcbd1749cd57caf5a0c/lib/sprinkle/package/rendering.rb#L15-L20
train
sprinkle-tool/sprinkle
lib/sprinkle/package/rendering.rb
Sprinkle::Package.Rendering.render
def render(filename, context=binding) contents=File.read(expand_filename(filename)) template(contents, context) end
ruby
def render(filename, context=binding) contents=File.read(expand_filename(filename)) template(contents, context) end
[ "def", "render", "(", "filename", ",", "context", "=", "binding", ")", "contents", "=", "File", ".", "read", "(", "expand_filename", "(", "filename", ")", ")", "template", "(", "contents", ",", "context", ")", "end" ]
read in filename and render it as ERB
[ "read", "in", "filename", "and", "render", "it", "as", "ERB" ]
883594d2531d99ac6cac3bcbd1749cd57caf5a0c
https://github.com/sprinkle-tool/sprinkle/blob/883594d2531d99ac6cac3bcbd1749cd57caf5a0c/lib/sprinkle/package/rendering.rb#L23-L26
train
timothyf/gameday_api
lib/gameday_api/pitcher.rb
GamedayApi.Pitcher.load_from_id
def load_from_id(gid, pid) @gid = gid @pid = pid @position = 'P' @xml_data = GamedayFetcher.fetch_pitcher(gid, pid) @xml_doc = REXML::Document.new(@xml_data) @team_abbrev = @xml_doc.root.attributes["team"] @first_name = @xml_doc.root.attributes["first_name"] @last_name = @xml_doc.root.attributes["last_name"] @jersey_number = @xml_doc.root.attributes["jersey_number"] @height = @xml_doc.root.attributes["height"] @weight = @xml_doc.root.attributes["weight"] @bats = @xml_doc.root.attributes["bats"] @throws = @xml_doc.root.attributes["throws"] @dob = @xml_doc.root.attributes['dob'] set_opponent_stats end
ruby
def load_from_id(gid, pid) @gid = gid @pid = pid @position = 'P' @xml_data = GamedayFetcher.fetch_pitcher(gid, pid) @xml_doc = REXML::Document.new(@xml_data) @team_abbrev = @xml_doc.root.attributes["team"] @first_name = @xml_doc.root.attributes["first_name"] @last_name = @xml_doc.root.attributes["last_name"] @jersey_number = @xml_doc.root.attributes["jersey_number"] @height = @xml_doc.root.attributes["height"] @weight = @xml_doc.root.attributes["weight"] @bats = @xml_doc.root.attributes["bats"] @throws = @xml_doc.root.attributes["throws"] @dob = @xml_doc.root.attributes['dob'] set_opponent_stats end
[ "def", "load_from_id", "(", "gid", ",", "pid", ")", "@gid", "=", "gid", "@pid", "=", "pid", "@position", "=", "'P'", "@xml_data", "=", "GamedayFetcher", ".", "fetch_pitcher", "(", "gid", ",", "pid", ")", "@xml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "@xml_data", ")", "@team_abbrev", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"team\"", "]", "@first_name", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"first_name\"", "]", "@last_name", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"last_name\"", "]", "@jersey_number", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"jersey_number\"", "]", "@height", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"height\"", "]", "@weight", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"weight\"", "]", "@bats", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"bats\"", "]", "@throws", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"throws\"", "]", "@dob", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "'dob'", "]", "set_opponent_stats", "end" ]
Loads a Pitcher object given a game id and a player id
[ "Loads", "a", "Pitcher", "object", "given", "a", "game", "id", "and", "a", "player", "id" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/pitcher.rb#L18-L34
train
timothyf/gameday_api
lib/gameday_api/pitcher.rb
GamedayApi.Pitcher.get_all_starts
def get_all_starts(year) results = [] app = get_all_appearances(year) if app.start == true results << app end end
ruby
def get_all_starts(year) results = [] app = get_all_appearances(year) if app.start == true results << app end end
[ "def", "get_all_starts", "(", "year", ")", "results", "=", "[", "]", "app", "=", "get_all_appearances", "(", "year", ")", "if", "app", ".", "start", "==", "true", "results", "<<", "app", "end", "end" ]
Returns an array of PitchingAppearance objects for all of the pitchers starts
[ "Returns", "an", "array", "of", "PitchingAppearance", "objects", "for", "all", "of", "the", "pitchers", "starts" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/pitcher.rb#L38-L44
train
timothyf/gameday_api
lib/gameday_api/pitcher.rb
GamedayApi.Pitcher.get_vs_ab
def get_vs_ab results = [] abs = get_game.get_atbats abs.each do |ab| if ab.pitcher_id == @pid results << ab end end results end
ruby
def get_vs_ab results = [] abs = get_game.get_atbats abs.each do |ab| if ab.pitcher_id == @pid results << ab end end results end
[ "def", "get_vs_ab", "results", "=", "[", "]", "abs", "=", "get_game", ".", "get_atbats", "abs", ".", "each", "do", "|", "ab", "|", "if", "ab", ".", "pitcher_id", "==", "@pid", "results", "<<", "ab", "end", "end", "results", "end" ]
Returns an array of the atbats against this pitcher during this game
[ "Returns", "an", "array", "of", "the", "atbats", "against", "this", "pitcher", "during", "this", "game" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/pitcher.rb#L48-L57
train
timothyf/gameday_api
lib/gameday_api/pitcher.rb
GamedayApi.Pitcher.get_pitches
def get_pitches results = [] ab = get_vs_ab ab.each do |ab| results << ab.pitches end results.flatten end
ruby
def get_pitches results = [] ab = get_vs_ab ab.each do |ab| results << ab.pitches end results.flatten end
[ "def", "get_pitches", "results", "=", "[", "]", "ab", "=", "get_vs_ab", "ab", ".", "each", "do", "|", "ab", "|", "results", "<<", "ab", ".", "pitches", "end", "results", ".", "flatten", "end" ]
Returns an array of pitches thrown by this pitcher during this game
[ "Returns", "an", "array", "of", "pitches", "thrown", "by", "this", "pitcher", "during", "this", "game" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/pitcher.rb#L61-L68
train
timothyf/gameday_api
lib/gameday_api/box_score.rb
GamedayApi.BoxScore.load_from_id
def load_from_id(gid) @gid = gid @xml_data = GamedayFetcher.fetch_boxscore(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root @game = Game.new(@gid) @game.boxscore = self set_basic_info @linescore = LineScore.new @linescore.init(@xml_doc.root.elements["linescore"]) @home_runs = @linescore.home_team_runs @away_runs = @linescore.away_team_runs @game_info = @xml_doc.root.elements["game_info"].text set_batting_text set_cities set_pitchers set_batters set_weather end end
ruby
def load_from_id(gid) @gid = gid @xml_data = GamedayFetcher.fetch_boxscore(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root @game = Game.new(@gid) @game.boxscore = self set_basic_info @linescore = LineScore.new @linescore.init(@xml_doc.root.elements["linescore"]) @home_runs = @linescore.home_team_runs @away_runs = @linescore.away_team_runs @game_info = @xml_doc.root.elements["game_info"].text set_batting_text set_cities set_pitchers set_batters set_weather end end
[ "def", "load_from_id", "(", "gid", ")", "@gid", "=", "gid", "@xml_data", "=", "GamedayFetcher", ".", "fetch_boxscore", "(", "gid", ")", "@xml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "@xml_data", ")", "if", "@xml_doc", ".", "root", "@game", "=", "Game", ".", "new", "(", "@gid", ")", "@game", ".", "boxscore", "=", "self", "set_basic_info", "@linescore", "=", "LineScore", ".", "new", "@linescore", ".", "init", "(", "@xml_doc", ".", "root", ".", "elements", "[", "\"linescore\"", "]", ")", "@home_runs", "=", "@linescore", ".", "home_team_runs", "@away_runs", "=", "@linescore", ".", "away_team_runs", "@game_info", "=", "@xml_doc", ".", "root", ".", "elements", "[", "\"game_info\"", "]", ".", "text", "set_batting_text", "set_cities", "set_pitchers", "set_batters", "set_weather", "end", "end" ]
Loads the boxscore XML from the MLB gameday server and parses it using REXML
[ "Loads", "the", "boxscore", "XML", "from", "the", "MLB", "gameday", "server", "and", "parses", "it", "using", "REXML" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/box_score.rb#L32-L51
train
timothyf/gameday_api
lib/gameday_api/box_score.rb
GamedayApi.BoxScore.to_html
def to_html(template_filename) gameday_info = GamedayUtil.parse_gameday_id('gid_' + gid) template = ERB.new File.new(File.expand_path(File.dirname(__FILE__) + "/" + template_filename)).read, nil, "%" return template.result(binding) end
ruby
def to_html(template_filename) gameday_info = GamedayUtil.parse_gameday_id('gid_' + gid) template = ERB.new File.new(File.expand_path(File.dirname(__FILE__) + "/" + template_filename)).read, nil, "%" return template.result(binding) end
[ "def", "to_html", "(", "template_filename", ")", "gameday_info", "=", "GamedayUtil", ".", "parse_gameday_id", "(", "'gid_'", "+", "gid", ")", "template", "=", "ERB", ".", "new", "File", ".", "new", "(", "File", ".", "expand_path", "(", "File", ".", "dirname", "(", "__FILE__", ")", "+", "\"/\"", "+", "template_filename", ")", ")", ".", "read", ",", "nil", ",", "\"%\"", "return", "template", ".", "result", "(", "binding", ")", "end" ]
Converts the boxscore into a formatted HTML representation. Relies on the boxscore.html.erb template for describing the layout
[ "Converts", "the", "boxscore", "into", "a", "formatted", "HTML", "representation", ".", "Relies", "on", "the", "boxscore", ".", "html", ".", "erb", "template", "for", "describing", "the", "layout" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/box_score.rb#L62-L66
train
timothyf/gameday_api
lib/gameday_api/box_score.rb
GamedayApi.BoxScore.set_basic_info
def set_basic_info @game_id = @xml_doc.root.attributes["game_id"] @game_pk = @xml_doc.root.attributes["game_pk"] @home_sport_code = @xml_doc.root.attributes["home_sport_code"] @away_team_code = @xml_doc.root.attributes["away_team_code"] @home_team_code = @xml_doc.root.attributes["home_team_code"] @away_id = @xml_doc.root.attributes["away_id"] @home_id = @xml_doc.root.attributes["home_id"] @away_fname = @xml_doc.root.attributes["away_fname"] @home_fname = @xml_doc.root.attributes["home_fname"] @away_sname = @xml_doc.root.attributes["away_sname"] @home_sname = @xml_doc.root.attributes["home_sname"] @date = @xml_doc.root.attributes["date"] @away_wins = @xml_doc.root.attributes["away_wins"] @away_loss = @xml_doc.root.attributes["away_loss"] @home_wins = @xml_doc.root.attributes["home_wins"] @home_loss = @xml_doc.root.attributes["home_loss"] @status_ind = @xml_doc.root.attributes["status_ind"] end
ruby
def set_basic_info @game_id = @xml_doc.root.attributes["game_id"] @game_pk = @xml_doc.root.attributes["game_pk"] @home_sport_code = @xml_doc.root.attributes["home_sport_code"] @away_team_code = @xml_doc.root.attributes["away_team_code"] @home_team_code = @xml_doc.root.attributes["home_team_code"] @away_id = @xml_doc.root.attributes["away_id"] @home_id = @xml_doc.root.attributes["home_id"] @away_fname = @xml_doc.root.attributes["away_fname"] @home_fname = @xml_doc.root.attributes["home_fname"] @away_sname = @xml_doc.root.attributes["away_sname"] @home_sname = @xml_doc.root.attributes["home_sname"] @date = @xml_doc.root.attributes["date"] @away_wins = @xml_doc.root.attributes["away_wins"] @away_loss = @xml_doc.root.attributes["away_loss"] @home_wins = @xml_doc.root.attributes["home_wins"] @home_loss = @xml_doc.root.attributes["home_loss"] @status_ind = @xml_doc.root.attributes["status_ind"] end
[ "def", "set_basic_info", "@game_id", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"game_id\"", "]", "@game_pk", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"game_pk\"", "]", "@home_sport_code", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_sport_code\"", "]", "@away_team_code", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_team_code\"", "]", "@home_team_code", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_team_code\"", "]", "@away_id", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_id\"", "]", "@home_id", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_id\"", "]", "@away_fname", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_fname\"", "]", "@home_fname", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_fname\"", "]", "@away_sname", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_sname\"", "]", "@home_sname", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_sname\"", "]", "@date", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"date\"", "]", "@away_wins", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_wins\"", "]", "@away_loss", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_loss\"", "]", "@home_wins", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_wins\"", "]", "@home_loss", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_loss\"", "]", "@status_ind", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"status_ind\"", "]", "end" ]
Retrieves basic game data from the XML root element and sets in object
[ "Retrieves", "basic", "game", "data", "from", "the", "XML", "root", "element", "and", "sets", "in", "object" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/box_score.rb#L102-L120
train
timothyf/gameday_api
lib/gameday_api/box_score.rb
GamedayApi.BoxScore.set_pitchers
def set_pitchers @pitchers, away_pitchers, home_pitchers = [], [], [] count = 1 @xml_doc.elements.each("boxscore/pitching[@team_flag='away']/pitcher") { |element| pitcher = PitchingAppearance.new pitcher.init(@gid, element, count) count += 1 away_pitchers.push pitcher } count = 1 @xml_doc.elements.each("boxscore/pitching[@team_flag='home']/pitcher") { |element| pitcher = PitchingAppearance.new pitcher.init(@gid, element, count) count += 1 home_pitchers.push pitcher } @pitchers << away_pitchers @pitchers << home_pitchers end
ruby
def set_pitchers @pitchers, away_pitchers, home_pitchers = [], [], [] count = 1 @xml_doc.elements.each("boxscore/pitching[@team_flag='away']/pitcher") { |element| pitcher = PitchingAppearance.new pitcher.init(@gid, element, count) count += 1 away_pitchers.push pitcher } count = 1 @xml_doc.elements.each("boxscore/pitching[@team_flag='home']/pitcher") { |element| pitcher = PitchingAppearance.new pitcher.init(@gid, element, count) count += 1 home_pitchers.push pitcher } @pitchers << away_pitchers @pitchers << home_pitchers end
[ "def", "set_pitchers", "@pitchers", ",", "away_pitchers", ",", "home_pitchers", "=", "[", "]", ",", "[", "]", ",", "[", "]", "count", "=", "1", "@xml_doc", ".", "elements", ".", "each", "(", "\"boxscore/pitching[@team_flag='away']/pitcher\"", ")", "{", "|", "element", "|", "pitcher", "=", "PitchingAppearance", ".", "new", "pitcher", ".", "init", "(", "@gid", ",", "element", ",", "count", ")", "count", "+=", "1", "away_pitchers", ".", "push", "pitcher", "}", "count", "=", "1", "@xml_doc", ".", "elements", ".", "each", "(", "\"boxscore/pitching[@team_flag='home']/pitcher\"", ")", "{", "|", "element", "|", "pitcher", "=", "PitchingAppearance", ".", "new", "pitcher", ".", "init", "(", "@gid", ",", "element", ",", "count", ")", "count", "+=", "1", "home_pitchers", ".", "push", "pitcher", "}", "@pitchers", "<<", "away_pitchers", "@pitchers", "<<", "home_pitchers", "end" ]
Sets an array of hashes where each hash holds data for a pitcher whom appeared in the game. Specify either home or away team pitchers.
[ "Sets", "an", "array", "of", "hashes", "where", "each", "hash", "holds", "data", "for", "a", "pitcher", "whom", "appeared", "in", "the", "game", ".", "Specify", "either", "home", "or", "away", "team", "pitchers", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/box_score.rb#L150-L168
train
timothyf/gameday_api
lib/gameday_api/box_score.rb
GamedayApi.BoxScore.set_batters
def set_batters @batters, away_batters, home_batters = [], [], [] @xml_doc.elements.each("boxscore/batting[@team_flag='away']/batter") { |element| batter = BattingAppearance.new batter.init(element) away_batters.push batter } @xml_doc.elements.each("boxscore/batting[@team_flag='home']/batter") { |element| batter = BattingAppearance.new batter.init(element) home_batters.push batter } @batters << away_batters @batters << home_batters end
ruby
def set_batters @batters, away_batters, home_batters = [], [], [] @xml_doc.elements.each("boxscore/batting[@team_flag='away']/batter") { |element| batter = BattingAppearance.new batter.init(element) away_batters.push batter } @xml_doc.elements.each("boxscore/batting[@team_flag='home']/batter") { |element| batter = BattingAppearance.new batter.init(element) home_batters.push batter } @batters << away_batters @batters << home_batters end
[ "def", "set_batters", "@batters", ",", "away_batters", ",", "home_batters", "=", "[", "]", ",", "[", "]", ",", "[", "]", "@xml_doc", ".", "elements", ".", "each", "(", "\"boxscore/batting[@team_flag='away']/batter\"", ")", "{", "|", "element", "|", "batter", "=", "BattingAppearance", ".", "new", "batter", ".", "init", "(", "element", ")", "away_batters", ".", "push", "batter", "}", "@xml_doc", ".", "elements", ".", "each", "(", "\"boxscore/batting[@team_flag='home']/batter\"", ")", "{", "|", "element", "|", "batter", "=", "BattingAppearance", ".", "new", "batter", ".", "init", "(", "element", ")", "home_batters", ".", "push", "batter", "}", "@batters", "<<", "away_batters", "@batters", "<<", "home_batters", "end" ]
Sets an array of hashes where each hash holds data for a batter whom appeared in the game. Specify either home or away team batters.
[ "Sets", "an", "array", "of", "hashes", "where", "each", "hash", "holds", "data", "for", "a", "batter", "whom", "appeared", "in", "the", "game", ".", "Specify", "either", "home", "or", "away", "team", "batters", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/box_score.rb#L173-L187
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.all_games
def all_games(year) if !@games puts 'Finding all games for team...' results = [] (START_MONTH..END_MONTH).each do |month| puts "Month: " + month.to_s month_s = GamedayUtil.convert_digit_to_string(month) (1..31).each do |date| if !GamedayUtil.is_date_valid(month, date) next end date_s = GamedayUtil.convert_digit_to_string(date) games = games_for_date(year, month_s, date_s) if games # make sure game was not postponed good_games = games.select { |g| g.get_boxscore.status_ind != 'P' } good_games.each do |game| results << game end end end end @games = results end @games end
ruby
def all_games(year) if !@games puts 'Finding all games for team...' results = [] (START_MONTH..END_MONTH).each do |month| puts "Month: " + month.to_s month_s = GamedayUtil.convert_digit_to_string(month) (1..31).each do |date| if !GamedayUtil.is_date_valid(month, date) next end date_s = GamedayUtil.convert_digit_to_string(date) games = games_for_date(year, month_s, date_s) if games # make sure game was not postponed good_games = games.select { |g| g.get_boxscore.status_ind != 'P' } good_games.each do |game| results << game end end end end @games = results end @games end
[ "def", "all_games", "(", "year", ")", "if", "!", "@games", "puts", "'Finding all games for team...'", "results", "=", "[", "]", "(", "START_MONTH", "..", "END_MONTH", ")", ".", "each", "do", "|", "month", "|", "puts", "\"Month: \"", "+", "month", ".", "to_s", "month_s", "=", "GamedayUtil", ".", "convert_digit_to_string", "(", "month", ")", "(", "1", "..", "31", ")", ".", "each", "do", "|", "date", "|", "if", "!", "GamedayUtil", ".", "is_date_valid", "(", "month", ",", "date", ")", "next", "end", "date_s", "=", "GamedayUtil", ".", "convert_digit_to_string", "(", "date", ")", "games", "=", "games_for_date", "(", "year", ",", "month_s", ",", "date_s", ")", "if", "games", "good_games", "=", "games", ".", "select", "{", "|", "g", "|", "g", ".", "get_boxscore", ".", "status_ind", "!=", "'P'", "}", "good_games", ".", "each", "do", "|", "game", "|", "results", "<<", "game", "end", "end", "end", "end", "@games", "=", "results", "end", "@games", "end" ]
Returns an array of all games for this team for the specified season
[ "Returns", "an", "array", "of", "all", "games", "for", "this", "team", "for", "the", "specified", "season" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L93-L118
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.all_home_games
def all_home_games(year) games = all_games(year) results = games.select {|g| g.home_team_abbrev == @abrev } end
ruby
def all_home_games(year) games = all_games(year) results = games.select {|g| g.home_team_abbrev == @abrev } end
[ "def", "all_home_games", "(", "year", ")", "games", "=", "all_games", "(", "year", ")", "results", "=", "games", ".", "select", "{", "|", "g", "|", "g", ".", "home_team_abbrev", "==", "@abrev", "}", "end" ]
Returns an array of all home games for this team for the specified season
[ "Returns", "an", "array", "of", "all", "home", "games", "for", "this", "team", "for", "the", "specified", "season" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L122-L125
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.all_away_games
def all_away_games(year) games = all_games(year) results = games.select {|g| g.visit_team_abbrev == @abrev } end
ruby
def all_away_games(year) games = all_games(year) results = games.select {|g| g.visit_team_abbrev == @abrev } end
[ "def", "all_away_games", "(", "year", ")", "games", "=", "all_games", "(", "year", ")", "results", "=", "games", ".", "select", "{", "|", "g", "|", "g", ".", "visit_team_abbrev", "==", "@abrev", "}", "end" ]
Returns an array of all away games for this team for the specified season
[ "Returns", "an", "array", "of", "all", "away", "games", "for", "this", "team", "for", "the", "specified", "season" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L129-L132
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.games_for_date
def games_for_date(year, month, day) games_page = GamedayFetcher.fetch_games_page(year, month, day) gids = find_gid_for_date(year, month, day, games_page) if gids results = gids.collect {|gid| Game.new(gid) } else results = nil end results end
ruby
def games_for_date(year, month, day) games_page = GamedayFetcher.fetch_games_page(year, month, day) gids = find_gid_for_date(year, month, day, games_page) if gids results = gids.collect {|gid| Game.new(gid) } else results = nil end results end
[ "def", "games_for_date", "(", "year", ",", "month", ",", "day", ")", "games_page", "=", "GamedayFetcher", ".", "fetch_games_page", "(", "year", ",", "month", ",", "day", ")", "gids", "=", "find_gid_for_date", "(", "year", ",", "month", ",", "day", ",", "games_page", ")", "if", "gids", "results", "=", "gids", ".", "collect", "{", "|", "gid", "|", "Game", ".", "new", "(", "gid", ")", "}", "else", "results", "=", "nil", "end", "results", "end" ]
Returns an array of the team's game objects for the date passed in.
[ "Returns", "an", "array", "of", "the", "team", "s", "game", "objects", "for", "the", "date", "passed", "in", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L136-L145
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.get_leadoff_hitters_by_year
def get_leadoff_hitters_by_year(year) results = [] games = all_games(year) games.each do |game| boxscore = game.get_boxscore leadoffs = boxscore.get_leadoff_hitters if game.home_team_abbrev == @abrev results << leadoffs[1] else results << leadoffs[0] end end results end
ruby
def get_leadoff_hitters_by_year(year) results = [] games = all_games(year) games.each do |game| boxscore = game.get_boxscore leadoffs = boxscore.get_leadoff_hitters if game.home_team_abbrev == @abrev results << leadoffs[1] else results << leadoffs[0] end end results end
[ "def", "get_leadoff_hitters_by_year", "(", "year", ")", "results", "=", "[", "]", "games", "=", "all_games", "(", "year", ")", "games", ".", "each", "do", "|", "game", "|", "boxscore", "=", "game", ".", "get_boxscore", "leadoffs", "=", "boxscore", ".", "get_leadoff_hitters", "if", "game", ".", "home_team_abbrev", "==", "@abrev", "results", "<<", "leadoffs", "[", "1", "]", "else", "results", "<<", "leadoffs", "[", "0", "]", "end", "end", "results", "end" ]
Returns an array of BattingAppearance containing the leadoff hitters for each game of the specified season.
[ "Returns", "an", "array", "of", "BattingAppearance", "containing", "the", "leadoff", "hitters", "for", "each", "game", "of", "the", "specified", "season", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L149-L162
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.get_leadoff_hitters_unique
def get_leadoff_hitters_unique(year) hitters = get_leadoff_hitters_by_year(year) h = {} hitters.each {|hitter| h[hitter.batter_name]=hitter} h.values end
ruby
def get_leadoff_hitters_unique(year) hitters = get_leadoff_hitters_by_year(year) h = {} hitters.each {|hitter| h[hitter.batter_name]=hitter} h.values end
[ "def", "get_leadoff_hitters_unique", "(", "year", ")", "hitters", "=", "get_leadoff_hitters_by_year", "(", "year", ")", "h", "=", "{", "}", "hitters", ".", "each", "{", "|", "hitter", "|", "h", "[", "hitter", ".", "batter_name", "]", "=", "hitter", "}", "h", ".", "values", "end" ]
Returns an array of BattingAppearance of all hitters who have led off at least one game during the specified season
[ "Returns", "an", "array", "of", "BattingAppearance", "of", "all", "hitters", "who", "have", "led", "off", "at", "least", "one", "game", "during", "the", "specified", "season" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L166-L171
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.get_cleanup_hitters_by_year
def get_cleanup_hitters_by_year(year) results = [] games = all_games(year) games.each do |game| boxscore = game.get_boxscore hitters = boxscore.get_cleanup_hitters if game.home_team_abbrev == @abrev results << hitters[1] else results << hitters[0] end end results end
ruby
def get_cleanup_hitters_by_year(year) results = [] games = all_games(year) games.each do |game| boxscore = game.get_boxscore hitters = boxscore.get_cleanup_hitters if game.home_team_abbrev == @abrev results << hitters[1] else results << hitters[0] end end results end
[ "def", "get_cleanup_hitters_by_year", "(", "year", ")", "results", "=", "[", "]", "games", "=", "all_games", "(", "year", ")", "games", ".", "each", "do", "|", "game", "|", "boxscore", "=", "game", ".", "get_boxscore", "hitters", "=", "boxscore", ".", "get_cleanup_hitters", "if", "game", ".", "home_team_abbrev", "==", "@abrev", "results", "<<", "hitters", "[", "1", "]", "else", "results", "<<", "hitters", "[", "0", "]", "end", "end", "results", "end" ]
Returns an array containing the cleanup hitters for each game of the specified season. The cleanup hitter is the 4th hitter in the batting order
[ "Returns", "an", "array", "containing", "the", "cleanup", "hitters", "for", "each", "game", "of", "the", "specified", "season", ".", "The", "cleanup", "hitter", "is", "the", "4th", "hitter", "in", "the", "batting", "order" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L176-L189
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.get_starters_unique
def get_starters_unique(year) pitchers = get_start_pitcher_appearances_by_year(year) h = {} pitchers.each {|pitcher| h[pitcher.pitcher_name]=pitcher} h.values end
ruby
def get_starters_unique(year) pitchers = get_start_pitcher_appearances_by_year(year) h = {} pitchers.each {|pitcher| h[pitcher.pitcher_name]=pitcher} h.values end
[ "def", "get_starters_unique", "(", "year", ")", "pitchers", "=", "get_start_pitcher_appearances_by_year", "(", "year", ")", "h", "=", "{", "}", "pitchers", ".", "each", "{", "|", "pitcher", "|", "h", "[", "pitcher", ".", "pitcher_name", "]", "=", "pitcher", "}", "h", ".", "values", "end" ]
Returns an array of all pitchers who have started at least one game during the specified season
[ "Returns", "an", "array", "of", "all", "pitchers", "who", "have", "started", "at", "least", "one", "game", "during", "the", "specified", "season" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L217-L222
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.get_closers_unique
def get_closers_unique(year) pitchers = get_close_pitcher_appearances_by_year(year) h = {} pitchers.each {|pitcher| h[pitcher.pitcher_name]=pitcher} h.values end
ruby
def get_closers_unique(year) pitchers = get_close_pitcher_appearances_by_year(year) h = {} pitchers.each {|pitcher| h[pitcher.pitcher_name]=pitcher} h.values end
[ "def", "get_closers_unique", "(", "year", ")", "pitchers", "=", "get_close_pitcher_appearances_by_year", "(", "year", ")", "h", "=", "{", "}", "pitchers", ".", "each", "{", "|", "pitcher", "|", "h", "[", "pitcher", ".", "pitcher_name", "]", "=", "pitcher", "}", "h", ".", "values", "end" ]
Returns an array of all pitchers who have closed at least one game during the specified season
[ "Returns", "an", "array", "of", "all", "pitchers", "who", "have", "closed", "at", "least", "one", "game", "during", "the", "specified", "season" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L241-L246
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.quality_starts_count
def quality_starts_count(year) count = 0 games = all_games(year) games.each do |game| starters = game.get_starting_pitchers if game.home_team_abbrev == @abrev if starters[1].quality_start? count = count + 1 end else if starters[0].quality_start? count = count + 1 end end end count end
ruby
def quality_starts_count(year) count = 0 games = all_games(year) games.each do |game| starters = game.get_starting_pitchers if game.home_team_abbrev == @abrev if starters[1].quality_start? count = count + 1 end else if starters[0].quality_start? count = count + 1 end end end count end
[ "def", "quality_starts_count", "(", "year", ")", "count", "=", "0", "games", "=", "all_games", "(", "year", ")", "games", ".", "each", "do", "|", "game", "|", "starters", "=", "game", ".", "get_starting_pitchers", "if", "game", ".", "home_team_abbrev", "==", "@abrev", "if", "starters", "[", "1", "]", ".", "quality_start?", "count", "=", "count", "+", "1", "end", "else", "if", "starters", "[", "0", "]", ".", "quality_start?", "count", "=", "count", "+", "1", "end", "end", "end", "count", "end" ]
Returns a count of the number of quality starts for this team for the specified year.
[ "Returns", "a", "count", "of", "the", "number", "of", "quality", "starts", "for", "this", "team", "for", "the", "specified", "year", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L250-L266
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.get_opening_day_game
def get_opening_day_game(year) schedule = Schedule.new(year) oday = schedule.get_opening_day oday_array = GamedayUtil.parse_date_string(oday) games = games_for_date(oday_array[0], oday_array[1], oday_array[2]) if games[0] == nil games = games_for_date(oday_array[0], oday_array[1], GamedayUtil.convert_digit_to_string(oday_array[2].to_i + 1)) end return games[0] end
ruby
def get_opening_day_game(year) schedule = Schedule.new(year) oday = schedule.get_opening_day oday_array = GamedayUtil.parse_date_string(oday) games = games_for_date(oday_array[0], oday_array[1], oday_array[2]) if games[0] == nil games = games_for_date(oday_array[0], oday_array[1], GamedayUtil.convert_digit_to_string(oday_array[2].to_i + 1)) end return games[0] end
[ "def", "get_opening_day_game", "(", "year", ")", "schedule", "=", "Schedule", ".", "new", "(", "year", ")", "oday", "=", "schedule", ".", "get_opening_day", "oday_array", "=", "GamedayUtil", ".", "parse_date_string", "(", "oday", ")", "games", "=", "games_for_date", "(", "oday_array", "[", "0", "]", ",", "oday_array", "[", "1", "]", ",", "oday_array", "[", "2", "]", ")", "if", "games", "[", "0", "]", "==", "nil", "games", "=", "games_for_date", "(", "oday_array", "[", "0", "]", ",", "oday_array", "[", "1", "]", ",", "GamedayUtil", ".", "convert_digit_to_string", "(", "oday_array", "[", "2", "]", ".", "to_i", "+", "1", ")", ")", "end", "return", "games", "[", "0", "]", "end" ]
Returns a game object representing the opening day game for this team for the season passed in.
[ "Returns", "a", "game", "object", "representing", "the", "opening", "day", "game", "for", "this", "team", "for", "the", "season", "passed", "in", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L283-L294
train
timothyf/gameday_api
lib/gameday_api/team.rb
GamedayApi.Team.opening_day_roster
def opening_day_roster(year) game = get_opening_day_game(year) rosters = game.get_rosters rosters[0].team_name == city + ' ' + name ? rosters[0] : rosters[1] end
ruby
def opening_day_roster(year) game = get_opening_day_game(year) rosters = game.get_rosters rosters[0].team_name == city + ' ' + name ? rosters[0] : rosters[1] end
[ "def", "opening_day_roster", "(", "year", ")", "game", "=", "get_opening_day_game", "(", "year", ")", "rosters", "=", "game", ".", "get_rosters", "rosters", "[", "0", "]", ".", "team_name", "==", "city", "+", "' '", "+", "name", "?", "rosters", "[", "0", "]", ":", "rosters", "[", "1", "]", "end" ]
Returns a Roster object representing the opening day roster for this team for the specified year.
[ "Returns", "a", "Roster", "object", "representing", "the", "opening", "day", "roster", "for", "this", "team", "for", "the", "specified", "year", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/team.rb#L299-L303
train
timothyf/gameday_api
lib/gameday_api/gameday.rb
GamedayApi.Gameday.get_all_gids_for_date
def get_all_gids_for_date(year, month, day) begin gids = [] url = GamedayUtil.build_day_url(year, month, date) connection = GamedayUtil.get_connection(url) if connection @hp = Hpricot(connection) a = @hp.at('ul') (a/"a").each do |link| if link.inner_html.include?('gid') str = link.inner_html gids.push str[5..str.length-2] end end end connection.close return gids rescue puts "No games data found for #{year}, #{month}, #{day}." end end
ruby
def get_all_gids_for_date(year, month, day) begin gids = [] url = GamedayUtil.build_day_url(year, month, date) connection = GamedayUtil.get_connection(url) if connection @hp = Hpricot(connection) a = @hp.at('ul') (a/"a").each do |link| if link.inner_html.include?('gid') str = link.inner_html gids.push str[5..str.length-2] end end end connection.close return gids rescue puts "No games data found for #{year}, #{month}, #{day}." end end
[ "def", "get_all_gids_for_date", "(", "year", ",", "month", ",", "day", ")", "begin", "gids", "=", "[", "]", "url", "=", "GamedayUtil", ".", "build_day_url", "(", "year", ",", "month", ",", "date", ")", "connection", "=", "GamedayUtil", ".", "get_connection", "(", "url", ")", "if", "connection", "@hp", "=", "Hpricot", "(", "connection", ")", "a", "=", "@hp", ".", "at", "(", "'ul'", ")", "(", "a", "/", "\"a\"", ")", ".", "each", "do", "|", "link", "|", "if", "link", ".", "inner_html", ".", "include?", "(", "'gid'", ")", "str", "=", "link", ".", "inner_html", "gids", ".", "push", "str", "[", "5", "..", "str", ".", "length", "-", "2", "]", "end", "end", "end", "connection", ".", "close", "return", "gids", "rescue", "puts", "\"No games data found for #{year}, #{month}, #{day}.\"", "end", "end" ]
Returns an array of game id's for the given date
[ "Returns", "an", "array", "of", "game", "id", "s", "for", "the", "given", "date" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/gameday.rb#L22-L42
train
timothyf/gameday_api
lib/gameday_api/player.rb
GamedayApi.Player.load_from_id
def load_from_id(gid, pid) @gid = gid @pid = pid # fetch players.xml file @xml_data = GamedayFetcher.fetch_players(gid) @xml_doc = REXML::Document.new(@xml_data) # find specific player in the file pelement = @xml_doc.root.elements["team/player[@id=#{pid}]"] init(pelement, gid) end
ruby
def load_from_id(gid, pid) @gid = gid @pid = pid # fetch players.xml file @xml_data = GamedayFetcher.fetch_players(gid) @xml_doc = REXML::Document.new(@xml_data) # find specific player in the file pelement = @xml_doc.root.elements["team/player[@id=#{pid}]"] init(pelement, gid) end
[ "def", "load_from_id", "(", "gid", ",", "pid", ")", "@gid", "=", "gid", "@pid", "=", "pid", "@xml_data", "=", "GamedayFetcher", ".", "fetch_players", "(", "gid", ")", "@xml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "@xml_data", ")", "pelement", "=", "@xml_doc", ".", "root", ".", "elements", "[", "\"team/player[@id=#{pid}]\"", "]", "init", "(", "pelement", ",", "gid", ")", "end" ]
Initializes a Player object by reading the player data from the players.xml file for the player specified by game id and player id.
[ "Initializes", "a", "Player", "object", "by", "reading", "the", "player", "data", "from", "the", "players", ".", "xml", "file", "for", "the", "player", "specified", "by", "game", "id", "and", "player", "id", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/player.rb#L20-L29
train
timothyf/gameday_api
lib/gameday_api/player.rb
GamedayApi.Player.init_pitcher_from_scoreboard
def init_pitcher_from_scoreboard(element) @first = element.attributes['first'] @last = element.attributes['last'] @wins = element.attributes['wins'] @losses = element.attributes['losses'] @era = element.attributes['era'] end
ruby
def init_pitcher_from_scoreboard(element) @first = element.attributes['first'] @last = element.attributes['last'] @wins = element.attributes['wins'] @losses = element.attributes['losses'] @era = element.attributes['era'] end
[ "def", "init_pitcher_from_scoreboard", "(", "element", ")", "@first", "=", "element", ".", "attributes", "[", "'first'", "]", "@last", "=", "element", ".", "attributes", "[", "'last'", "]", "@wins", "=", "element", ".", "attributes", "[", "'wins'", "]", "@losses", "=", "element", ".", "attributes", "[", "'losses'", "]", "@era", "=", "element", ".", "attributes", "[", "'era'", "]", "end" ]
Initializes pitcher info from data read from the masterscoreboard.xml file
[ "Initializes", "pitcher", "info", "from", "data", "read", "from", "the", "masterscoreboard", ".", "xml", "file" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/player.rb#L33-L39
train
timothyf/gameday_api
lib/gameday_api/player.rb
GamedayApi.Player.at_bats_count
def at_bats_count gameday_info = GamedayUtil.parse_gameday_id(@gid) appearances = get_all_appearances(gameday_info["year"]) count = appearances.inject(0) {|sum, a| sum + a.ab.to_i } end
ruby
def at_bats_count gameday_info = GamedayUtil.parse_gameday_id(@gid) appearances = get_all_appearances(gameday_info["year"]) count = appearances.inject(0) {|sum, a| sum + a.ab.to_i } end
[ "def", "at_bats_count", "gameday_info", "=", "GamedayUtil", ".", "parse_gameday_id", "(", "@gid", ")", "appearances", "=", "get_all_appearances", "(", "gameday_info", "[", "\"year\"", "]", ")", "count", "=", "appearances", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "a", "|", "sum", "+", "a", ".", "ab", ".", "to_i", "}", "end" ]
Returns the number of at bats over the entire season for this player
[ "Returns", "the", "number", "of", "at", "bats", "over", "the", "entire", "season", "for", "this", "player" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/player.rb#L69-L73
train
timothyf/gameday_api
lib/gameday_api/player.rb
GamedayApi.Player.init
def init(element, gid) @gid = gid @pid = element.attributes['id'] @first = element.attributes['first'] @last = element.attributes['last'] @num= element.attributes['num'] @boxname = element.attributes['boxname'] @rl, = element.attributes['rl'] @position = element.attributes['position'] @status = element.attributes['status'] @bat_order = element.attributes['bat_order'] @game_position = element.attributes['game_position'] @avg = element.attributes['avg'] @hr = element.attributes['hr'] @rbi = element.attributes['rbi'] @wins = element.attributes['wins'] @losses = element.attributes['losses'] @era = element.attributes['era'] set_extra_info end
ruby
def init(element, gid) @gid = gid @pid = element.attributes['id'] @first = element.attributes['first'] @last = element.attributes['last'] @num= element.attributes['num'] @boxname = element.attributes['boxname'] @rl, = element.attributes['rl'] @position = element.attributes['position'] @status = element.attributes['status'] @bat_order = element.attributes['bat_order'] @game_position = element.attributes['game_position'] @avg = element.attributes['avg'] @hr = element.attributes['hr'] @rbi = element.attributes['rbi'] @wins = element.attributes['wins'] @losses = element.attributes['losses'] @era = element.attributes['era'] set_extra_info end
[ "def", "init", "(", "element", ",", "gid", ")", "@gid", "=", "gid", "@pid", "=", "element", ".", "attributes", "[", "'id'", "]", "@first", "=", "element", ".", "attributes", "[", "'first'", "]", "@last", "=", "element", ".", "attributes", "[", "'last'", "]", "@num", "=", "element", ".", "attributes", "[", "'num'", "]", "@boxname", "=", "element", ".", "attributes", "[", "'boxname'", "]", "@rl", ",", "=", "element", ".", "attributes", "[", "'rl'", "]", "@position", "=", "element", ".", "attributes", "[", "'position'", "]", "@status", "=", "element", ".", "attributes", "[", "'status'", "]", "@bat_order", "=", "element", ".", "attributes", "[", "'bat_order'", "]", "@game_position", "=", "element", ".", "attributes", "[", "'game_position'", "]", "@avg", "=", "element", ".", "attributes", "[", "'avg'", "]", "@hr", "=", "element", ".", "attributes", "[", "'hr'", "]", "@rbi", "=", "element", ".", "attributes", "[", "'rbi'", "]", "@wins", "=", "element", ".", "attributes", "[", "'wins'", "]", "@losses", "=", "element", ".", "attributes", "[", "'losses'", "]", "@era", "=", "element", ".", "attributes", "[", "'era'", "]", "set_extra_info", "end" ]
Initialize a player object by reading data from the players.xml file
[ "Initialize", "a", "player", "object", "by", "reading", "data", "from", "the", "players", ".", "xml", "file" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/player.rb#L96-L115
train
timothyf/gameday_api
lib/gameday_api/data_downloader.rb
GamedayApi.DataDownloader.download_all_for_game
def download_all_for_game(gid) download_xml_for_game(gid) download_batters_for_game(gid) download_inning_for_game(gid) download_media_for_game(gid) download_notification_for_game(gid) download_onbase_for_game(gid) download_pitchers_for_game(gid) end
ruby
def download_all_for_game(gid) download_xml_for_game(gid) download_batters_for_game(gid) download_inning_for_game(gid) download_media_for_game(gid) download_notification_for_game(gid) download_onbase_for_game(gid) download_pitchers_for_game(gid) end
[ "def", "download_all_for_game", "(", "gid", ")", "download_xml_for_game", "(", "gid", ")", "download_batters_for_game", "(", "gid", ")", "download_inning_for_game", "(", "gid", ")", "download_media_for_game", "(", "gid", ")", "download_notification_for_game", "(", "gid", ")", "download_onbase_for_game", "(", "gid", ")", "download_pitchers_for_game", "(", "gid", ")", "end" ]
Downloads all data files associated with the game specified by the game id passed in.
[ "Downloads", "all", "data", "files", "associated", "with", "the", "game", "specified", "by", "the", "game", "id", "passed", "in", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/data_downloader.rb#L22-L30
train
timothyf/gameday_api
lib/gameday_api/data_downloader.rb
GamedayApi.DataDownloader.write_file
def write_file(file_path, gd_data) if gd_data && !File.exists?(file_path) FileUtils.mkdir_p(File.dirname(file_path)) File.open(file_path, "wb") do |data| data << gd_data end end end
ruby
def write_file(file_path, gd_data) if gd_data && !File.exists?(file_path) FileUtils.mkdir_p(File.dirname(file_path)) File.open(file_path, "wb") do |data| data << gd_data end end end
[ "def", "write_file", "(", "file_path", ",", "gd_data", ")", "if", "gd_data", "&&", "!", "File", ".", "exists?", "(", "file_path", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "file_path", ")", ")", "File", ".", "open", "(", "file_path", ",", "\"wb\"", ")", "do", "|", "data", "|", "data", "<<", "gd_data", "end", "end", "end" ]
Writes the gameday data to the file specified. Does not overwrite existing files.
[ "Writes", "the", "gameday", "data", "to", "the", "file", "specified", ".", "Does", "not", "overwrite", "existing", "files", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/data_downloader.rb#L224-L231
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.load_from_scoreboard
def load_from_scoreboard(element) @away_innings = [] @home_innings = [] @scoreboard_game_id = element.attributes['id'] @ampm = element.attributes['ampm'] @venue = element.attributes['venue'] @game_pk = element.attributes['game_pk'] @time = element.attributes['time'] @time_zone = element.attributes['time_zone'] @game_type = element.attributes['game_type'] @away_name_abbrev = element.attributes['away_name_abbrev'] @home_name_abbrev = element.attributes['home_name_abbrev'] @away_code = element.attributes['away_code'] @away_file_code = element.attributes['away_file_code'] @away_team_id = element.attributes['away_team_id'] @away_team_city = element.attributes['away_team_city'] @away_team_name = element.attributes['away_team_name'] @away_division = element.attributes['away_division'] @home_code = element.attributes['home_code'] @home_file_code = element.attributes['home_file_code'] @home_team_id = element.attributes['home_team_id'] @home_team_city = element.attributes['home_team_city'] @home_team_name = element.attributes['home_team_name'] @home_division = element.attributes['home_division'] @day = element.attributes['day'] @gameday_sw = element.attributes['gameday_sw'] @away_games_back = element.attributes['away_games_back'] @home_games_back = element.attributes['home_games_back'] @away_games_back_wildcard = element.attributes['away_games_back_wildcard'] @home_games_back_wildcard = element.attributes['home_games_back_wildcard'] @venue_w_chan_loc = element.attributes['venue_w_chan_loc'] @gameday = element.attributes['gameday'] @away_win = element.attributes['away_win'] @away_loss = element.attributes['away_loss'] @home_win = element.attributes['home_win'] @home_loss = element.attributes['home_loss'] @league = element.attributes['league'] set_status(element) set_innings(element) set_totals(element) set_pitchers(element) set_homeruns(element) end
ruby
def load_from_scoreboard(element) @away_innings = [] @home_innings = [] @scoreboard_game_id = element.attributes['id'] @ampm = element.attributes['ampm'] @venue = element.attributes['venue'] @game_pk = element.attributes['game_pk'] @time = element.attributes['time'] @time_zone = element.attributes['time_zone'] @game_type = element.attributes['game_type'] @away_name_abbrev = element.attributes['away_name_abbrev'] @home_name_abbrev = element.attributes['home_name_abbrev'] @away_code = element.attributes['away_code'] @away_file_code = element.attributes['away_file_code'] @away_team_id = element.attributes['away_team_id'] @away_team_city = element.attributes['away_team_city'] @away_team_name = element.attributes['away_team_name'] @away_division = element.attributes['away_division'] @home_code = element.attributes['home_code'] @home_file_code = element.attributes['home_file_code'] @home_team_id = element.attributes['home_team_id'] @home_team_city = element.attributes['home_team_city'] @home_team_name = element.attributes['home_team_name'] @home_division = element.attributes['home_division'] @day = element.attributes['day'] @gameday_sw = element.attributes['gameday_sw'] @away_games_back = element.attributes['away_games_back'] @home_games_back = element.attributes['home_games_back'] @away_games_back_wildcard = element.attributes['away_games_back_wildcard'] @home_games_back_wildcard = element.attributes['home_games_back_wildcard'] @venue_w_chan_loc = element.attributes['venue_w_chan_loc'] @gameday = element.attributes['gameday'] @away_win = element.attributes['away_win'] @away_loss = element.attributes['away_loss'] @home_win = element.attributes['home_win'] @home_loss = element.attributes['home_loss'] @league = element.attributes['league'] set_status(element) set_innings(element) set_totals(element) set_pitchers(element) set_homeruns(element) end
[ "def", "load_from_scoreboard", "(", "element", ")", "@away_innings", "=", "[", "]", "@home_innings", "=", "[", "]", "@scoreboard_game_id", "=", "element", ".", "attributes", "[", "'id'", "]", "@ampm", "=", "element", ".", "attributes", "[", "'ampm'", "]", "@venue", "=", "element", ".", "attributes", "[", "'venue'", "]", "@game_pk", "=", "element", ".", "attributes", "[", "'game_pk'", "]", "@time", "=", "element", ".", "attributes", "[", "'time'", "]", "@time_zone", "=", "element", ".", "attributes", "[", "'time_zone'", "]", "@game_type", "=", "element", ".", "attributes", "[", "'game_type'", "]", "@away_name_abbrev", "=", "element", ".", "attributes", "[", "'away_name_abbrev'", "]", "@home_name_abbrev", "=", "element", ".", "attributes", "[", "'home_name_abbrev'", "]", "@away_code", "=", "element", ".", "attributes", "[", "'away_code'", "]", "@away_file_code", "=", "element", ".", "attributes", "[", "'away_file_code'", "]", "@away_team_id", "=", "element", ".", "attributes", "[", "'away_team_id'", "]", "@away_team_city", "=", "element", ".", "attributes", "[", "'away_team_city'", "]", "@away_team_name", "=", "element", ".", "attributes", "[", "'away_team_name'", "]", "@away_division", "=", "element", ".", "attributes", "[", "'away_division'", "]", "@home_code", "=", "element", ".", "attributes", "[", "'home_code'", "]", "@home_file_code", "=", "element", ".", "attributes", "[", "'home_file_code'", "]", "@home_team_id", "=", "element", ".", "attributes", "[", "'home_team_id'", "]", "@home_team_city", "=", "element", ".", "attributes", "[", "'home_team_city'", "]", "@home_team_name", "=", "element", ".", "attributes", "[", "'home_team_name'", "]", "@home_division", "=", "element", ".", "attributes", "[", "'home_division'", "]", "@day", "=", "element", ".", "attributes", "[", "'day'", "]", "@gameday_sw", "=", "element", ".", "attributes", "[", "'gameday_sw'", "]", "@away_games_back", "=", "element", ".", "attributes", "[", "'away_games_back'", "]", "@home_games_back", "=", "element", ".", "attributes", "[", "'home_games_back'", "]", "@away_games_back_wildcard", "=", "element", ".", "attributes", "[", "'away_games_back_wildcard'", "]", "@home_games_back_wildcard", "=", "element", ".", "attributes", "[", "'home_games_back_wildcard'", "]", "@venue_w_chan_loc", "=", "element", ".", "attributes", "[", "'venue_w_chan_loc'", "]", "@gameday", "=", "element", ".", "attributes", "[", "'gameday'", "]", "@away_win", "=", "element", ".", "attributes", "[", "'away_win'", "]", "@away_loss", "=", "element", ".", "attributes", "[", "'away_loss'", "]", "@home_win", "=", "element", ".", "attributes", "[", "'home_win'", "]", "@home_loss", "=", "element", ".", "attributes", "[", "'home_loss'", "]", "@league", "=", "element", ".", "attributes", "[", "'league'", "]", "set_status", "(", "element", ")", "set_innings", "(", "element", ")", "set_totals", "(", "element", ")", "set_pitchers", "(", "element", ")", "set_homeruns", "(", "element", ")", "end" ]
Setup a Game object from data read from the master_scoreboard.xml file
[ "Setup", "a", "Game", "object", "from", "data", "read", "from", "the", "master_scoreboard", ".", "xml", "file" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L73-L116
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.set_status
def set_status(element) element.elements.each("status") { |status| @status = GameStatus.new @status.status = status.attributes['status'] @status.ind = status.attributes['ind'] @status.reason = status.attributes['reason'] @status.inning = status.attributes['inning'] @status.top_inning = status.attributes['top_inning'] @status.b = status.attributes['b'] @status.s = status.attributes['s'] @status.o = status.attributes['o'] } end
ruby
def set_status(element) element.elements.each("status") { |status| @status = GameStatus.new @status.status = status.attributes['status'] @status.ind = status.attributes['ind'] @status.reason = status.attributes['reason'] @status.inning = status.attributes['inning'] @status.top_inning = status.attributes['top_inning'] @status.b = status.attributes['b'] @status.s = status.attributes['s'] @status.o = status.attributes['o'] } end
[ "def", "set_status", "(", "element", ")", "element", ".", "elements", ".", "each", "(", "\"status\"", ")", "{", "|", "status", "|", "@status", "=", "GameStatus", ".", "new", "@status", ".", "status", "=", "status", ".", "attributes", "[", "'status'", "]", "@status", ".", "ind", "=", "status", ".", "attributes", "[", "'ind'", "]", "@status", ".", "reason", "=", "status", ".", "attributes", "[", "'reason'", "]", "@status", ".", "inning", "=", "status", ".", "attributes", "[", "'inning'", "]", "@status", ".", "top_inning", "=", "status", ".", "attributes", "[", "'top_inning'", "]", "@status", ".", "b", "=", "status", ".", "attributes", "[", "'b'", "]", "@status", ".", "s", "=", "status", ".", "attributes", "[", "'s'", "]", "@status", ".", "o", "=", "status", ".", "attributes", "[", "'o'", "]", "}", "end" ]
Sets the game status from data in the master_scoreboard.xml file
[ "Sets", "the", "game", "status", "from", "data", "in", "the", "master_scoreboard", ".", "xml", "file" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L120-L132
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.set_innings
def set_innings(element) element.elements.each("linescore/inning") { |element| @away_innings << element.attributes['away'] @home_innings << element.attributes['home'] } end
ruby
def set_innings(element) element.elements.each("linescore/inning") { |element| @away_innings << element.attributes['away'] @home_innings << element.attributes['home'] } end
[ "def", "set_innings", "(", "element", ")", "element", ".", "elements", ".", "each", "(", "\"linescore/inning\"", ")", "{", "|", "element", "|", "@away_innings", "<<", "element", ".", "attributes", "[", "'away'", "]", "@home_innings", "<<", "element", ".", "attributes", "[", "'home'", "]", "}", "end" ]
Sets the away and home innings array containing scores by inning from data in the master_scoreboard.xml file
[ "Sets", "the", "away", "and", "home", "innings", "array", "containing", "scores", "by", "inning", "from", "data", "in", "the", "master_scoreboard", ".", "xml", "file" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L136-L141
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.set_homeruns
def set_homeruns(element) @homeruns = [] element.elements.each("home_runs/player") do |hr| player = Player.new player.last = hr.attributes['last'] player.first = hr.attributes['first'] player.hr = hr.attributes['hr'] player.std_hr = hr.attributes['std_hr'] player.team_code = hr.attributes['team_code'] @homeruns << player end end
ruby
def set_homeruns(element) @homeruns = [] element.elements.each("home_runs/player") do |hr| player = Player.new player.last = hr.attributes['last'] player.first = hr.attributes['first'] player.hr = hr.attributes['hr'] player.std_hr = hr.attributes['std_hr'] player.team_code = hr.attributes['team_code'] @homeruns << player end end
[ "def", "set_homeruns", "(", "element", ")", "@homeruns", "=", "[", "]", "element", ".", "elements", ".", "each", "(", "\"home_runs/player\"", ")", "do", "|", "hr", "|", "player", "=", "Player", ".", "new", "player", ".", "last", "=", "hr", ".", "attributes", "[", "'last'", "]", "player", ".", "first", "=", "hr", ".", "attributes", "[", "'first'", "]", "player", ".", "hr", "=", "hr", ".", "attributes", "[", "'hr'", "]", "player", ".", "std_hr", "=", "hr", ".", "attributes", "[", "'std_hr'", "]", "player", ".", "team_code", "=", "hr", ".", "attributes", "[", "'team_code'", "]", "@homeruns", "<<", "player", "end", "end" ]
Sets a list of players who had homeruns in this game from data in the master_scoreboard.xml file
[ "Sets", "a", "list", "of", "players", "who", "had", "homeruns", "in", "this", "game", "from", "data", "in", "the", "master_scoreboard", ".", "xml", "file" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L162-L173
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.get_pitchers
def get_pitchers(home_or_away) if self.gid bs = get_boxscore if home_or_away == 'away' bs.pitchers[0] else bs.pitchers[1] end else puts "No data for input specified" end end
ruby
def get_pitchers(home_or_away) if self.gid bs = get_boxscore if home_or_away == 'away' bs.pitchers[0] else bs.pitchers[1] end else puts "No data for input specified" end end
[ "def", "get_pitchers", "(", "home_or_away", ")", "if", "self", ".", "gid", "bs", "=", "get_boxscore", "if", "home_or_away", "==", "'away'", "bs", ".", "pitchers", "[", "0", "]", "else", "bs", ".", "pitchers", "[", "1", "]", "end", "else", "puts", "\"No data for input specified\"", "end", "end" ]
Returns an array of all pitchers for either the home team or the away team. The values in the returned array are PitchingAppearance instances
[ "Returns", "an", "array", "of", "all", "pitchers", "for", "either", "the", "home", "team", "or", "the", "away", "team", ".", "The", "values", "in", "the", "returned", "array", "are", "PitchingAppearance", "instances" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L325-L336
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.get_pitches
def get_pitches(pid) results = [] atbats = get_atbats atbats.each do |ab| if ab.pitcher_id == pid results << ab.pitches end end results.flatten end
ruby
def get_pitches(pid) results = [] atbats = get_atbats atbats.each do |ab| if ab.pitcher_id == pid results << ab.pitches end end results.flatten end
[ "def", "get_pitches", "(", "pid", ")", "results", "=", "[", "]", "atbats", "=", "get_atbats", "atbats", ".", "each", "do", "|", "ab", "|", "if", "ab", ".", "pitcher_id", "==", "pid", "results", "<<", "ab", ".", "pitches", "end", "end", "results", ".", "flatten", "end" ]
Returns an array of pitches from this game for the pitcher identified by pid
[ "Returns", "an", "array", "of", "pitches", "from", "this", "game", "for", "the", "pitcher", "identified", "by", "pid" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L340-L349
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.get_batters
def get_batters(home_or_away) if self.gid bs = get_boxscore if home_or_away == 'away' bs.batters[0] else bs.batters[1] end else puts "No data for input specified" end end
ruby
def get_batters(home_or_away) if self.gid bs = get_boxscore if home_or_away == 'away' bs.batters[0] else bs.batters[1] end else puts "No data for input specified" end end
[ "def", "get_batters", "(", "home_or_away", ")", "if", "self", ".", "gid", "bs", "=", "get_boxscore", "if", "home_or_away", "==", "'away'", "bs", ".", "batters", "[", "0", "]", "else", "bs", ".", "batters", "[", "1", "]", "end", "else", "puts", "\"No data for input specified\"", "end", "end" ]
Returns an array of either home or away batters for this game home_or_away must be a string with value 'home' or 'away' The values in the returned array are BattingAppearance instances
[ "Returns", "an", "array", "of", "either", "home", "or", "away", "batters", "for", "this", "game", "home_or_away", "must", "be", "a", "string", "with", "value", "home", "or", "away", "The", "values", "in", "the", "returned", "array", "are", "BattingAppearance", "instances" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L355-L366
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.get_winner
def get_winner ls = get_boxscore.linescore if ls.home_team_runs > ls.away_team_runs return home_team_abbrev else return visit_team_abbrev end end
ruby
def get_winner ls = get_boxscore.linescore if ls.home_team_runs > ls.away_team_runs return home_team_abbrev else return visit_team_abbrev end end
[ "def", "get_winner", "ls", "=", "get_boxscore", ".", "linescore", "if", "ls", ".", "home_team_runs", ">", "ls", ".", "away_team_runs", "return", "home_team_abbrev", "else", "return", "visit_team_abbrev", "end", "end" ]
Returns the team abreviation of the winning team
[ "Returns", "the", "team", "abreviation", "of", "the", "winning", "team" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L390-L397
train