repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
czycha/pxlsrt
lib/pxlsrt/image.rb
Pxlsrt.Image.diagonalColumnRow
def diagonalColumnRow(d, i) { 'column' => (d.to_i < 0 ? i : d.to_i + i).to_i, 'row' => (d.to_i < 0 ? d.to_i.abs + i : i).to_i } end
ruby
def diagonalColumnRow(d, i) { 'column' => (d.to_i < 0 ? i : d.to_i + i).to_i, 'row' => (d.to_i < 0 ? d.to_i.abs + i : i).to_i } end
[ "def", "diagonalColumnRow", "(", "d", ",", "i", ")", "{", "'column'", "=>", "(", "d", ".", "to_i", "<", "0", "?", "i", ":", "d", ".", "to_i", "+", "i", ")", ".", "to_i", ",", "'row'", "=>", "(", "d", ".", "to_i", "<", "0", "?", "d", ".", "to_i", ".", "abs", "+", "i", ":", "i", ")", ".", "to_i", "}", "end" ]
Get the column and row based on the diagonal hash created using diagonalLines.
[ "Get", "the", "column", "and", "row", "based", "on", "the", "diagonal", "hash", "created", "using", "diagonalLines", "." ]
f65880032f441887d77ddfbe5ebb0760edc96e1c
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/image.rb#L75-L80
train
czycha/pxlsrt
lib/pxlsrt/image.rb
Pxlsrt.Image.getSobel
def getSobel(x, y) if !defined?(@sobels) @sobel_x ||= [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] @sobel_y ||= [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] return 0 if x.zero? || (x == (@width - 1)) || y.zero? || (y == (@height - 1)) t1 = @grey[y - 1][x - 1] t2 = @grey[y - 1][x] t3 = @grey[y - 1][x + 1] t4 = @grey[y][x - 1] t5 = @grey[y][x] t6 = @grey[y][x + 1] t7 = @grey[y + 1][x - 1] t8 = @grey[y + 1][x] t9 = @grey[y + 1][x + 1] pixel_x = (@sobel_x[0][0] * t1) + (@sobel_x[0][1] * t2) + (@sobel_x[0][2] * t3) + (@sobel_x[1][0] * t4) + (@sobel_x[1][1] * t5) + (@sobel_x[1][2] * t6) + (@sobel_x[2][0] * t7) + (@sobel_x[2][1] * t8) + (@sobel_x[2][2] * t9) pixel_y = (@sobel_y[0][0] * t1) + (@sobel_y[0][1] * t2) + (@sobel_y[0][2] * t3) + (@sobel_y[1][0] * t4) + (@sobel_y[1][1] * t5) + (@sobel_y[1][2] * t6) + (@sobel_y[2][0] * t7) + (@sobel_y[2][1] * t8) + (@sobel_y[2][2] * t9) Math.sqrt(pixel_x * pixel_x + pixel_y * pixel_y).ceil else @sobels[y * @width + x] end end
ruby
def getSobel(x, y) if !defined?(@sobels) @sobel_x ||= [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] @sobel_y ||= [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] return 0 if x.zero? || (x == (@width - 1)) || y.zero? || (y == (@height - 1)) t1 = @grey[y - 1][x - 1] t2 = @grey[y - 1][x] t3 = @grey[y - 1][x + 1] t4 = @grey[y][x - 1] t5 = @grey[y][x] t6 = @grey[y][x + 1] t7 = @grey[y + 1][x - 1] t8 = @grey[y + 1][x] t9 = @grey[y + 1][x + 1] pixel_x = (@sobel_x[0][0] * t1) + (@sobel_x[0][1] * t2) + (@sobel_x[0][2] * t3) + (@sobel_x[1][0] * t4) + (@sobel_x[1][1] * t5) + (@sobel_x[1][2] * t6) + (@sobel_x[2][0] * t7) + (@sobel_x[2][1] * t8) + (@sobel_x[2][2] * t9) pixel_y = (@sobel_y[0][0] * t1) + (@sobel_y[0][1] * t2) + (@sobel_y[0][2] * t3) + (@sobel_y[1][0] * t4) + (@sobel_y[1][1] * t5) + (@sobel_y[1][2] * t6) + (@sobel_y[2][0] * t7) + (@sobel_y[2][1] * t8) + (@sobel_y[2][2] * t9) Math.sqrt(pixel_x * pixel_x + pixel_y * pixel_y).ceil else @sobels[y * @width + x] end end
[ "def", "getSobel", "(", "x", ",", "y", ")", "if", "!", "defined?", "(", "@sobels", ")", "@sobel_x", "||=", "[", "[", "-", "1", ",", "0", ",", "1", "]", ",", "[", "-", "2", ",", "0", ",", "2", "]", ",", "[", "-", "1", ",", "0", ",", "1", "]", "]", "@sobel_y", "||=", "[", "[", "-", "1", ",", "-", "2", ",", "-", "1", "]", ",", "[", "0", ",", "0", ",", "0", "]", ",", "[", "1", ",", "2", ",", "1", "]", "]", "return", "0", "if", "x", ".", "zero?", "||", "(", "x", "==", "(", "@width", "-", "1", ")", ")", "||", "y", ".", "zero?", "||", "(", "y", "==", "(", "@height", "-", "1", ")", ")", "t1", "=", "@grey", "[", "y", "-", "1", "]", "[", "x", "-", "1", "]", "t2", "=", "@grey", "[", "y", "-", "1", "]", "[", "x", "]", "t3", "=", "@grey", "[", "y", "-", "1", "]", "[", "x", "+", "1", "]", "t4", "=", "@grey", "[", "y", "]", "[", "x", "-", "1", "]", "t5", "=", "@grey", "[", "y", "]", "[", "x", "]", "t6", "=", "@grey", "[", "y", "]", "[", "x", "+", "1", "]", "t7", "=", "@grey", "[", "y", "+", "1", "]", "[", "x", "-", "1", "]", "t8", "=", "@grey", "[", "y", "+", "1", "]", "[", "x", "]", "t9", "=", "@grey", "[", "y", "+", "1", "]", "[", "x", "+", "1", "]", "pixel_x", "=", "(", "@sobel_x", "[", "0", "]", "[", "0", "]", "*", "t1", ")", "+", "(", "@sobel_x", "[", "0", "]", "[", "1", "]", "*", "t2", ")", "+", "(", "@sobel_x", "[", "0", "]", "[", "2", "]", "*", "t3", ")", "+", "(", "@sobel_x", "[", "1", "]", "[", "0", "]", "*", "t4", ")", "+", "(", "@sobel_x", "[", "1", "]", "[", "1", "]", "*", "t5", ")", "+", "(", "@sobel_x", "[", "1", "]", "[", "2", "]", "*", "t6", ")", "+", "(", "@sobel_x", "[", "2", "]", "[", "0", "]", "*", "t7", ")", "+", "(", "@sobel_x", "[", "2", "]", "[", "1", "]", "*", "t8", ")", "+", "(", "@sobel_x", "[", "2", "]", "[", "2", "]", "*", "t9", ")", "pixel_y", "=", "(", "@sobel_y", "[", "0", "]", "[", "0", "]", "*", "t1", ")", "+", "(", "@sobel_y", "[", "0", "]", "[", "1", "]", "*", "t2", ")", "+", "(", "@sobel_y", "[", "0", "]", "[", "2", "]", "*", "t3", ")", "+", "(", "@sobel_y", "[", "1", "]", "[", "0", "]", "*", "t4", ")", "+", "(", "@sobel_y", "[", "1", "]", "[", "1", "]", "*", "t5", ")", "+", "(", "@sobel_y", "[", "1", "]", "[", "2", "]", "*", "t6", ")", "+", "(", "@sobel_y", "[", "2", "]", "[", "0", "]", "*", "t7", ")", "+", "(", "@sobel_y", "[", "2", "]", "[", "1", "]", "*", "t8", ")", "+", "(", "@sobel_y", "[", "2", "]", "[", "2", "]", "*", "t9", ")", "Math", ".", "sqrt", "(", "pixel_x", "*", "pixel_x", "+", "pixel_y", "*", "pixel_y", ")", ".", "ceil", "else", "@sobels", "[", "y", "*", "@width", "+", "x", "]", "end", "end" ]
Retrieve Sobel value for a given pixel.
[ "Retrieve", "Sobel", "value", "for", "a", "given", "pixel", "." ]
f65880032f441887d77ddfbe5ebb0760edc96e1c
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/image.rb#L124-L144
train
czycha/pxlsrt
lib/pxlsrt/image.rb
Pxlsrt.Image.getSobels
def getSobels unless defined?(@sobels) l = [] (0...(@width * @height)).each do |xy| s = getSobel(xy % @width, (xy / @width).floor) l.push(s) end @sobels = l end @sobels end
ruby
def getSobels unless defined?(@sobels) l = [] (0...(@width * @height)).each do |xy| s = getSobel(xy % @width, (xy / @width).floor) l.push(s) end @sobels = l end @sobels end
[ "def", "getSobels", "unless", "defined?", "(", "@sobels", ")", "l", "=", "[", "]", "(", "0", "...", "(", "@width", "*", "@height", ")", ")", ".", "each", "do", "|", "xy", "|", "s", "=", "getSobel", "(", "xy", "%", "@width", ",", "(", "xy", "/", "@width", ")", ".", "floor", ")", "l", ".", "push", "(", "s", ")", "end", "@sobels", "=", "l", "end", "@sobels", "end" ]
Retrieve the Sobel values for every pixel and set it as @sobel.
[ "Retrieve", "the", "Sobel", "values", "for", "every", "pixel", "and", "set", "it", "as" ]
f65880032f441887d77ddfbe5ebb0760edc96e1c
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/image.rb#L148-L158
train
Ibsciss/ruby-middleware
lib/middleware/runner.rb
Middleware.Runner.build_call_chain
def build_call_chain(stack) # We need to instantiate the middleware stack in reverse # order so that each middleware can have a reference to # the next middleware it has to call. The final middleware # is always the empty middleware, which does nothing but return. stack.reverse.inject(EMPTY_MIDDLEWARE) do |next_middleware, current_middleware| # Unpack the actual item klass, args, block = current_middleware # Default the arguments to an empty array. Otherwise in Ruby 1.8 # a `nil` args will actually pass `nil` into the class. Not what # we want! args ||= [] if klass.is_a?(Class) # If the klass actually is a class, then instantiate it with # the app and any other arguments given. klass.new(next_middleware, *args, &block) elsif klass.respond_to?(:call) # Make it a lambda which calls the item then forwards up # the chain. lambda do |env| next_middleware.call(klass.call(env, *args)) end else fail "Invalid middleware, doesn't respond to `call`: #{klass.inspect}" end end end
ruby
def build_call_chain(stack) # We need to instantiate the middleware stack in reverse # order so that each middleware can have a reference to # the next middleware it has to call. The final middleware # is always the empty middleware, which does nothing but return. stack.reverse.inject(EMPTY_MIDDLEWARE) do |next_middleware, current_middleware| # Unpack the actual item klass, args, block = current_middleware # Default the arguments to an empty array. Otherwise in Ruby 1.8 # a `nil` args will actually pass `nil` into the class. Not what # we want! args ||= [] if klass.is_a?(Class) # If the klass actually is a class, then instantiate it with # the app and any other arguments given. klass.new(next_middleware, *args, &block) elsif klass.respond_to?(:call) # Make it a lambda which calls the item then forwards up # the chain. lambda do |env| next_middleware.call(klass.call(env, *args)) end else fail "Invalid middleware, doesn't respond to `call`: #{klass.inspect}" end end end
[ "def", "build_call_chain", "(", "stack", ")", "# We need to instantiate the middleware stack in reverse", "# order so that each middleware can have a reference to", "# the next middleware it has to call. The final middleware", "# is always the empty middleware, which does nothing but return.", "stack", ".", "reverse", ".", "inject", "(", "EMPTY_MIDDLEWARE", ")", "do", "|", "next_middleware", ",", "current_middleware", "|", "# Unpack the actual item", "klass", ",", "args", ",", "block", "=", "current_middleware", "# Default the arguments to an empty array. Otherwise in Ruby 1.8", "# a `nil` args will actually pass `nil` into the class. Not what", "# we want!", "args", "||=", "[", "]", "if", "klass", ".", "is_a?", "(", "Class", ")", "# If the klass actually is a class, then instantiate it with", "# the app and any other arguments given.", "klass", ".", "new", "(", "next_middleware", ",", "args", ",", "block", ")", "elsif", "klass", ".", "respond_to?", "(", ":call", ")", "# Make it a lambda which calls the item then forwards up", "# the chain.", "lambda", "do", "|", "env", "|", "next_middleware", ".", "call", "(", "klass", ".", "call", "(", "env", ",", "args", ")", ")", "end", "else", "fail", "\"Invalid middleware, doesn't respond to `call`: #{klass.inspect}\"", "end", "end", "end" ]
This takes a stack of middlewares and initializes them in a way that each middleware properly calls the next middleware.
[ "This", "takes", "a", "stack", "of", "middlewares", "and", "initializes", "them", "in", "a", "way", "that", "each", "middleware", "properly", "calls", "the", "next", "middleware", "." ]
51bb6504737b126fcfb9c4845a806244fad3493b
https://github.com/Ibsciss/ruby-middleware/blob/51bb6504737b126fcfb9c4845a806244fad3493b/lib/middleware/runner.rb#L38-L66
train
Ibsciss/ruby-middleware
lib/middleware/builder.rb
Middleware.Builder.insert_before_each
def insert_before_each(middleware, *args, &block) self.stack = stack.reduce([]) do |carry, item| carry.push([middleware, args, block], item) end end
ruby
def insert_before_each(middleware, *args, &block) self.stack = stack.reduce([]) do |carry, item| carry.push([middleware, args, block], item) end end
[ "def", "insert_before_each", "(", "middleware", ",", "*", "args", ",", "&", "block", ")", "self", ".", "stack", "=", "stack", ".", "reduce", "(", "[", "]", ")", "do", "|", "carry", ",", "item", "|", "carry", ".", "push", "(", "[", "middleware", ",", "args", ",", "block", "]", ",", "item", ")", "end", "end" ]
Inserts a middleware before each middleware object
[ "Inserts", "a", "middleware", "before", "each", "middleware", "object" ]
51bb6504737b126fcfb9c4845a806244fad3493b
https://github.com/Ibsciss/ruby-middleware/blob/51bb6504737b126fcfb9c4845a806244fad3493b/lib/middleware/builder.rb#L104-L108
train
Ibsciss/ruby-middleware
lib/middleware/builder.rb
Middleware.Builder.delete
def delete(index) index = self.index(index) unless index.is_a?(Integer) stack.delete_at(index) end
ruby
def delete(index) index = self.index(index) unless index.is_a?(Integer) stack.delete_at(index) end
[ "def", "delete", "(", "index", ")", "index", "=", "self", ".", "index", "(", "index", ")", "unless", "index", ".", "is_a?", "(", "Integer", ")", "stack", ".", "delete_at", "(", "index", ")", "end" ]
Deletes the given middleware object or index
[ "Deletes", "the", "given", "middleware", "object", "or", "index" ]
51bb6504737b126fcfb9c4845a806244fad3493b
https://github.com/Ibsciss/ruby-middleware/blob/51bb6504737b126fcfb9c4845a806244fad3493b/lib/middleware/builder.rb#L126-L129
train
bradleypriest/pxpay
lib/pxpay/notification.rb
Pxpay.Notification.to_hash
def to_hash doc = ::Nokogiri::XML( self.response ) hash = {} doc.at_css("Response").element_children.each do |attribute| hash[attribute.name.underscore.to_sym] = attribute.inner_text end hash[:valid] = doc.at_css("Response")['valid'] hash end
ruby
def to_hash doc = ::Nokogiri::XML( self.response ) hash = {} doc.at_css("Response").element_children.each do |attribute| hash[attribute.name.underscore.to_sym] = attribute.inner_text end hash[:valid] = doc.at_css("Response")['valid'] hash end
[ "def", "to_hash", "doc", "=", "::", "Nokogiri", "::", "XML", "(", "self", ".", "response", ")", "hash", "=", "{", "}", "doc", ".", "at_css", "(", "\"Response\"", ")", ".", "element_children", ".", "each", "do", "|", "attribute", "|", "hash", "[", "attribute", ".", "name", ".", "underscore", ".", "to_sym", "]", "=", "attribute", ".", "inner_text", "end", "hash", "[", ":valid", "]", "=", "doc", ".", "at_css", "(", "\"Response\"", ")", "[", "'valid'", "]", "hash", "end" ]
Return the response as a hash
[ "Return", "the", "response", "as", "a", "hash" ]
ba8822adb2349007b85ad2ddeb8d924695983dfa
https://github.com/bradleypriest/pxpay/blob/ba8822adb2349007b85ad2ddeb8d924695983dfa/lib/pxpay/notification.rb#L17-L25
train
frodenas/cloudfoundry-client
lib/cloudfoundry/client.rb
CloudFoundry.Client.valid_target_url?
def valid_target_url? return false unless cloud_info = cloud_info() return false unless cloud_info[:name] return false unless cloud_info[:build] return false unless cloud_info[:support] return false unless cloud_info[:version] true rescue false end
ruby
def valid_target_url? return false unless cloud_info = cloud_info() return false unless cloud_info[:name] return false unless cloud_info[:build] return false unless cloud_info[:support] return false unless cloud_info[:version] true rescue false end
[ "def", "valid_target_url?", "return", "false", "unless", "cloud_info", "=", "cloud_info", "(", ")", "return", "false", "unless", "cloud_info", "[", ":name", "]", "return", "false", "unless", "cloud_info", "[", ":build", "]", "return", "false", "unless", "cloud_info", "[", ":support", "]", "return", "false", "unless", "cloud_info", "[", ":version", "]", "true", "rescue", "false", "end" ]
Checks if the target_url is a valid CloudFoundry target. @return [Boolean] Returns true if target_url is a valid CloudFoundry API URL, false otherwise.
[ "Checks", "if", "the", "target_url", "is", "a", "valid", "CloudFoundry", "target", "." ]
831d6045d29f4d34388c61d34023b201480f0591
https://github.com/frodenas/cloudfoundry-client/blob/831d6045d29f4d34388c61d34023b201480f0591/lib/cloudfoundry/client.rb#L75-L84
train
Zerocchi/jikan.rb
lib/jikan/models/search.rb
Jikan.Search.result
def result case @type when :anime iter { |i| Jikan::AnimeResult.new(i) } when :manga iter { |i| Jikan::MangaResult.new(i) } when :character iter { |i| Jikan::CharacterResult.new(i) } when :person iter { |i| Jikan::PersonResult.new(i) } end end
ruby
def result case @type when :anime iter { |i| Jikan::AnimeResult.new(i) } when :manga iter { |i| Jikan::MangaResult.new(i) } when :character iter { |i| Jikan::CharacterResult.new(i) } when :person iter { |i| Jikan::PersonResult.new(i) } end end
[ "def", "result", "case", "@type", "when", ":anime", "iter", "{", "|", "i", "|", "Jikan", "::", "AnimeResult", ".", "new", "(", "i", ")", "}", "when", ":manga", "iter", "{", "|", "i", "|", "Jikan", "::", "MangaResult", ".", "new", "(", "i", ")", "}", "when", ":character", "iter", "{", "|", "i", "|", "Jikan", "::", "CharacterResult", ".", "new", "(", "i", ")", "}", "when", ":person", "iter", "{", "|", "i", "|", "Jikan", "::", "PersonResult", ".", "new", "(", "i", ")", "}", "end", "end" ]
returns each result items wrapped in their respective objects
[ "returns", "each", "result", "items", "wrapped", "in", "their", "respective", "objects" ]
498a779e9f85a191e8d6375f7ca83039e984cd4a
https://github.com/Zerocchi/jikan.rb/blob/498a779e9f85a191e8d6375f7ca83039e984cd4a/lib/jikan/models/search.rb#L27-L38
train
github/octocatalog-diff
lib/octocatalog-diff/puppetdb.rb
OctocatalogDiff.PuppetDB.parse_url
def parse_url(url) uri = URI(url) if URI.split(url)[3].nil? uri.port = uri.scheme == 'https' ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT end raise ArgumentError, "URL #{url} has invalid scheme" unless uri.scheme =~ /^https?$/ parsed_url = { ssl: uri.scheme == 'https', host: uri.host, port: uri.port } if uri.user || uri.password parsed_url[:username] = uri.user parsed_url[:password] = uri.password end parsed_url rescue URI::InvalidURIError => exc raise exc.class, "Invalid URL: #{url} (#{exc.message})" end
ruby
def parse_url(url) uri = URI(url) if URI.split(url)[3].nil? uri.port = uri.scheme == 'https' ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT end raise ArgumentError, "URL #{url} has invalid scheme" unless uri.scheme =~ /^https?$/ parsed_url = { ssl: uri.scheme == 'https', host: uri.host, port: uri.port } if uri.user || uri.password parsed_url[:username] = uri.user parsed_url[:password] = uri.password end parsed_url rescue URI::InvalidURIError => exc raise exc.class, "Invalid URL: #{url} (#{exc.message})" end
[ "def", "parse_url", "(", "url", ")", "uri", "=", "URI", "(", "url", ")", "if", "URI", ".", "split", "(", "url", ")", "[", "3", "]", ".", "nil?", "uri", ".", "port", "=", "uri", ".", "scheme", "==", "'https'", "?", "DEFAULT_HTTPS_PORT", ":", "DEFAULT_HTTP_PORT", "end", "raise", "ArgumentError", ",", "\"URL #{url} has invalid scheme\"", "unless", "uri", ".", "scheme", "=~", "/", "/", "parsed_url", "=", "{", "ssl", ":", "uri", ".", "scheme", "==", "'https'", ",", "host", ":", "uri", ".", "host", ",", "port", ":", "uri", ".", "port", "}", "if", "uri", ".", "user", "||", "uri", ".", "password", "parsed_url", "[", ":username", "]", "=", "uri", ".", "user", "parsed_url", "[", ":password", "]", "=", "uri", ".", "password", "end", "parsed_url", "rescue", "URI", "::", "InvalidURIError", "=>", "exc", "raise", "exc", ".", "class", ",", "\"Invalid URL: #{url} (#{exc.message})\"", "end" ]
Parse a URL to determine hostname, port number, and whether or not SSL is used. @param url [String] URL to parse @return [Hash] { ssl: true/false, host: <String>, port: <Integer> }
[ "Parse", "a", "URL", "to", "determine", "hostname", "port", "number", "and", "whether", "or", "not", "SSL", "is", "used", "." ]
c0ec977e7bd4e6d1b925f8697028901f2aca40eb
https://github.com/github/octocatalog-diff/blob/c0ec977e7bd4e6d1b925f8697028901f2aca40eb/lib/octocatalog-diff/puppetdb.rb#L156-L172
train
github/octocatalog-diff
lib/octocatalog-diff/catalog.rb
OctocatalogDiff.Catalog.resources
def resources build raise OctocatalogDiff::Errors::CatalogError, 'Catalog does not appear to have been built' if !valid? && error_message.nil? raise OctocatalogDiff::Errors::CatalogError, error_message unless valid? return @catalog['data']['resources'] if @catalog['data'].is_a?(Hash) && @catalog['data']['resources'].is_a?(Array) return @catalog['resources'] if @catalog['resources'].is_a?(Array) # This is a bug condition # :nocov: raise "BUG: catalog has no data::resources or ::resources array. Please report this. #{@catalog.inspect}" # :nocov: end
ruby
def resources build raise OctocatalogDiff::Errors::CatalogError, 'Catalog does not appear to have been built' if !valid? && error_message.nil? raise OctocatalogDiff::Errors::CatalogError, error_message unless valid? return @catalog['data']['resources'] if @catalog['data'].is_a?(Hash) && @catalog['data']['resources'].is_a?(Array) return @catalog['resources'] if @catalog['resources'].is_a?(Array) # This is a bug condition # :nocov: raise "BUG: catalog has no data::resources or ::resources array. Please report this. #{@catalog.inspect}" # :nocov: end
[ "def", "resources", "build", "raise", "OctocatalogDiff", "::", "Errors", "::", "CatalogError", ",", "'Catalog does not appear to have been built'", "if", "!", "valid?", "&&", "error_message", ".", "nil?", "raise", "OctocatalogDiff", "::", "Errors", "::", "CatalogError", ",", "error_message", "unless", "valid?", "return", "@catalog", "[", "'data'", "]", "[", "'resources'", "]", "if", "@catalog", "[", "'data'", "]", ".", "is_a?", "(", "Hash", ")", "&&", "@catalog", "[", "'data'", "]", "[", "'resources'", "]", ".", "is_a?", "(", "Array", ")", "return", "@catalog", "[", "'resources'", "]", "if", "@catalog", "[", "'resources'", "]", ".", "is_a?", "(", "Array", ")", "# This is a bug condition", "# :nocov:", "raise", "\"BUG: catalog has no data::resources or ::resources array. Please report this. #{@catalog.inspect}\"", "# :nocov:", "end" ]
This is a compatibility layer for the resources, which are in a different place in Puppet 3.x and Puppet 4.x @return [Array] Resource array
[ "This", "is", "a", "compatibility", "layer", "for", "the", "resources", "which", "are", "in", "a", "different", "place", "in", "Puppet", "3", ".", "x", "and", "Puppet", "4", ".", "x" ]
c0ec977e7bd4e6d1b925f8697028901f2aca40eb
https://github.com/github/octocatalog-diff/blob/c0ec977e7bd4e6d1b925f8697028901f2aca40eb/lib/octocatalog-diff/catalog.rb#L190-L200
train
github/octocatalog-diff
lib/octocatalog-diff/facts.rb
OctocatalogDiff.Facts.facts
def facts(node = @node, timestamp = false) raise "Expected @facts to be a hash but it is a #{@facts.class}" unless @facts.is_a?(Hash) raise "Expected @facts['values'] to be a hash but it is a #{@facts['values'].class}" unless @facts['values'].is_a?(Hash) f = @facts.dup f['name'] = node unless node.nil? || node.empty? f['values'].delete('_timestamp') f.delete('expiration') if timestamp f['timestamp'] = Time.now.to_s f['values']['timestamp'] = f['timestamp'] f['expiration'] = (Time.now + (24 * 60 * 60)).to_s end f end
ruby
def facts(node = @node, timestamp = false) raise "Expected @facts to be a hash but it is a #{@facts.class}" unless @facts.is_a?(Hash) raise "Expected @facts['values'] to be a hash but it is a #{@facts['values'].class}" unless @facts['values'].is_a?(Hash) f = @facts.dup f['name'] = node unless node.nil? || node.empty? f['values'].delete('_timestamp') f.delete('expiration') if timestamp f['timestamp'] = Time.now.to_s f['values']['timestamp'] = f['timestamp'] f['expiration'] = (Time.now + (24 * 60 * 60)).to_s end f end
[ "def", "facts", "(", "node", "=", "@node", ",", "timestamp", "=", "false", ")", "raise", "\"Expected @facts to be a hash but it is a #{@facts.class}\"", "unless", "@facts", ".", "is_a?", "(", "Hash", ")", "raise", "\"Expected @facts['values'] to be a hash but it is a #{@facts['values'].class}\"", "unless", "@facts", "[", "'values'", "]", ".", "is_a?", "(", "Hash", ")", "f", "=", "@facts", ".", "dup", "f", "[", "'name'", "]", "=", "node", "unless", "node", ".", "nil?", "||", "node", ".", "empty?", "f", "[", "'values'", "]", ".", "delete", "(", "'_timestamp'", ")", "f", ".", "delete", "(", "'expiration'", ")", "if", "timestamp", "f", "[", "'timestamp'", "]", "=", "Time", ".", "now", ".", "to_s", "f", "[", "'values'", "]", "[", "'timestamp'", "]", "=", "f", "[", "'timestamp'", "]", "f", "[", "'expiration'", "]", "=", "(", "Time", ".", "now", "+", "(", "24", "*", "60", "*", "60", ")", ")", ".", "to_s", "end", "f", "end" ]
Facts - returned the 'cleansed' facts. Clean up facts by setting 'name' to the node if given, and deleting _timestamp and expiration which may cause Puppet catalog compilation to fail if the facts are old. @param node [String] Node name to override returned facts @return [Hash] Facts hash { 'name' => '...', 'values' => { ... } }
[ "Facts", "-", "returned", "the", "cleansed", "facts", ".", "Clean", "up", "facts", "by", "setting", "name", "to", "the", "node", "if", "given", "and", "deleting", "_timestamp", "and", "expiration", "which", "may", "cause", "Puppet", "catalog", "compilation", "to", "fail", "if", "the", "facts", "are", "old", "." ]
c0ec977e7bd4e6d1b925f8697028901f2aca40eb
https://github.com/github/octocatalog-diff/blob/c0ec977e7bd4e6d1b925f8697028901f2aca40eb/lib/octocatalog-diff/facts.rb#L57-L70
train
github/octocatalog-diff
lib/octocatalog-diff/facts.rb
OctocatalogDiff.Facts.without
def without(remove) r = remove.is_a?(Array) ? remove : [remove] obj = dup r.each { |fact| obj.remove_fact_from_list(fact) } obj end
ruby
def without(remove) r = remove.is_a?(Array) ? remove : [remove] obj = dup r.each { |fact| obj.remove_fact_from_list(fact) } obj end
[ "def", "without", "(", "remove", ")", "r", "=", "remove", ".", "is_a?", "(", "Array", ")", "?", "remove", ":", "[", "remove", "]", "obj", "=", "dup", "r", ".", "each", "{", "|", "fact", "|", "obj", ".", "remove_fact_from_list", "(", "fact", ")", "}", "obj", "end" ]
Facts - remove one or more facts from the list. @param remove [String|Array<String>] Fact(s) to remove @return self
[ "Facts", "-", "remove", "one", "or", "more", "facts", "from", "the", "list", "." ]
c0ec977e7bd4e6d1b925f8697028901f2aca40eb
https://github.com/github/octocatalog-diff/blob/c0ec977e7bd4e6d1b925f8697028901f2aca40eb/lib/octocatalog-diff/facts.rb#L82-L87
train
github/octocatalog-diff
lib/octocatalog-diff/facts.rb
OctocatalogDiff.Facts.facts_to_yaml
def facts_to_yaml(node = @node) # Add the header that Puppet needs to treat this as facts. Save the results # as a string in the option. f = facts(node) fact_file = f.to_yaml.split(/\n/) fact_file[0] = '--- !ruby/object:Puppet::Node::Facts' if fact_file[0] =~ /^---/ fact_file.join("\n") end
ruby
def facts_to_yaml(node = @node) # Add the header that Puppet needs to treat this as facts. Save the results # as a string in the option. f = facts(node) fact_file = f.to_yaml.split(/\n/) fact_file[0] = '--- !ruby/object:Puppet::Node::Facts' if fact_file[0] =~ /^---/ fact_file.join("\n") end
[ "def", "facts_to_yaml", "(", "node", "=", "@node", ")", "# Add the header that Puppet needs to treat this as facts. Save the results", "# as a string in the option.", "f", "=", "facts", "(", "node", ")", "fact_file", "=", "f", ".", "to_yaml", ".", "split", "(", "/", "\\n", "/", ")", "fact_file", "[", "0", "]", "=", "'--- !ruby/object:Puppet::Node::Facts'", "if", "fact_file", "[", "0", "]", "=~", "/", "/", "fact_file", ".", "join", "(", "\"\\n\"", ")", "end" ]
Turn hash of facts into appropriate YAML for Puppet @param node [String] Node name to override returned facts @return [String] Puppet-compatible YAML facts
[ "Turn", "hash", "of", "facts", "into", "appropriate", "YAML", "for", "Puppet" ]
c0ec977e7bd4e6d1b925f8697028901f2aca40eb
https://github.com/github/octocatalog-diff/blob/c0ec977e7bd4e6d1b925f8697028901f2aca40eb/lib/octocatalog-diff/facts.rb#L98-L105
train
fortesinformatica/jasper-rails
lib/jasper-rails/jasper_reports_renderer.rb
JasperRails.JasperReportsRenderer.parameter_value_of
def parameter_value_of(param) _String = Rjb::import 'java.lang.String' # Using Rjb::import('java.util.HashMap').new, it returns an instance of # Rjb::Rjb_JavaProxy, so the Rjb_JavaProxy parent is the Rjb module itself. if param.class.parent == Rjb param else _String.new(param.to_s, "UTF-8") end end
ruby
def parameter_value_of(param) _String = Rjb::import 'java.lang.String' # Using Rjb::import('java.util.HashMap').new, it returns an instance of # Rjb::Rjb_JavaProxy, so the Rjb_JavaProxy parent is the Rjb module itself. if param.class.parent == Rjb param else _String.new(param.to_s, "UTF-8") end end
[ "def", "parameter_value_of", "(", "param", ")", "_String", "=", "Rjb", "::", "import", "'java.lang.String'", "# Using Rjb::import('java.util.HashMap').new, it returns an instance of", "# Rjb::Rjb_JavaProxy, so the Rjb_JavaProxy parent is the Rjb module itself.", "if", "param", ".", "class", ".", "parent", "==", "Rjb", "param", "else", "_String", ".", "new", "(", "param", ".", "to_s", ",", "\"UTF-8\"", ")", "end", "end" ]
Returns the value without conversion when it's converted to Java Types. When isn't a Rjb class, returns a Java String of it.
[ "Returns", "the", "value", "without", "conversion", "when", "it", "s", "converted", "to", "Java", "Types", ".", "When", "isn", "t", "a", "Rjb", "class", "returns", "a", "Java", "String", "of", "it", "." ]
d04e8046f3824a71dbfe9375039c0ed38d2ea71f
https://github.com/fortesinformatica/jasper-rails/blob/d04e8046f3824a71dbfe9375039c0ed38d2ea71f/lib/jasper-rails/jasper_reports_renderer.rb#L129-L138
train
amitree/delayed_job_recurring
lib/delayed/recurring_job.rb
Delayed.RecurringJob.schedule!
def schedule! options = {} options = options.dup if run_every = options.delete(:run_every) options[:run_interval] = serialize_duration(run_every) end @schedule_options = options.reverse_merge(@schedule_options || {}).reverse_merge( run_at: self.class.run_at, timezone: self.class.timezone, run_interval: serialize_duration(self.class.run_every), priority: self.class.priority, queue: self.class.queue ) enqueue_opts = { priority: @schedule_options[:priority], run_at: next_run_time } enqueue_opts[:queue] = @schedule_options[:queue] if @schedule_options[:queue] Delayed::Job.transaction do self.class.jobs(@schedule_options).destroy_all if Gem.loaded_specs['delayed_job'].version.to_s.first.to_i < 3 Delayed::Job.enqueue self, enqueue_opts[:priority], enqueue_opts[:run_at] else Delayed::Job.enqueue self, enqueue_opts end end end
ruby
def schedule! options = {} options = options.dup if run_every = options.delete(:run_every) options[:run_interval] = serialize_duration(run_every) end @schedule_options = options.reverse_merge(@schedule_options || {}).reverse_merge( run_at: self.class.run_at, timezone: self.class.timezone, run_interval: serialize_duration(self.class.run_every), priority: self.class.priority, queue: self.class.queue ) enqueue_opts = { priority: @schedule_options[:priority], run_at: next_run_time } enqueue_opts[:queue] = @schedule_options[:queue] if @schedule_options[:queue] Delayed::Job.transaction do self.class.jobs(@schedule_options).destroy_all if Gem.loaded_specs['delayed_job'].version.to_s.first.to_i < 3 Delayed::Job.enqueue self, enqueue_opts[:priority], enqueue_opts[:run_at] else Delayed::Job.enqueue self, enqueue_opts end end end
[ "def", "schedule!", "options", "=", "{", "}", "options", "=", "options", ".", "dup", "if", "run_every", "=", "options", ".", "delete", "(", ":run_every", ")", "options", "[", ":run_interval", "]", "=", "serialize_duration", "(", "run_every", ")", "end", "@schedule_options", "=", "options", ".", "reverse_merge", "(", "@schedule_options", "||", "{", "}", ")", ".", "reverse_merge", "(", "run_at", ":", "self", ".", "class", ".", "run_at", ",", "timezone", ":", "self", ".", "class", ".", "timezone", ",", "run_interval", ":", "serialize_duration", "(", "self", ".", "class", ".", "run_every", ")", ",", "priority", ":", "self", ".", "class", ".", "priority", ",", "queue", ":", "self", ".", "class", ".", "queue", ")", "enqueue_opts", "=", "{", "priority", ":", "@schedule_options", "[", ":priority", "]", ",", "run_at", ":", "next_run_time", "}", "enqueue_opts", "[", ":queue", "]", "=", "@schedule_options", "[", ":queue", "]", "if", "@schedule_options", "[", ":queue", "]", "Delayed", "::", "Job", ".", "transaction", "do", "self", ".", "class", ".", "jobs", "(", "@schedule_options", ")", ".", "destroy_all", "if", "Gem", ".", "loaded_specs", "[", "'delayed_job'", "]", ".", "version", ".", "to_s", ".", "first", ".", "to_i", "<", "3", "Delayed", "::", "Job", ".", "enqueue", "self", ",", "enqueue_opts", "[", ":priority", "]", ",", "enqueue_opts", "[", ":run_at", "]", "else", "Delayed", "::", "Job", ".", "enqueue", "self", ",", "enqueue_opts", "end", "end", "end" ]
Schedule this "repeating" job
[ "Schedule", "this", "repeating", "job" ]
c0eb8c6f53f49319e9b029f0cc1993603718bfa6
https://github.com/amitree/delayed_job_recurring/blob/c0eb8c6f53f49319e9b029f0cc1993603718bfa6/lib/delayed/recurring_job.rb#L25-L51
train
Yelp/yelp-ruby
lib/yelp/client.rb
Yelp.Client.create_methods_from_instance
def create_methods_from_instance(instance) instance.public_methods(false).each do |method_name| add_method(instance, method_name) end end
ruby
def create_methods_from_instance(instance) instance.public_methods(false).each do |method_name| add_method(instance, method_name) end end
[ "def", "create_methods_from_instance", "(", "instance", ")", "instance", ".", "public_methods", "(", "false", ")", ".", "each", "do", "|", "method_name", "|", "add_method", "(", "instance", ",", "method_name", ")", "end", "end" ]
Loop through all of the endpoint instances' public singleton methods to add the method to client
[ "Loop", "through", "all", "of", "the", "endpoint", "instances", "public", "singleton", "methods", "to", "add", "the", "method", "to", "client" ]
cca275c39dbb01b59fcb40902aa00a482352a35d
https://github.com/Yelp/yelp-ruby/blob/cca275c39dbb01b59fcb40902aa00a482352a35d/lib/yelp/client.rb#L92-L96
train
Yelp/yelp-ruby
lib/yelp/client.rb
Yelp.Client.add_method
def add_method(instance, method_name) define_singleton_method(method_name) do |*args| instance.public_send(method_name, *args) end end
ruby
def add_method(instance, method_name) define_singleton_method(method_name) do |*args| instance.public_send(method_name, *args) end end
[ "def", "add_method", "(", "instance", ",", "method_name", ")", "define_singleton_method", "(", "method_name", ")", "do", "|", "*", "args", "|", "instance", ".", "public_send", "(", "method_name", ",", "args", ")", "end", "end" ]
Define the method on the client and send it to the endpoint instance with the args passed in
[ "Define", "the", "method", "on", "the", "client", "and", "send", "it", "to", "the", "endpoint", "instance", "with", "the", "args", "passed", "in" ]
cca275c39dbb01b59fcb40902aa00a482352a35d
https://github.com/Yelp/yelp-ruby/blob/cca275c39dbb01b59fcb40902aa00a482352a35d/lib/yelp/client.rb#L100-L104
train
Yelp/yelp-ruby
lib/yelp/configuration.rb
Yelp.Configuration.auth_keys
def auth_keys AUTH_KEYS.inject({}) do |keys_hash, key| keys_hash[key] = send(key) keys_hash end end
ruby
def auth_keys AUTH_KEYS.inject({}) do |keys_hash, key| keys_hash[key] = send(key) keys_hash end end
[ "def", "auth_keys", "AUTH_KEYS", ".", "inject", "(", "{", "}", ")", "do", "|", "keys_hash", ",", "key", "|", "keys_hash", "[", "key", "]", "=", "send", "(", "key", ")", "keys_hash", "end", "end" ]
Creates the configuration @param [Hash] hash containing configuration parameters and their values @return [Configuration] a new configuration with the values from the config_hash set Returns a hash of api keys and their values
[ "Creates", "the", "configuration" ]
cca275c39dbb01b59fcb40902aa00a482352a35d
https://github.com/Yelp/yelp-ruby/blob/cca275c39dbb01b59fcb40902aa00a482352a35d/lib/yelp/configuration.rb#L20-L25
train
mowens/cocoapods-links
lib/pod/lockfile.rb
Pod.Lockfile.write_to_disk
def write_to_disk(path) # code here mimics the original method but with link filtering filename = File.basename(path) path.dirname.mkpath unless path.dirname.exist? yaml = to_link_yaml File.open(path, 'w') { |f| f.write(yaml) } self.defined_in_file = path end
ruby
def write_to_disk(path) # code here mimics the original method but with link filtering filename = File.basename(path) path.dirname.mkpath unless path.dirname.exist? yaml = to_link_yaml File.open(path, 'w') { |f| f.write(yaml) } self.defined_in_file = path end
[ "def", "write_to_disk", "(", "path", ")", "# code here mimics the original method but with link filtering", "filename", "=", "File", ".", "basename", "(", "path", ")", "path", ".", "dirname", ".", "mkpath", "unless", "path", ".", "dirname", ".", "exist?", "yaml", "=", "to_link_yaml", "File", ".", "open", "(", "path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "yaml", ")", "}", "self", ".", "defined_in_file", "=", "path", "end" ]
Hook the Podfile.lock file generation to allow us to filter out the links added to the Podfile.lock. The logic here is to replace the new Podfile.lock link content with what existed before the link was added. Currently, this is called for both Podfile.lock and Manifest.lock file so we only want to alter the Podfile.lock @param path path to write the .lock file to
[ "Hook", "the", "Podfile", ".", "lock", "file", "generation", "to", "allow", "us", "to", "filter", "out", "the", "links", "added", "to", "the", "Podfile", ".", "lock", ".", "The", "logic", "here", "is", "to", "replace", "the", "new", "Podfile", ".", "lock", "link", "content", "with", "what", "existed", "before", "the", "link", "was", "added", ".", "Currently", "this", "is", "called", "for", "both", "Podfile", ".", "lock", "and", "Manifest", ".", "lock", "file", "so", "we", "only", "want", "to", "alter", "the", "Podfile", ".", "lock" ]
148611a98f8258862a8b03e11c8fea095544d770
https://github.com/mowens/cocoapods-links/blob/148611a98f8258862a8b03e11c8fea095544d770/lib/pod/lockfile.rb#L27-L35
train
mowens/cocoapods-links
lib/pod/lockfile.rb
Pod.Lockfile.to_link_hash
def to_link_hash # retrieve the lock contents with links after_hash = to_hash unless File.exists?(PODFILE_LOCK) return after_hash end # retrieve the lock content before the links before_hash = YAML.load(File.read(PODFILE_LOCK)) # retrieve installed links links = Pod::Command::Links.installed_links # # Logic: # Here we will replace anything that changed in the contents that will be dumped in the # Podfile.lock due to links with the data that previously exists in the Podfile.lock. This # allows the Podfile.lock with the dependency trees to remain unchanged when linking # developement pods. The Podfile.lock contains several keys, but we only need to alter the # following: # # - PODS # - DEPENDENCIES # - EXTERNAL SOURCES # - CHECKOUT OPTIONS # - SPEC CHECKSUMS # after_hash['PODS'] = merge_pods links, before_hash['PODS'], after_hash['PODS'] after_hash['DEPENDENCIES'] = merge_dependencies links, before_hash['DEPENDENCIES'], after_hash['DEPENDENCIES'] after_hash['EXTERNAL SOURCES'] = merge_hashes links, before_hash['EXTERNAL SOURCES'], after_hash['EXTERNAL SOURCES'] after_hash['CHECKOUT OPTIONS'] = merge_hashes links, before_hash['CHECKOUT OPTIONS'], after_hash['CHECKOUT OPTIONS'] after_hash['SPEC CHECKSUMS'] = merge_hashes links, before_hash['SPEC CHECKSUMS'], after_hash['SPEC CHECKSUMS'] return after_hash end
ruby
def to_link_hash # retrieve the lock contents with links after_hash = to_hash unless File.exists?(PODFILE_LOCK) return after_hash end # retrieve the lock content before the links before_hash = YAML.load(File.read(PODFILE_LOCK)) # retrieve installed links links = Pod::Command::Links.installed_links # # Logic: # Here we will replace anything that changed in the contents that will be dumped in the # Podfile.lock due to links with the data that previously exists in the Podfile.lock. This # allows the Podfile.lock with the dependency trees to remain unchanged when linking # developement pods. The Podfile.lock contains several keys, but we only need to alter the # following: # # - PODS # - DEPENDENCIES # - EXTERNAL SOURCES # - CHECKOUT OPTIONS # - SPEC CHECKSUMS # after_hash['PODS'] = merge_pods links, before_hash['PODS'], after_hash['PODS'] after_hash['DEPENDENCIES'] = merge_dependencies links, before_hash['DEPENDENCIES'], after_hash['DEPENDENCIES'] after_hash['EXTERNAL SOURCES'] = merge_hashes links, before_hash['EXTERNAL SOURCES'], after_hash['EXTERNAL SOURCES'] after_hash['CHECKOUT OPTIONS'] = merge_hashes links, before_hash['CHECKOUT OPTIONS'], after_hash['CHECKOUT OPTIONS'] after_hash['SPEC CHECKSUMS'] = merge_hashes links, before_hash['SPEC CHECKSUMS'], after_hash['SPEC CHECKSUMS'] return after_hash end
[ "def", "to_link_hash", "# retrieve the lock contents with links", "after_hash", "=", "to_hash", "unless", "File", ".", "exists?", "(", "PODFILE_LOCK", ")", "return", "after_hash", "end", "# retrieve the lock content before the links", "before_hash", "=", "YAML", ".", "load", "(", "File", ".", "read", "(", "PODFILE_LOCK", ")", ")", "# retrieve installed links", "links", "=", "Pod", "::", "Command", "::", "Links", ".", "installed_links", "#", "# Logic:", "# Here we will replace anything that changed in the contents that will be dumped in the", "# Podfile.lock due to links with the data that previously exists in the Podfile.lock. This", "# allows the Podfile.lock with the dependency trees to remain unchanged when linking", "# developement pods. The Podfile.lock contains several keys, but we only need to alter the", "# following:", "# ", "# - PODS", "# - DEPENDENCIES", "# - EXTERNAL SOURCES", "# - CHECKOUT OPTIONS", "# - SPEC CHECKSUMS", "# ", "after_hash", "[", "'PODS'", "]", "=", "merge_pods", "links", ",", "before_hash", "[", "'PODS'", "]", ",", "after_hash", "[", "'PODS'", "]", "after_hash", "[", "'DEPENDENCIES'", "]", "=", "merge_dependencies", "links", ",", "before_hash", "[", "'DEPENDENCIES'", "]", ",", "after_hash", "[", "'DEPENDENCIES'", "]", "after_hash", "[", "'EXTERNAL SOURCES'", "]", "=", "merge_hashes", "links", ",", "before_hash", "[", "'EXTERNAL SOURCES'", "]", ",", "after_hash", "[", "'EXTERNAL SOURCES'", "]", "after_hash", "[", "'CHECKOUT OPTIONS'", "]", "=", "merge_hashes", "links", ",", "before_hash", "[", "'CHECKOUT OPTIONS'", "]", ",", "after_hash", "[", "'CHECKOUT OPTIONS'", "]", "after_hash", "[", "'SPEC CHECKSUMS'", "]", "=", "merge_hashes", "links", ",", "before_hash", "[", "'SPEC CHECKSUMS'", "]", ",", "after_hash", "[", "'SPEC CHECKSUMS'", "]", "return", "after_hash", "end" ]
Will get the Podfile.lock contents hash after replacing the linked content with its previous Podfile.lock information keeping the Podfile and Podfile.lock in sync and clear of any link data @returns hash that is to be dumped to the Podfile.lock file without link content
[ "Will", "get", "the", "Podfile", ".", "lock", "contents", "hash", "after", "replacing", "the", "linked", "content", "with", "its", "previous", "Podfile", ".", "lock", "information", "keeping", "the", "Podfile", "and", "Podfile", ".", "lock", "in", "sync", "and", "clear", "of", "any", "link", "data" ]
148611a98f8258862a8b03e11c8fea095544d770
https://github.com/mowens/cocoapods-links/blob/148611a98f8258862a8b03e11c8fea095544d770/lib/pod/lockfile.rb#L63-L108
train
mowens/cocoapods-links
lib/pod/lockfile.rb
Pod.Lockfile.merge_dependencies
def merge_dependencies(links, before, after) links.each do |link| before_index = find_dependency_index before, link after_index = find_dependency_index after, link unless before_index.nil? || after_index.nil? after[after_index] = before[before_index] end end return after end
ruby
def merge_dependencies(links, before, after) links.each do |link| before_index = find_dependency_index before, link after_index = find_dependency_index after, link unless before_index.nil? || after_index.nil? after[after_index] = before[before_index] end end return after end
[ "def", "merge_dependencies", "(", "links", ",", "before", ",", "after", ")", "links", ".", "each", "do", "|", "link", "|", "before_index", "=", "find_dependency_index", "before", ",", "link", "after_index", "=", "find_dependency_index", "after", ",", "link", "unless", "before_index", ".", "nil?", "||", "after_index", ".", "nil?", "after", "[", "after_index", "]", "=", "before", "[", "before_index", "]", "end", "end", "return", "after", "end" ]
Will merge the DEPENDENCIES of the Podfile.lock before a link and after a link @param links the installed links @param before the DEPENDENCIES in the Podfile.lock before the link occurs @param after the DEPENDENCIES after the link (includes new link that we want to filter out) @returns the merged DEPENDENCIES replacing any links that were added with their previous value
[ "Will", "merge", "the", "DEPENDENCIES", "of", "the", "Podfile", ".", "lock", "before", "a", "link", "and", "after", "a", "link" ]
148611a98f8258862a8b03e11c8fea095544d770
https://github.com/mowens/cocoapods-links/blob/148611a98f8258862a8b03e11c8fea095544d770/lib/pod/lockfile.rb#L157-L166
train
mowens/cocoapods-links
lib/pod/lockfile.rb
Pod.Lockfile.merge_hashes
def merge_hashes(links, before, after) if before.nil? return after end links.each do |link| if before.has_key?(link) after[link] = before[link] else if after.has_key?(link) after.delete(link) end end end return after end
ruby
def merge_hashes(links, before, after) if before.nil? return after end links.each do |link| if before.has_key?(link) after[link] = before[link] else if after.has_key?(link) after.delete(link) end end end return after end
[ "def", "merge_hashes", "(", "links", ",", "before", ",", "after", ")", "if", "before", ".", "nil?", "return", "after", "end", "links", ".", "each", "do", "|", "link", "|", "if", "before", ".", "has_key?", "(", "link", ")", "after", "[", "link", "]", "=", "before", "[", "link", "]", "else", "if", "after", ".", "has_key?", "(", "link", ")", "after", ".", "delete", "(", "link", ")", "end", "end", "end", "return", "after", "end" ]
Will merge the hashes of the Podfile.lock before a link and after a link @param links the installed links @param before the hash in the Podfile.lock before the link occurs @param after the hash after the link (includes new link that we want to filter out) @returns the merged hash replacing any links that were added with their previous value
[ "Will", "merge", "the", "hashes", "of", "the", "Podfile", ".", "lock", "before", "a", "link", "and", "after", "a", "link" ]
148611a98f8258862a8b03e11c8fea095544d770
https://github.com/mowens/cocoapods-links/blob/148611a98f8258862a8b03e11c8fea095544d770/lib/pod/lockfile.rb#L177-L191
train
michelson/chaskiq
app/jobs/chaskiq/ses_sender_job.rb
Chaskiq.SesSenderJob.perform
def perform(campaign, subscription) subscriber = subscription.subscriber return if subscriber.blank? mailer = campaign.prepare_mail_to(subscription) response = mailer.deliver message_id = response.message_id.gsub("@email.amazonses.com", "") campaign.metrics.create( trackable: subscription, action: "deliver", data: message_id) end
ruby
def perform(campaign, subscription) subscriber = subscription.subscriber return if subscriber.blank? mailer = campaign.prepare_mail_to(subscription) response = mailer.deliver message_id = response.message_id.gsub("@email.amazonses.com", "") campaign.metrics.create( trackable: subscription, action: "deliver", data: message_id) end
[ "def", "perform", "(", "campaign", ",", "subscription", ")", "subscriber", "=", "subscription", ".", "subscriber", "return", "if", "subscriber", ".", "blank?", "mailer", "=", "campaign", ".", "prepare_mail_to", "(", "subscription", ")", "response", "=", "mailer", ".", "deliver", "message_id", "=", "response", ".", "message_id", ".", "gsub", "(", "\"@email.amazonses.com\"", ",", "\"\"", ")", "campaign", ".", "metrics", ".", "create", "(", "trackable", ":", "subscription", ",", "action", ":", "\"deliver\"", ",", "data", ":", "message_id", ")", "end" ]
send to ses
[ "send", "to", "ses" ]
1f0d0e6cf7f198e888d421471619bdfdedffa1d2
https://github.com/michelson/chaskiq/blob/1f0d0e6cf7f198e888d421471619bdfdedffa1d2/app/jobs/chaskiq/ses_sender_job.rb#L7-L22
train
michelson/chaskiq
app/models/chaskiq/campaign.rb
Chaskiq.Campaign.clean_inline_css
def clean_inline_css(url) premailer = Premailer.new(url, :adapter => :nokogiri, :escape_url_attributes => false) premailer.to_inline_css.gsub("Drop Content Blocks Here", "") end
ruby
def clean_inline_css(url) premailer = Premailer.new(url, :adapter => :nokogiri, :escape_url_attributes => false) premailer.to_inline_css.gsub("Drop Content Blocks Here", "") end
[ "def", "clean_inline_css", "(", "url", ")", "premailer", "=", "Premailer", ".", "new", "(", "url", ",", ":adapter", "=>", ":nokogiri", ",", ":escape_url_attributes", "=>", "false", ")", "premailer", ".", "to_inline_css", ".", "gsub", "(", "\"Drop Content Blocks Here\"", ",", "\"\"", ")", "end" ]
will remove content blocks text
[ "will", "remove", "content", "blocks", "text" ]
1f0d0e6cf7f198e888d421471619bdfdedffa1d2
https://github.com/michelson/chaskiq/blob/1f0d0e6cf7f198e888d421471619bdfdedffa1d2/app/models/chaskiq/campaign.rb#L97-L100
train
michelson/chaskiq
app/jobs/chaskiq/mail_sender_job.rb
Chaskiq.MailSenderJob.perform
def perform(campaign) campaign.apply_premailer campaign.list.subscriptions.availables.each do |s| campaign.push_notification(s) end end
ruby
def perform(campaign) campaign.apply_premailer campaign.list.subscriptions.availables.each do |s| campaign.push_notification(s) end end
[ "def", "perform", "(", "campaign", ")", "campaign", ".", "apply_premailer", "campaign", ".", "list", ".", "subscriptions", ".", "availables", ".", "each", "do", "|", "s", "|", "campaign", ".", "push_notification", "(", "s", ")", "end", "end" ]
send to all list with state passive & subscribed
[ "send", "to", "all", "list", "with", "state", "passive", "&", "subscribed" ]
1f0d0e6cf7f198e888d421471619bdfdedffa1d2
https://github.com/michelson/chaskiq/blob/1f0d0e6cf7f198e888d421471619bdfdedffa1d2/app/jobs/chaskiq/mail_sender_job.rb#L7-L12
train
2Checkout/2checkout-ruby
lib/twocheckout/option.rb
Twocheckout.Option.update
def update(opts) opts = opts.merge(:option_id => self.option_id) Twocheckout::API.request(:post, 'products/update_option', opts) response = Twocheckout::API.request(:get, 'products/detail_option', opts) Option.new(response['option'][0]) end
ruby
def update(opts) opts = opts.merge(:option_id => self.option_id) Twocheckout::API.request(:post, 'products/update_option', opts) response = Twocheckout::API.request(:get, 'products/detail_option', opts) Option.new(response['option'][0]) end
[ "def", "update", "(", "opts", ")", "opts", "=", "opts", ".", "merge", "(", ":option_id", "=>", "self", ".", "option_id", ")", "Twocheckout", "::", "API", ".", "request", "(", ":post", ",", "'products/update_option'", ",", "opts", ")", "response", "=", "Twocheckout", "::", "API", ".", "request", "(", ":get", ",", "'products/detail_option'", ",", "opts", ")", "Option", ".", "new", "(", "response", "[", "'option'", "]", "[", "0", "]", ")", "end" ]
Updates option and returns a new object
[ "Updates", "option", "and", "returns", "a", "new", "object" ]
e9447ed61ef33c6cbaee7defe9eac0e8f8252509
https://github.com/2Checkout/2checkout-ruby/blob/e9447ed61ef33c6cbaee7defe9eac0e8f8252509/lib/twocheckout/option.rb#L27-L32
train
2Checkout/2checkout-ruby
lib/twocheckout/sale.rb
Twocheckout.Sale.comment
def comment(opts) opts = opts.merge(:sale_id => self.sale_id) Twocheckout::API.request(:post, 'sales/create_comment', opts) end
ruby
def comment(opts) opts = opts.merge(:sale_id => self.sale_id) Twocheckout::API.request(:post, 'sales/create_comment', opts) end
[ "def", "comment", "(", "opts", ")", "opts", "=", "opts", ".", "merge", "(", ":sale_id", "=>", "self", ".", "sale_id", ")", "Twocheckout", "::", "API", ".", "request", "(", ":post", ",", "'sales/create_comment'", ",", "opts", ")", "end" ]
Add a sale comment
[ "Add", "a", "sale", "comment" ]
e9447ed61ef33c6cbaee7defe9eac0e8f8252509
https://github.com/2Checkout/2checkout-ruby/blob/e9447ed61ef33c6cbaee7defe9eac0e8f8252509/lib/twocheckout/sale.rb#L65-L68
train
2Checkout/2checkout-ruby
lib/twocheckout/sale.rb
Twocheckout.Sale.ship
def ship(opts) opts = opts.merge(:sale_id => self.sale_id) Twocheckout::API.request(:post, 'sales/mark_shipped', opts) end
ruby
def ship(opts) opts = opts.merge(:sale_id => self.sale_id) Twocheckout::API.request(:post, 'sales/mark_shipped', opts) end
[ "def", "ship", "(", "opts", ")", "opts", "=", "opts", ".", "merge", "(", ":sale_id", "=>", "self", ".", "sale_id", ")", "Twocheckout", "::", "API", ".", "request", "(", ":post", ",", "'sales/mark_shipped'", ",", "opts", ")", "end" ]
Mark tangible sale as shipped
[ "Mark", "tangible", "sale", "as", "shipped" ]
e9447ed61ef33c6cbaee7defe9eac0e8f8252509
https://github.com/2Checkout/2checkout-ruby/blob/e9447ed61ef33c6cbaee7defe9eac0e8f8252509/lib/twocheckout/sale.rb#L73-L76
train
2Checkout/2checkout-ruby
lib/twocheckout/lineitem.rb
Twocheckout.LineItem.update_recurring!
def update_recurring!(opts) opts = opts.merge(:lineitem_id => self.lineitem_id) Twocheckout::API.request(:post, 'sales/update_lineitem_recurring', opts) end
ruby
def update_recurring!(opts) opts = opts.merge(:lineitem_id => self.lineitem_id) Twocheckout::API.request(:post, 'sales/update_lineitem_recurring', opts) end
[ "def", "update_recurring!", "(", "opts", ")", "opts", "=", "opts", ".", "merge", "(", ":lineitem_id", "=>", "self", ".", "lineitem_id", ")", "Twocheckout", "::", "API", ".", "request", "(", ":post", ",", "'sales/update_lineitem_recurring'", ",", "opts", ")", "end" ]
Provide access to update existing recurring lineitems by allowing to lower the lineitem price and push the recurring billing date forward. This call is not currently documented in the 2Checkout API documentation. POST https://www.2checkout.com/api/sales/update_lineitem_recurring Parameters: * (required) lineitem_id: lineitem_id * (optional) comment: Optional comment added to sale * (optional) shift: days to shift next recurring payment forward * (optional) price: new recurring price (must be lower than previous price or else call will fail) The shift and price parameters are optional, but at least one of them must be provided for the call to be valid. Example Shift Date Next curl -X POST https://www.2checkout.com/api/sales/update_lineitem_recurring -u \ 'username:password' -d 'lineitem_id=1234567890' -d 'shift=7' -H 'Accept: application/json' Example Update Price curl -X POST https://www.2checkout.com/api/sales/update_lineitem_recurring -u \ 'username:password' -d 'lineitem_id=1234567890' -d 'price=1.00' -H 'Accept: application/json' Please note that this method cannot be used on PayPal sales as 2Checkout cannot alter the customer's billing agreement so this call can only update a recurring lineitem on credit card sales.
[ "Provide", "access", "to", "update", "existing", "recurring", "lineitems", "by", "allowing", "to", "lower", "the", "lineitem", "price", "and", "push", "the", "recurring", "billing", "date", "forward", ".", "This", "call", "is", "not", "currently", "documented", "in", "the", "2Checkout", "API", "documentation", "." ]
e9447ed61ef33c6cbaee7defe9eac0e8f8252509
https://github.com/2Checkout/2checkout-ruby/blob/e9447ed61ef33c6cbaee7defe9eac0e8f8252509/lib/twocheckout/lineitem.rb#L45-L48
train
2Checkout/2checkout-ruby
lib/twocheckout/product.rb
Twocheckout.Product.update
def update(opts) opts = opts.merge(:product_id => self.product_id) Twocheckout::API.request(:post, 'products/update_product', opts) response = Twocheckout::API.request(:get, 'products/detail_product', opts) Product.new(response['product']) end
ruby
def update(opts) opts = opts.merge(:product_id => self.product_id) Twocheckout::API.request(:post, 'products/update_product', opts) response = Twocheckout::API.request(:get, 'products/detail_product', opts) Product.new(response['product']) end
[ "def", "update", "(", "opts", ")", "opts", "=", "opts", ".", "merge", "(", ":product_id", "=>", "self", ".", "product_id", ")", "Twocheckout", "::", "API", ".", "request", "(", ":post", ",", "'products/update_product'", ",", "opts", ")", "response", "=", "Twocheckout", "::", "API", ".", "request", "(", ":get", ",", "'products/detail_product'", ",", "opts", ")", "Product", ".", "new", "(", "response", "[", "'product'", "]", ")", "end" ]
Updates product and returns a new Product object
[ "Updates", "product", "and", "returns", "a", "new", "Product", "object" ]
e9447ed61ef33c6cbaee7defe9eac0e8f8252509
https://github.com/2Checkout/2checkout-ruby/blob/e9447ed61ef33c6cbaee7defe9eac0e8f8252509/lib/twocheckout/product.rb#L27-L32
train
browserify-rails/browserify-rails
lib/browserify-rails/browserify_processor.rb
BrowserifyRails.BrowserifyProcessor.commonjs_module?
def commonjs_module? data.to_s.include?("module.exports") || data.present? && data.to_s.match(/(require\(.*\)|import)/) && dependencies.length > 0 end
ruby
def commonjs_module? data.to_s.include?("module.exports") || data.present? && data.to_s.match(/(require\(.*\)|import)/) && dependencies.length > 0 end
[ "def", "commonjs_module?", "data", ".", "to_s", ".", "include?", "(", "\"module.exports\"", ")", "||", "data", ".", "present?", "&&", "data", ".", "to_s", ".", "match", "(", "/", "\\(", "\\)", "/", ")", "&&", "dependencies", ".", "length", ">", "0", "end" ]
Is this a commonjs module? Be here as strict as possible, so that non-commonjs files are not preprocessed.
[ "Is", "this", "a", "commonjs", "module?" ]
fcf33879619bef124e7347c46fd303276073c5d4
https://github.com/browserify-rails/browserify-rails/blob/fcf33879619bef124e7347c46fd303276073c5d4/lib/browserify-rails/browserify_processor.rb#L120-L122
train
browserify-rails/browserify-rails
lib/browserify-rails/browserify_processor.rb
BrowserifyRails.BrowserifyProcessor.evaluate_dependencies
def evaluate_dependencies(asset_paths) return dependencies if config.evaluate_node_modules dependencies.select do |path| path.start_with?(*asset_paths) end end
ruby
def evaluate_dependencies(asset_paths) return dependencies if config.evaluate_node_modules dependencies.select do |path| path.start_with?(*asset_paths) end end
[ "def", "evaluate_dependencies", "(", "asset_paths", ")", "return", "dependencies", "if", "config", ".", "evaluate_node_modules", "dependencies", ".", "select", "do", "|", "path", "|", "path", ".", "start_with?", "(", "asset_paths", ")", "end", "end" ]
This primarily filters out required files from node modules @return [<String>] Paths of dependencies to evaluate
[ "This", "primarily", "filters", "out", "required", "files", "from", "node", "modules" ]
fcf33879619bef124e7347c46fd303276073c5d4
https://github.com/browserify-rails/browserify-rails/blob/fcf33879619bef124e7347c46fd303276073c5d4/lib/browserify-rails/browserify_processor.rb#L131-L137
train
rapid7/nexpose-client
lib/nexpose/manage.rb
Nexpose.Connection.console_command
def console_command(cmd_string) xml = make_xml('ConsoleCommandRequest', {}) cmd = REXML::Element.new('Command') cmd.text = cmd_string xml << cmd r = execute(xml) if r.success r.res.elements.each('//Output') do |out| return out.text.to_s end else false end end
ruby
def console_command(cmd_string) xml = make_xml('ConsoleCommandRequest', {}) cmd = REXML::Element.new('Command') cmd.text = cmd_string xml << cmd r = execute(xml) if r.success r.res.elements.each('//Output') do |out| return out.text.to_s end else false end end
[ "def", "console_command", "(", "cmd_string", ")", "xml", "=", "make_xml", "(", "'ConsoleCommandRequest'", ",", "{", "}", ")", "cmd", "=", "REXML", "::", "Element", ".", "new", "(", "'Command'", ")", "cmd", ".", "text", "=", "cmd_string", "xml", "<<", "cmd", "r", "=", "execute", "(", "xml", ")", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'//Output'", ")", "do", "|", "out", "|", "return", "out", ".", "text", ".", "to_s", "end", "else", "false", "end", "end" ]
Execute an arbitrary console command that is supplied as text via the supplied parameter. Console commands are documented in the administrator's guide. If you use a command that is not listed in the administrator's guide, the application will return the XMLResponse.
[ "Execute", "an", "arbitrary", "console", "command", "that", "is", "supplied", "as", "text", "via", "the", "supplied", "parameter", ".", "Console", "commands", "are", "documented", "in", "the", "administrator", "s", "guide", ".", "If", "you", "use", "a", "command", "that", "is", "not", "listed", "in", "the", "administrator", "s", "guide", "the", "application", "will", "return", "the", "XMLResponse", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/manage.rb#L12-L26
train
rapid7/nexpose-client
lib/nexpose/manage.rb
Nexpose.Connection.system_information
def system_information r = execute(make_xml('SystemInformationRequest', {})) if r.success res = {} r.res.elements.each('//Statistic') do |stat| res[stat.attributes['name'].to_s] = stat.text.to_s end res else false end end
ruby
def system_information r = execute(make_xml('SystemInformationRequest', {})) if r.success res = {} r.res.elements.each('//Statistic') do |stat| res[stat.attributes['name'].to_s] = stat.text.to_s end res else false end end
[ "def", "system_information", "r", "=", "execute", "(", "make_xml", "(", "'SystemInformationRequest'", ",", "{", "}", ")", ")", "if", "r", ".", "success", "res", "=", "{", "}", "r", ".", "res", ".", "elements", ".", "each", "(", "'//Statistic'", ")", "do", "|", "stat", "|", "res", "[", "stat", ".", "attributes", "[", "'name'", "]", ".", "to_s", "]", "=", "stat", ".", "text", ".", "to_s", "end", "res", "else", "false", "end", "end" ]
Obtain system data, such as total RAM, free RAM, total disk space, free disk space, CPU speed, number of CPU cores, and other vital information.
[ "Obtain", "system", "data", "such", "as", "total", "RAM", "free", "RAM", "total", "disk", "space", "free", "disk", "space", "CPU", "speed", "number", "of", "CPU", "cores", "and", "other", "vital", "information", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/manage.rb#L32-L44
train
rapid7/nexpose-client
lib/nexpose/manage.rb
Nexpose.Connection.engine_versions
def engine_versions info = console_command('version engines') versions = [] engines = info.sub('VERSION INFORMATION\n', '').split(/\n\n/) engines.each do |eng| engdata = {} eng.split(/\n/).each do |kv| key, value = kv.split(/:\s*/) key = key.sub('Local Engine ', '').sub('Remote Engine ', '') engdata[key] = value end versions << engdata end versions end
ruby
def engine_versions info = console_command('version engines') versions = [] engines = info.sub('VERSION INFORMATION\n', '').split(/\n\n/) engines.each do |eng| engdata = {} eng.split(/\n/).each do |kv| key, value = kv.split(/:\s*/) key = key.sub('Local Engine ', '').sub('Remote Engine ', '') engdata[key] = value end versions << engdata end versions end
[ "def", "engine_versions", "info", "=", "console_command", "(", "'version engines'", ")", "versions", "=", "[", "]", "engines", "=", "info", ".", "sub", "(", "'VERSION INFORMATION\\n'", ",", "''", ")", ".", "split", "(", "/", "\\n", "\\n", "/", ")", "engines", ".", "each", "do", "|", "eng", "|", "engdata", "=", "{", "}", "eng", ".", "split", "(", "/", "\\n", "/", ")", ".", "each", "do", "|", "kv", "|", "key", ",", "value", "=", "kv", ".", "split", "(", "/", "\\s", "/", ")", "key", "=", "key", ".", "sub", "(", "'Local Engine '", ",", "''", ")", ".", "sub", "(", "'Remote Engine '", ",", "''", ")", "engdata", "[", "key", "]", "=", "value", "end", "versions", "<<", "engdata", "end", "versions", "end" ]
Obtain the version information for each scan engine. Includes Product, Content, and Java versions.
[ "Obtain", "the", "version", "information", "for", "each", "scan", "engine", ".", "Includes", "Product", "Content", "and", "Java", "versions", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/manage.rb#L49-L63
train
rapid7/nexpose-client
lib/nexpose/manage.rb
Nexpose.Connection.send_log
def send_log(uri = 'https://support.rapid7.com') url = REXML::Element.new('URL') url.text = uri tpt = REXML::Element.new('Transport') tpt.add_attribute('protocol', 'https') tpt << url xml = make_xml('SendLogRequest') xml << tpt execute(xml).success end
ruby
def send_log(uri = 'https://support.rapid7.com') url = REXML::Element.new('URL') url.text = uri tpt = REXML::Element.new('Transport') tpt.add_attribute('protocol', 'https') tpt << url xml = make_xml('SendLogRequest') xml << tpt execute(xml).success end
[ "def", "send_log", "(", "uri", "=", "'https://support.rapid7.com'", ")", "url", "=", "REXML", "::", "Element", ".", "new", "(", "'URL'", ")", "url", ".", "text", "=", "uri", "tpt", "=", "REXML", "::", "Element", ".", "new", "(", "'Transport'", ")", "tpt", ".", "add_attribute", "(", "'protocol'", ",", "'https'", ")", "tpt", "<<", "url", "xml", "=", "make_xml", "(", "'SendLogRequest'", ")", "xml", "<<", "tpt", "execute", "(", "xml", ")", ".", "success", "end" ]
Output diagnostic information into log files, zip the files, and encrypt the archive with a PGP public key that is provided as a parameter for the API call. Then upload the archive using HTTPS to a URL that is specified as an API parameter. @param uri Upload server to send the support log package to.
[ "Output", "diagnostic", "information", "into", "log", "files", "zip", "the", "files", "and", "encrypt", "the", "archive", "with", "a", "PGP", "public", "key", "that", "is", "provided", "as", "a", "parameter", "for", "the", "API", "call", ".", "Then", "upload", "the", "archive", "using", "HTTPS", "to", "a", "URL", "that", "is", "specified", "as", "an", "API", "parameter", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/manage.rb#L90-L100
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_ips_with_schedule
def scan_ips_with_schedule(site_id, ip_addresses, schedules) xml = make_xml('SiteDevicesScanRequest', 'site-id' => site_id) hosts = REXML::Element.new('Hosts') ip_addresses.each do |ip| xml.add_element('range', 'from' => ip) end xml.add_element(hosts) scheds = REXML::Element.new('Schedules') schedules.each { |sched| scheds.add_element(sched.as_xml) } xml.add_element(scheds) _scan_ad_hoc_with_schedules(xml) end
ruby
def scan_ips_with_schedule(site_id, ip_addresses, schedules) xml = make_xml('SiteDevicesScanRequest', 'site-id' => site_id) hosts = REXML::Element.new('Hosts') ip_addresses.each do |ip| xml.add_element('range', 'from' => ip) end xml.add_element(hosts) scheds = REXML::Element.new('Schedules') schedules.each { |sched| scheds.add_element(sched.as_xml) } xml.add_element(scheds) _scan_ad_hoc_with_schedules(xml) end
[ "def", "scan_ips_with_schedule", "(", "site_id", ",", "ip_addresses", ",", "schedules", ")", "xml", "=", "make_xml", "(", "'SiteDevicesScanRequest'", ",", "'site-id'", "=>", "site_id", ")", "hosts", "=", "REXML", "::", "Element", ".", "new", "(", "'Hosts'", ")", "ip_addresses", ".", "each", "do", "|", "ip", "|", "xml", ".", "add_element", "(", "'range'", ",", "'from'", "=>", "ip", ")", "end", "xml", ".", "add_element", "(", "hosts", ")", "scheds", "=", "REXML", "::", "Element", ".", "new", "(", "'Schedules'", ")", "schedules", ".", "each", "{", "|", "sched", "|", "scheds", ".", "add_element", "(", "sched", ".", "as_xml", ")", "}", "xml", ".", "add_element", "(", "scheds", ")", "_scan_ad_hoc_with_schedules", "(", "xml", ")", "end" ]
Perform an ad hoc scan of a subset of IP addresses for a site at a specific time. Only IPs from a single site can be submitted per request, and IP addresses must already be included in the site configuration. Method is designed for scanning when the targets are coming from an external source that does not have access to internal identfiers. For example: to_scan = ['192.168.2.1', '192.168.2.107'] nsc.scan_ips(5, to_scan) @param [Fixnum] site_id Site ID that the assets belong to. @param [Array[String]] ip_addresses Array of IP addresses to scan. @return [Status] whether the request was successful
[ "Perform", "an", "ad", "hoc", "scan", "of", "a", "subset", "of", "IP", "addresses", "for", "a", "site", "at", "a", "specific", "time", ".", "Only", "IPs", "from", "a", "single", "site", "can", "be", "submitted", "per", "request", "and", "IP", "addresses", "must", "already", "be", "included", "in", "the", "site", "configuration", ".", "Method", "is", "designed", "for", "scanning", "when", "the", "targets", "are", "coming", "from", "an", "external", "source", "that", "does", "not", "have", "access", "to", "internal", "identfiers", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L157-L169
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_ips
def scan_ips(site_id, ip_addresses) xml = make_xml('SiteDevicesScanRequest', 'site-id' => site_id) hosts = REXML::Element.new('Hosts') ip_addresses.each do |ip| xml.add_element('range', 'from' => ip) end xml.add_element(hosts) _scan_ad_hoc(xml) end
ruby
def scan_ips(site_id, ip_addresses) xml = make_xml('SiteDevicesScanRequest', 'site-id' => site_id) hosts = REXML::Element.new('Hosts') ip_addresses.each do |ip| xml.add_element('range', 'from' => ip) end xml.add_element(hosts) _scan_ad_hoc(xml) end
[ "def", "scan_ips", "(", "site_id", ",", "ip_addresses", ")", "xml", "=", "make_xml", "(", "'SiteDevicesScanRequest'", ",", "'site-id'", "=>", "site_id", ")", "hosts", "=", "REXML", "::", "Element", ".", "new", "(", "'Hosts'", ")", "ip_addresses", ".", "each", "do", "|", "ip", "|", "xml", ".", "add_element", "(", "'range'", ",", "'from'", "=>", "ip", ")", "end", "xml", ".", "add_element", "(", "hosts", ")", "_scan_ad_hoc", "(", "xml", ")", "end" ]
Perform an ad hoc scan of a subset of IP addresses for a site. Only IPs from a single site can be submitted per request, and IP addresses must already be included in the site configuration. Method is designed for scanning when the targets are coming from an external source that does not have access to internal identfiers. For example: to_scan = ['192.168.2.1', '192.168.2.107'] nsc.scan_ips(5, to_scan) @param [Fixnum] site_id Site ID that the assets belong to. @param [Array[String]] ip_addresses Array of IP addresses to scan. @return [Scan] Scan launch information.
[ "Perform", "an", "ad", "hoc", "scan", "of", "a", "subset", "of", "IP", "addresses", "for", "a", "site", ".", "Only", "IPs", "from", "a", "single", "site", "can", "be", "submitted", "per", "request", "and", "IP", "addresses", "must", "already", "be", "included", "in", "the", "site", "configuration", ".", "Method", "is", "designed", "for", "scanning", "when", "the", "targets", "are", "coming", "from", "an", "external", "source", "that", "does", "not", "have", "access", "to", "internal", "identfiers", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L185-L194
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_site
def scan_site(site_id, blackout_override = false) xml = make_xml('SiteScanRequest', 'site-id' => site_id) xml.add_attributes({ 'force' => true }) if blackout_override response = execute(xml) Scan.parse(response.res) if response.success end
ruby
def scan_site(site_id, blackout_override = false) xml = make_xml('SiteScanRequest', 'site-id' => site_id) xml.add_attributes({ 'force' => true }) if blackout_override response = execute(xml) Scan.parse(response.res) if response.success end
[ "def", "scan_site", "(", "site_id", ",", "blackout_override", "=", "false", ")", "xml", "=", "make_xml", "(", "'SiteScanRequest'", ",", "'site-id'", "=>", "site_id", ")", "xml", ".", "add_attributes", "(", "{", "'force'", "=>", "true", "}", ")", "if", "blackout_override", "response", "=", "execute", "(", "xml", ")", "Scan", ".", "parse", "(", "response", ".", "res", ")", "if", "response", ".", "success", "end" ]
Initiate a site scan. @param [Fixnum] site_id Site ID to scan. @param [Boolean] blackout_override Optional. Given suffencent permissions, force bypass blackout and start scan. @return [Scan] Scan launch information.
[ "Initiate", "a", "site", "scan", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L202-L207
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_assets_with_template_and_engine
def scan_assets_with_template_and_engine(site_id, assets, scan_template, scan_engine) uri = "/data/site/#{site_id}/scan" assets.size > 1 ? addresses = assets.join(',') : addresses = assets.first params = { 'addressList' => addresses, 'template' => scan_template, 'scanEngine' => scan_engine } scan_id = AJAX.form_post(self, uri, params) scan_id.to_i end
ruby
def scan_assets_with_template_and_engine(site_id, assets, scan_template, scan_engine) uri = "/data/site/#{site_id}/scan" assets.size > 1 ? addresses = assets.join(',') : addresses = assets.first params = { 'addressList' => addresses, 'template' => scan_template, 'scanEngine' => scan_engine } scan_id = AJAX.form_post(self, uri, params) scan_id.to_i end
[ "def", "scan_assets_with_template_and_engine", "(", "site_id", ",", "assets", ",", "scan_template", ",", "scan_engine", ")", "uri", "=", "\"/data/site/#{site_id}/scan\"", "assets", ".", "size", ">", "1", "?", "addresses", "=", "assets", ".", "join", "(", "','", ")", ":", "addresses", "=", "assets", ".", "first", "params", "=", "{", "'addressList'", "=>", "addresses", ",", "'template'", "=>", "scan_template", ",", "'scanEngine'", "=>", "scan_engine", "}", "scan_id", "=", "AJAX", ".", "form_post", "(", "self", ",", "uri", ",", "params", ")", "scan_id", ".", "to_i", "end" ]
Initiate an ad-hoc scan on a subset of site assets with a specific scan template and scan engine, which may differ from the site's defined scan template and scan engine. @param [Fixnum] site_id Site ID to scan. @param [Array[String]] assets Hostnames and/or IP addresses to scan. @param [String] scan_template The scan template ID. @param [Fixnum] scan_engine The scan engine ID. @return [Fixnum] Scan ID.
[ "Initiate", "an", "ad", "-", "hoc", "scan", "on", "a", "subset", "of", "site", "assets", "with", "a", "specific", "scan", "template", "and", "scan", "engine", "which", "may", "differ", "from", "the", "site", "s", "defined", "scan", "template", "and", "scan", "engine", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L219-L227
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection._append_asset!
def _append_asset!(xml, asset) if asset.is_a? Nexpose::IPRange xml.add_element('range', 'from' => asset.from, 'to' => asset.to) else # Assume HostName host = REXML::Element.new('host') host.text = asset xml.add_element(host) end end
ruby
def _append_asset!(xml, asset) if asset.is_a? Nexpose::IPRange xml.add_element('range', 'from' => asset.from, 'to' => asset.to) else # Assume HostName host = REXML::Element.new('host') host.text = asset xml.add_element(host) end end
[ "def", "_append_asset!", "(", "xml", ",", "asset", ")", "if", "asset", ".", "is_a?", "Nexpose", "::", "IPRange", "xml", ".", "add_element", "(", "'range'", ",", "'from'", "=>", "asset", ".", "from", ",", "'to'", "=>", "asset", ".", "to", ")", "else", "# Assume HostName", "host", "=", "REXML", "::", "Element", ".", "new", "(", "'host'", ")", "host", ".", "text", "=", "asset", "xml", ".", "add_element", "(", "host", ")", "end", "end" ]
Utility method for appending a HostName or IPRange object into an XML object, in preparation for ad hoc scanning. @param [REXML::Document] xml Prepared API call to execute. @param [HostName|IPRange] asset Asset to append to XML.
[ "Utility", "method", "for", "appending", "a", "HostName", "or", "IPRange", "object", "into", "an", "XML", "object", "in", "preparation", "for", "ad", "hoc", "scanning", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L235-L243
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection._scan_ad_hoc
def _scan_ad_hoc(xml) r = execute(xml, '1.1', timeout: 60) Scan.parse(r.res) end
ruby
def _scan_ad_hoc(xml) r = execute(xml, '1.1', timeout: 60) Scan.parse(r.res) end
[ "def", "_scan_ad_hoc", "(", "xml", ")", "r", "=", "execute", "(", "xml", ",", "'1.1'", ",", "timeout", ":", "60", ")", "Scan", ".", "parse", "(", "r", ".", "res", ")", "end" ]
Utility method for executing prepared XML and extracting Scan launch information. @param [REXML::Document] xml Prepared API call to execute. @return [Scan] Scan launch information.
[ "Utility", "method", "for", "executing", "prepared", "XML", "and", "extracting", "Scan", "launch", "information", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L251-L254
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.stop_scan
def stop_scan(scan_id, wait_sec = 0) r = execute(make_xml('ScanStopRequest', 'scan-id' => scan_id)) if r.success so_far = 0 while so_far < wait_sec status = scan_status(scan_id) return status if status == 'stopped' sleep 5 so_far += 5 end end r.success end
ruby
def stop_scan(scan_id, wait_sec = 0) r = execute(make_xml('ScanStopRequest', 'scan-id' => scan_id)) if r.success so_far = 0 while so_far < wait_sec status = scan_status(scan_id) return status if status == 'stopped' sleep 5 so_far += 5 end end r.success end
[ "def", "stop_scan", "(", "scan_id", ",", "wait_sec", "=", "0", ")", "r", "=", "execute", "(", "make_xml", "(", "'ScanStopRequest'", ",", "'scan-id'", "=>", "scan_id", ")", ")", "if", "r", ".", "success", "so_far", "=", "0", "while", "so_far", "<", "wait_sec", "status", "=", "scan_status", "(", "scan_id", ")", "return", "status", "if", "status", "==", "'stopped'", "sleep", "5", "so_far", "+=", "5", "end", "end", "r", ".", "success", "end" ]
Stop a running or paused scan. @param [Fixnum] scan_id ID of the scan to stop. @param [Fixnum] wait_sec Number of seconds to wait for status to be updated.
[ "Stop", "a", "running", "or", "paused", "scan", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L271-L283
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_status
def scan_status(scan_id) r = execute(make_xml('ScanStatusRequest', 'scan-id' => scan_id)) r.success ? r.attributes['status'] : nil end
ruby
def scan_status(scan_id) r = execute(make_xml('ScanStatusRequest', 'scan-id' => scan_id)) r.success ? r.attributes['status'] : nil end
[ "def", "scan_status", "(", "scan_id", ")", "r", "=", "execute", "(", "make_xml", "(", "'ScanStatusRequest'", ",", "'scan-id'", "=>", "scan_id", ")", ")", "r", ".", "success", "?", "r", ".", "attributes", "[", "'status'", "]", ":", "nil", "end" ]
Retrieve the status of a scan. @param [Fixnum] scan_id The scan ID. @return [String] Current status of the scan. See Nexpose::Scan::Status.
[ "Retrieve", "the", "status", "of", "a", "scan", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L290-L293
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.resume_scan
def resume_scan(scan_id) r = execute(make_xml('ScanResumeRequest', 'scan-id' => scan_id), '1.1', timeout: 60) r.success ? r.attributes['success'] == '1' : false end
ruby
def resume_scan(scan_id) r = execute(make_xml('ScanResumeRequest', 'scan-id' => scan_id), '1.1', timeout: 60) r.success ? r.attributes['success'] == '1' : false end
[ "def", "resume_scan", "(", "scan_id", ")", "r", "=", "execute", "(", "make_xml", "(", "'ScanResumeRequest'", ",", "'scan-id'", "=>", "scan_id", ")", ",", "'1.1'", ",", "timeout", ":", "60", ")", "r", ".", "success", "?", "r", ".", "attributes", "[", "'success'", "]", "==", "'1'", ":", "false", "end" ]
Resumes a scan. @param [Fixnum] scan_id The scan ID.
[ "Resumes", "a", "scan", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L299-L302
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.pause_scan
def pause_scan(scan_id) r = execute(make_xml('ScanPauseRequest', 'scan-id' => scan_id)) r.success ? r.attributes['success'] == '1' : false end
ruby
def pause_scan(scan_id) r = execute(make_xml('ScanPauseRequest', 'scan-id' => scan_id)) r.success ? r.attributes['success'] == '1' : false end
[ "def", "pause_scan", "(", "scan_id", ")", "r", "=", "execute", "(", "make_xml", "(", "'ScanPauseRequest'", ",", "'scan-id'", "=>", "scan_id", ")", ")", "r", ".", "success", "?", "r", ".", "attributes", "[", "'success'", "]", "==", "'1'", ":", "false", "end" ]
Pauses a scan. @param [Fixnum] scan_id The scan ID.
[ "Pauses", "a", "scan", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L308-L311
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.activity
def activity r = execute(make_xml('ScanActivityRequest')) res = [] if r.success r.res.elements.each('//ScanSummary') do |scan| res << ScanData.parse(scan) end end res end
ruby
def activity r = execute(make_xml('ScanActivityRequest')) res = [] if r.success r.res.elements.each('//ScanSummary') do |scan| res << ScanData.parse(scan) end end res end
[ "def", "activity", "r", "=", "execute", "(", "make_xml", "(", "'ScanActivityRequest'", ")", ")", "res", "=", "[", "]", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'//ScanSummary'", ")", "do", "|", "scan", "|", "res", "<<", "ScanData", ".", "parse", "(", "scan", ")", "end", "end", "res", "end" ]
Retrieve a list of current scan activities across all Scan Engines managed by Nexpose. This method returns lighter weight objects than scan_activity. @return [Array[ScanData]] Array of ScanData objects associated with each active scan on the engines.
[ "Retrieve", "a", "list", "of", "current", "scan", "activities", "across", "all", "Scan", "Engines", "managed", "by", "Nexpose", ".", "This", "method", "returns", "lighter", "weight", "objects", "than", "scan_activity", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L320-L329
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_activity
def scan_activity r = execute(make_xml('ScanActivityRequest')) res = [] if r.success r.res.elements.each('//ScanSummary') do |scan| res << ScanSummary.parse(scan) end end res end
ruby
def scan_activity r = execute(make_xml('ScanActivityRequest')) res = [] if r.success r.res.elements.each('//ScanSummary') do |scan| res << ScanSummary.parse(scan) end end res end
[ "def", "scan_activity", "r", "=", "execute", "(", "make_xml", "(", "'ScanActivityRequest'", ")", ")", "res", "=", "[", "]", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'//ScanSummary'", ")", "do", "|", "scan", "|", "res", "<<", "ScanSummary", ".", "parse", "(", "scan", ")", "end", "end", "res", "end" ]
Retrieve a list of current scan activities across all Scan Engines managed by Nexpose. @return [Array[ScanSummary]] Array of ScanSummary objects associated with each active scan on the engines.
[ "Retrieve", "a", "list", "of", "current", "scan", "activities", "across", "all", "Scan", "Engines", "managed", "by", "Nexpose", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L337-L346
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.scan_statistics
def scan_statistics(scan_id) r = execute(make_xml('ScanStatisticsRequest', 'scan-id' => scan_id)) if r.success ScanSummary.parse(r.res.elements['//ScanSummary']) else false end end
ruby
def scan_statistics(scan_id) r = execute(make_xml('ScanStatisticsRequest', 'scan-id' => scan_id)) if r.success ScanSummary.parse(r.res.elements['//ScanSummary']) else false end end
[ "def", "scan_statistics", "(", "scan_id", ")", "r", "=", "execute", "(", "make_xml", "(", "'ScanStatisticsRequest'", ",", "'scan-id'", "=>", "scan_id", ")", ")", "if", "r", ".", "success", "ScanSummary", ".", "parse", "(", "r", ".", "res", ".", "elements", "[", "'//ScanSummary'", "]", ")", "else", "false", "end", "end" ]
Get scan statistics, including node and vulnerability breakdowns. @param [Fixnum] scan_id Scan ID to retrieve statistics for. @return [ScanSummary] ScanSummary object providing statistics for the scan.
[ "Get", "scan", "statistics", "including", "node", "and", "vulnerability", "breakdowns", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L353-L360
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.past_scans
def past_scans(limit = nil) uri = '/data/scan/global/scan-history' rows = AJAX.row_pref_of(limit) params = { 'sort' => 'endTime', 'dir' => 'DESC', 'startIndex' => 0 } AJAX.preserving_preference(self, 'global-completed-scans') do data = DataTable._get_json_table(self, uri, params, rows, limit) data.map(&CompletedScan.method(:parse_json)) end end
ruby
def past_scans(limit = nil) uri = '/data/scan/global/scan-history' rows = AJAX.row_pref_of(limit) params = { 'sort' => 'endTime', 'dir' => 'DESC', 'startIndex' => 0 } AJAX.preserving_preference(self, 'global-completed-scans') do data = DataTable._get_json_table(self, uri, params, rows, limit) data.map(&CompletedScan.method(:parse_json)) end end
[ "def", "past_scans", "(", "limit", "=", "nil", ")", "uri", "=", "'/data/scan/global/scan-history'", "rows", "=", "AJAX", ".", "row_pref_of", "(", "limit", ")", "params", "=", "{", "'sort'", "=>", "'endTime'", ",", "'dir'", "=>", "'DESC'", ",", "'startIndex'", "=>", "0", "}", "AJAX", ".", "preserving_preference", "(", "self", ",", "'global-completed-scans'", ")", "do", "data", "=", "DataTable", ".", "_get_json_table", "(", "self", ",", "uri", ",", "params", ",", "rows", ",", "limit", ")", "data", ".", "map", "(", "CompletedScan", ".", "method", "(", ":parse_json", ")", ")", "end", "end" ]
Get a history of past scans for this console, sorted by most recent first. Please note that for consoles with a deep history of scanning, this method could return an excessive amount of data (and take quite a bit of time to retrieve). Consider limiting the amount of data with the optional argument. @param [Fixnum] limit The maximum number of records to return from this call. @return [Array[CompletedScan]] List of completed scans, ordered by most recently completed first.
[ "Get", "a", "history", "of", "past", "scans", "for", "this", "console", "sorted", "by", "most", "recent", "first", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L372-L380
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.paused_scans
def paused_scans(site_id = nil, limit = nil) if site_id uri = "/data/scan/site/#{site_id}?status=active" rows = AJAX.row_pref_of(limit) params = { 'sort' => 'endTime', 'dir' => 'DESC', 'startIndex' => 0 } AJAX.preserving_preference(self, 'site-active-scans') do data = DataTable._get_json_table(self, uri, params, rows, limit).select { |scan| scan['paused'] } data.map(&ActiveScan.method(:parse_json)) end else uri = '/data/site/scans/dyntable.xml?printDocType=0&tableID=siteScansTable&activeOnly=true' data = DataTable._get_dyn_table(self, uri).select { |scan| (scan['Status'].include? 'Paused') } data.map(&ActiveScan.method(:parse_dyntable)) end end
ruby
def paused_scans(site_id = nil, limit = nil) if site_id uri = "/data/scan/site/#{site_id}?status=active" rows = AJAX.row_pref_of(limit) params = { 'sort' => 'endTime', 'dir' => 'DESC', 'startIndex' => 0 } AJAX.preserving_preference(self, 'site-active-scans') do data = DataTable._get_json_table(self, uri, params, rows, limit).select { |scan| scan['paused'] } data.map(&ActiveScan.method(:parse_json)) end else uri = '/data/site/scans/dyntable.xml?printDocType=0&tableID=siteScansTable&activeOnly=true' data = DataTable._get_dyn_table(self, uri).select { |scan| (scan['Status'].include? 'Paused') } data.map(&ActiveScan.method(:parse_dyntable)) end end
[ "def", "paused_scans", "(", "site_id", "=", "nil", ",", "limit", "=", "nil", ")", "if", "site_id", "uri", "=", "\"/data/scan/site/#{site_id}?status=active\"", "rows", "=", "AJAX", ".", "row_pref_of", "(", "limit", ")", "params", "=", "{", "'sort'", "=>", "'endTime'", ",", "'dir'", "=>", "'DESC'", ",", "'startIndex'", "=>", "0", "}", "AJAX", ".", "preserving_preference", "(", "self", ",", "'site-active-scans'", ")", "do", "data", "=", "DataTable", ".", "_get_json_table", "(", "self", ",", "uri", ",", "params", ",", "rows", ",", "limit", ")", ".", "select", "{", "|", "scan", "|", "scan", "[", "'paused'", "]", "}", "data", ".", "map", "(", "ActiveScan", ".", "method", "(", ":parse_json", ")", ")", "end", "else", "uri", "=", "'/data/site/scans/dyntable.xml?printDocType=0&tableID=siteScansTable&activeOnly=true'", "data", "=", "DataTable", ".", "_get_dyn_table", "(", "self", ",", "uri", ")", ".", "select", "{", "|", "scan", "|", "(", "scan", "[", "'Status'", "]", ".", "include?", "'Paused'", ")", "}", "data", ".", "map", "(", "ActiveScan", ".", "method", "(", ":parse_dyntable", ")", ")", "end", "end" ]
Get paused scans. Provide a site ID to get paused scans for a site. With no site ID, all paused scans are returned. @param [Fixnum] site_id Site ID to retrieve paused scans for. @param [Fixnum] limit The maximum number of records to return from this call. @return [Array[ActiveScan]] List of paused scans.
[ "Get", "paused", "scans", ".", "Provide", "a", "site", "ID", "to", "get", "paused", "scans", "for", "a", "site", ".", "With", "no", "site", "ID", "all", "paused", "scans", "are", "returned", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L389-L403
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.export_scan
def export_scan(scan_id, zip_file = nil) http = AJAX.https(self) headers = { 'Cookie' => "nexposeCCSessionID=#{@session_id}", 'Accept-Encoding' => 'identity' } resp = http.get("/data/scan/#{scan_id}/export", headers) case resp when Net::HTTPSuccess if zip_file ::File.open(zip_file, 'wb') { |file| file.write(resp.body) } else resp.body end when Net::HTTPForbidden raise Nexpose::PermissionError.new(resp) else raise Nexpose::APIError.new(resp, "#{resp.class}: Unrecognized response.") end end
ruby
def export_scan(scan_id, zip_file = nil) http = AJAX.https(self) headers = { 'Cookie' => "nexposeCCSessionID=#{@session_id}", 'Accept-Encoding' => 'identity' } resp = http.get("/data/scan/#{scan_id}/export", headers) case resp when Net::HTTPSuccess if zip_file ::File.open(zip_file, 'wb') { |file| file.write(resp.body) } else resp.body end when Net::HTTPForbidden raise Nexpose::PermissionError.new(resp) else raise Nexpose::APIError.new(resp, "#{resp.class}: Unrecognized response.") end end
[ "def", "export_scan", "(", "scan_id", ",", "zip_file", "=", "nil", ")", "http", "=", "AJAX", ".", "https", "(", "self", ")", "headers", "=", "{", "'Cookie'", "=>", "\"nexposeCCSessionID=#{@session_id}\"", ",", "'Accept-Encoding'", "=>", "'identity'", "}", "resp", "=", "http", ".", "get", "(", "\"/data/scan/#{scan_id}/export\"", ",", "headers", ")", "case", "resp", "when", "Net", "::", "HTTPSuccess", "if", "zip_file", "::", "File", ".", "open", "(", "zip_file", ",", "'wb'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "resp", ".", "body", ")", "}", "else", "resp", ".", "body", "end", "when", "Net", "::", "HTTPForbidden", "raise", "Nexpose", "::", "PermissionError", ".", "new", "(", "resp", ")", "else", "raise", "Nexpose", "::", "APIError", ".", "new", "(", "resp", ",", "\"#{resp.class}: Unrecognized response.\"", ")", "end", "end" ]
Export the data associated with a single scan, and optionally store it in a zip-compressed file under the provided name. @param [Fixnum] scan_id Scan ID to remove data for. @param [String] zip_file Filename to export scan data to. @return [Fixnum] On success, returned the number of bytes written to zip_file, if provided. Otherwise, returns raw ZIP binary data.
[ "Export", "the", "data", "associated", "with", "a", "single", "scan", "and", "optionally", "store", "it", "in", "a", "zip", "-", "compressed", "file", "under", "the", "provided", "name", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L413-L430
train
rapid7/nexpose-client
lib/nexpose/scan.rb
Nexpose.Connection.import_scan
def import_scan(site_id, zip_file) data = Rexlite::MIME::Message.new data.add_part(site_id.to_s, nil, nil, 'form-data; name="siteid"') data.add_part(session_id, nil, nil, 'form-data; name="nexposeCCSessionID"') ::File.open(zip_file, 'rb') do |scan| data.add_part(scan.read, 'application/zip', 'binary', "form-data; name=\"scan\"; filename=\"#{zip_file}\"") end post = Net::HTTP::Post.new('/data/scan/import') post.body = data.to_s post.set_content_type('multipart/form-data', boundary: data.bound) # Avoiding AJAX#request, because the data can cause binary dump on error. http = AJAX.https(self) AJAX.headers(self, post) response = http.request(post) case response when Net::HTTPOK response.body.empty? ? response.body : response.body.to_i when Net::HTTPUnauthorized raise Nexpose::PermissionError.new(response) else raise Nexpose::APIError.new(post, response.body) end end
ruby
def import_scan(site_id, zip_file) data = Rexlite::MIME::Message.new data.add_part(site_id.to_s, nil, nil, 'form-data; name="siteid"') data.add_part(session_id, nil, nil, 'form-data; name="nexposeCCSessionID"') ::File.open(zip_file, 'rb') do |scan| data.add_part(scan.read, 'application/zip', 'binary', "form-data; name=\"scan\"; filename=\"#{zip_file}\"") end post = Net::HTTP::Post.new('/data/scan/import') post.body = data.to_s post.set_content_type('multipart/form-data', boundary: data.bound) # Avoiding AJAX#request, because the data can cause binary dump on error. http = AJAX.https(self) AJAX.headers(self, post) response = http.request(post) case response when Net::HTTPOK response.body.empty? ? response.body : response.body.to_i when Net::HTTPUnauthorized raise Nexpose::PermissionError.new(response) else raise Nexpose::APIError.new(post, response.body) end end
[ "def", "import_scan", "(", "site_id", ",", "zip_file", ")", "data", "=", "Rexlite", "::", "MIME", "::", "Message", ".", "new", "data", ".", "add_part", "(", "site_id", ".", "to_s", ",", "nil", ",", "nil", ",", "'form-data; name=\"siteid\"'", ")", "data", ".", "add_part", "(", "session_id", ",", "nil", ",", "nil", ",", "'form-data; name=\"nexposeCCSessionID\"'", ")", "::", "File", ".", "open", "(", "zip_file", ",", "'rb'", ")", "do", "|", "scan", "|", "data", ".", "add_part", "(", "scan", ".", "read", ",", "'application/zip'", ",", "'binary'", ",", "\"form-data; name=\\\"scan\\\"; filename=\\\"#{zip_file}\\\"\"", ")", "end", "post", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "'/data/scan/import'", ")", "post", ".", "body", "=", "data", ".", "to_s", "post", ".", "set_content_type", "(", "'multipart/form-data'", ",", "boundary", ":", "data", ".", "bound", ")", "# Avoiding AJAX#request, because the data can cause binary dump on error.", "http", "=", "AJAX", ".", "https", "(", "self", ")", "AJAX", ".", "headers", "(", "self", ",", "post", ")", "response", "=", "http", ".", "request", "(", "post", ")", "case", "response", "when", "Net", "::", "HTTPOK", "response", ".", "body", ".", "empty?", "?", "response", ".", "body", ":", "response", ".", "body", ".", "to_i", "when", "Net", "::", "HTTPUnauthorized", "raise", "Nexpose", "::", "PermissionError", ".", "new", "(", "response", ")", "else", "raise", "Nexpose", "::", "APIError", ".", "new", "(", "post", ",", "response", ".", "body", ")", "end", "end" ]
Import scan data into a site. This method is designed to work with export_scan to migrate scan data from one console to another. This method will import the data as if run from a local scan engine. Scan importing is restricted to only importing scans in chronological order. It assumes that it is the latest scan for a given site, and will abort if attempting to import an older scan. @param [Fixnum] site_id Site ID of the site to import the scan into. @param [String] zip_file Path to a previously exported scan archive. @return [Fixnum] The scan ID on success.
[ "Import", "scan", "data", "into", "a", "site", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan.rb#L446-L471
train
rapid7/nexpose-client
lib/nexpose/data_table.rb
Nexpose.DataTable._get_json_table
def _get_json_table(console, address, parameters = {}, page_size = 500, records = nil, post = true) parameters['dir'] = 'DESC' parameters['startIndex'] = -1 parameters['results'] = -1 if post request = lambda { |p| AJAX.form_post(console, address, p) } else request = lambda { |p| AJAX.get(console, address.dup, AJAX::CONTENT_TYPE::JSON, p) } end response = request.call(parameters) data = JSON.parse(response) # Don't attept to grab more records than there are. total = data['totalRecords'] return [] if total.zero? total = records.nil? ? total : [records, total].min rows = [] parameters['results'] = page_size while rows.length < total parameters['startIndex'] = rows.length data = JSON.parse(request.call(parameters)) rows.concat data['records'] end rows end
ruby
def _get_json_table(console, address, parameters = {}, page_size = 500, records = nil, post = true) parameters['dir'] = 'DESC' parameters['startIndex'] = -1 parameters['results'] = -1 if post request = lambda { |p| AJAX.form_post(console, address, p) } else request = lambda { |p| AJAX.get(console, address.dup, AJAX::CONTENT_TYPE::JSON, p) } end response = request.call(parameters) data = JSON.parse(response) # Don't attept to grab more records than there are. total = data['totalRecords'] return [] if total.zero? total = records.nil? ? total : [records, total].min rows = [] parameters['results'] = page_size while rows.length < total parameters['startIndex'] = rows.length data = JSON.parse(request.call(parameters)) rows.concat data['records'] end rows end
[ "def", "_get_json_table", "(", "console", ",", "address", ",", "parameters", "=", "{", "}", ",", "page_size", "=", "500", ",", "records", "=", "nil", ",", "post", "=", "true", ")", "parameters", "[", "'dir'", "]", "=", "'DESC'", "parameters", "[", "'startIndex'", "]", "=", "-", "1", "parameters", "[", "'results'", "]", "=", "-", "1", "if", "post", "request", "=", "lambda", "{", "|", "p", "|", "AJAX", ".", "form_post", "(", "console", ",", "address", ",", "p", ")", "}", "else", "request", "=", "lambda", "{", "|", "p", "|", "AJAX", ".", "get", "(", "console", ",", "address", ".", "dup", ",", "AJAX", "::", "CONTENT_TYPE", "::", "JSON", ",", "p", ")", "}", "end", "response", "=", "request", ".", "call", "(", "parameters", ")", "data", "=", "JSON", ".", "parse", "(", "response", ")", "# Don't attept to grab more records than there are.", "total", "=", "data", "[", "'totalRecords'", "]", "return", "[", "]", "if", "total", ".", "zero?", "total", "=", "records", ".", "nil?", "?", "total", ":", "[", "records", ",", "total", "]", ".", "min", "rows", "=", "[", "]", "parameters", "[", "'results'", "]", "=", "page_size", "while", "rows", ".", "length", "<", "total", "parameters", "[", "'startIndex'", "]", "=", "rows", ".", "length", "data", "=", "JSON", ".", "parse", "(", "request", ".", "call", "(", "parameters", ")", ")", "rows", ".", "concat", "data", "[", "'records'", "]", "end", "rows", "end" ]
Helper method to get the YUI tables into a consumable Ruby object. @param [Connection] console API connection to a Nexpose console. @param [String] address Controller address relative to https://host:port @param [Hash] parameters Parameters that need to be sent to the controller The following attributes may need to be provided: 'sort' Column to sort by 'table-id' The ID of the table to get from this controller @param [Fixnum] page_size Number of records to include per page. Value must conform to supported defaults: -1, 10, 25, 50, 100, 500. @param [Fixnum] records number of records to return, gets all if not specified. @param [Boolean] post Whether to use form post or get to retrieve data. @return [Array[Hash]] An array of hashes representing the requested table. Example usage: DataTable._get_json_table(@console, '/data/asset/site', { 'sort' => 'assetName', 'table-id' => 'site-assets', 'siteID' => site_id })
[ "Helper", "method", "to", "get", "the", "YUI", "tables", "into", "a", "consumable", "Ruby", "object", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/data_table.rb#L34-L58
train
rapid7/nexpose-client
lib/nexpose/data_table.rb
Nexpose.DataTable._get_dyn_table
def _get_dyn_table(console, address, payload = nil) if payload response = AJAX.post(console, address, payload) else response = AJAX.get(console, address) end response = REXML::Document.new(response) headers = _dyn_headers(response) rows = _dyn_rows(response) rows.map { |row| Hash[headers.zip(row)] } end
ruby
def _get_dyn_table(console, address, payload = nil) if payload response = AJAX.post(console, address, payload) else response = AJAX.get(console, address) end response = REXML::Document.new(response) headers = _dyn_headers(response) rows = _dyn_rows(response) rows.map { |row| Hash[headers.zip(row)] } end
[ "def", "_get_dyn_table", "(", "console", ",", "address", ",", "payload", "=", "nil", ")", "if", "payload", "response", "=", "AJAX", ".", "post", "(", "console", ",", "address", ",", "payload", ")", "else", "response", "=", "AJAX", ".", "get", "(", "console", ",", "address", ")", "end", "response", "=", "REXML", "::", "Document", ".", "new", "(", "response", ")", "headers", "=", "_dyn_headers", "(", "response", ")", "rows", "=", "_dyn_rows", "(", "response", ")", "rows", ".", "map", "{", "|", "row", "|", "Hash", "[", "headers", ".", "zip", "(", "row", ")", "]", "}", "end" ]
Helper method to get a Dyntable into a consumable Ruby object. @param [Connection] console API connection to a Nexpose console. @param [String] address Tag address with parameters relative to https://host:port @return [Array[Hash]] array of hashes representing the requested table. Example usage: DataTable._get_dyn_table(@console, '/data/asset/os/dyntable.xml?tableID=OSSynopsisTable')
[ "Helper", "method", "to", "get", "a", "Dyntable", "into", "a", "consumable", "Ruby", "object", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/data_table.rb#L70-L81
train
rapid7/nexpose-client
lib/nexpose/data_table.rb
Nexpose.DataTable._dyn_headers
def _dyn_headers(response) headers = [] response.elements.each('DynTable/MetaData/Column') do |header| headers << header.attributes['name'] end headers end
ruby
def _dyn_headers(response) headers = [] response.elements.each('DynTable/MetaData/Column') do |header| headers << header.attributes['name'] end headers end
[ "def", "_dyn_headers", "(", "response", ")", "headers", "=", "[", "]", "response", ".", "elements", ".", "each", "(", "'DynTable/MetaData/Column'", ")", "do", "|", "header", "|", "headers", "<<", "header", ".", "attributes", "[", "'name'", "]", "end", "headers", "end" ]
Parse headers out of a dyntable response.
[ "Parse", "headers", "out", "of", "a", "dyntable", "response", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/data_table.rb#L84-L90
train
rapid7/nexpose-client
lib/nexpose/data_table.rb
Nexpose.DataTable._dyn_rows
def _dyn_rows(response) rows = [] response.elements.each('DynTable/Data/tr') do |row| rows << _dyn_record(row) end rows end
ruby
def _dyn_rows(response) rows = [] response.elements.each('DynTable/Data/tr') do |row| rows << _dyn_record(row) end rows end
[ "def", "_dyn_rows", "(", "response", ")", "rows", "=", "[", "]", "response", ".", "elements", ".", "each", "(", "'DynTable/Data/tr'", ")", "do", "|", "row", "|", "rows", "<<", "_dyn_record", "(", "row", ")", "end", "rows", "end" ]
Parse rows out of a dyntable into an array of values.
[ "Parse", "rows", "out", "of", "a", "dyntable", "into", "an", "array", "of", "values", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/data_table.rb#L93-L99
train
rapid7/nexpose-client
lib/nexpose/data_table.rb
Nexpose.DataTable._dyn_record
def _dyn_record(row) record = [] row.elements.each('td') do |value| record << (value.text ? value.text.to_s : '') end record end
ruby
def _dyn_record(row) record = [] row.elements.each('td') do |value| record << (value.text ? value.text.to_s : '') end record end
[ "def", "_dyn_record", "(", "row", ")", "record", "=", "[", "]", "row", ".", "elements", ".", "each", "(", "'td'", ")", "do", "|", "value", "|", "record", "<<", "(", "value", ".", "text", "?", "value", ".", "text", ".", "to_s", ":", "''", ")", "end", "record", "end" ]
Parse records out of the row of a dyntable.
[ "Parse", "records", "out", "of", "the", "row", "of", "a", "dyntable", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/data_table.rb#L102-L108
train
rapid7/nexpose-client
lib/nexpose/report_template.rb
Nexpose.Connection.list_report_templates
def list_report_templates r = execute(make_xml('ReportTemplateListingRequest', {})) templates = [] if r.success r.res.elements.each('//ReportTemplateSummary') do |template| templates << ReportTemplateSummary.parse(template) end end templates end
ruby
def list_report_templates r = execute(make_xml('ReportTemplateListingRequest', {})) templates = [] if r.success r.res.elements.each('//ReportTemplateSummary') do |template| templates << ReportTemplateSummary.parse(template) end end templates end
[ "def", "list_report_templates", "r", "=", "execute", "(", "make_xml", "(", "'ReportTemplateListingRequest'", ",", "{", "}", ")", ")", "templates", "=", "[", "]", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'//ReportTemplateSummary'", ")", "do", "|", "template", "|", "templates", "<<", "ReportTemplateSummary", ".", "parse", "(", "template", ")", "end", "end", "templates", "end" ]
Provide a list of all report templates the user can access on the Security Console. @return [Array[ReportTemplateSummary]] List of current report templates.
[ "Provide", "a", "list", "of", "all", "report", "templates", "the", "user", "can", "access", "on", "the", "Security", "Console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report_template.rb#L11-L20
train
rapid7/nexpose-client
lib/nexpose/report_template.rb
Nexpose.ReportTemplate.save
def save(connection) xml = %(<ReportTemplateSaveRequest session-id='#{connection.session_id}' scope='#{@scope}'>) xml << to_xml xml << '</ReportTemplateSaveRequest>' response = connection.execute(xml) if response.success @id = response.attributes['template-id'] end end
ruby
def save(connection) xml = %(<ReportTemplateSaveRequest session-id='#{connection.session_id}' scope='#{@scope}'>) xml << to_xml xml << '</ReportTemplateSaveRequest>' response = connection.execute(xml) if response.success @id = response.attributes['template-id'] end end
[ "def", "save", "(", "connection", ")", "xml", "=", "%(<ReportTemplateSaveRequest session-id='#{connection.session_id}' scope='#{@scope}'>)", "xml", "<<", "to_xml", "xml", "<<", "'</ReportTemplateSaveRequest>'", "response", "=", "connection", ".", "execute", "(", "xml", ")", "if", "response", ".", "success", "@id", "=", "response", ".", "attributes", "[", "'template-id'", "]", "end", "end" ]
Save the configuration for a report template.
[ "Save", "the", "configuration", "for", "a", "report", "template", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report_template.rb#L128-L136
train
rapid7/nexpose-client
lib/nexpose/api.rb
Nexpose.APIObject.object_from_hash
def object_from_hash(nsc, hash) hash.each do |k, v| next if k == :url # Do not store self-referential URL. # Store resource URLs separately and create lazy accessors. if v.is_a?(Hash) && v.key?(:url) self.class.send(:define_method, k, proc { |conn = nsc| load_resource(conn, k, v[:url].gsub(/.*\/api/, '/api')) }) else # Convert timestamps. if v.is_a?(String) && v.match(/^\d{8}T\d{6}\.\d{3}/) instance_variable_set("@#{k}", ISO8601.to_time(v)) elsif v.is_a?(Array) && k == :attributes instance_variable_set("@#{k}", v.map { |h| { h[:key] => h[:value] } }) else instance_variable_set("@#{k}", v) end self.class.send(:define_method, k, proc { instance_variable_get("@#{k}") }) end end self end
ruby
def object_from_hash(nsc, hash) hash.each do |k, v| next if k == :url # Do not store self-referential URL. # Store resource URLs separately and create lazy accessors. if v.is_a?(Hash) && v.key?(:url) self.class.send(:define_method, k, proc { |conn = nsc| load_resource(conn, k, v[:url].gsub(/.*\/api/, '/api')) }) else # Convert timestamps. if v.is_a?(String) && v.match(/^\d{8}T\d{6}\.\d{3}/) instance_variable_set("@#{k}", ISO8601.to_time(v)) elsif v.is_a?(Array) && k == :attributes instance_variable_set("@#{k}", v.map { |h| { h[:key] => h[:value] } }) else instance_variable_set("@#{k}", v) end self.class.send(:define_method, k, proc { instance_variable_get("@#{k}") }) end end self end
[ "def", "object_from_hash", "(", "nsc", ",", "hash", ")", "hash", ".", "each", "do", "|", "k", ",", "v", "|", "next", "if", "k", "==", ":url", "# Do not store self-referential URL.", "# Store resource URLs separately and create lazy accessors.", "if", "v", ".", "is_a?", "(", "Hash", ")", "&&", "v", ".", "key?", "(", ":url", ")", "self", ".", "class", ".", "send", "(", ":define_method", ",", "k", ",", "proc", "{", "|", "conn", "=", "nsc", "|", "load_resource", "(", "conn", ",", "k", ",", "v", "[", ":url", "]", ".", "gsub", "(", "/", "\\/", "/", ",", "'/api'", ")", ")", "}", ")", "else", "# Convert timestamps.", "if", "v", ".", "is_a?", "(", "String", ")", "&&", "v", ".", "match", "(", "/", "\\d", "\\d", "\\.", "\\d", "/", ")", "instance_variable_set", "(", "\"@#{k}\"", ",", "ISO8601", ".", "to_time", "(", "v", ")", ")", "elsif", "v", ".", "is_a?", "(", "Array", ")", "&&", "k", "==", ":attributes", "instance_variable_set", "(", "\"@#{k}\"", ",", "v", ".", "map", "{", "|", "h", "|", "{", "h", "[", ":key", "]", "=>", "h", "[", ":value", "]", "}", "}", ")", "else", "instance_variable_set", "(", "\"@#{k}\"", ",", "v", ")", "end", "self", ".", "class", ".", "send", "(", ":define_method", ",", "k", ",", "proc", "{", "instance_variable_get", "(", "\"@#{k}\"", ")", "}", ")", "end", "end", "self", "end" ]
Populate object methods and attributes from a JSON-derived hash. @param [Nexpose::Connection] nsc Active connection to a console. @param [Hash] hash Result of running JSON#parse with the symbolize_names parameter to a 2.0 API response. Pass hash[:resources] if the response is pageable.
[ "Populate", "object", "methods", "and", "attributes", "from", "a", "JSON", "-", "derived", "hash", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/api.rb#L23-L42
train
rapid7/nexpose-client
lib/nexpose/api.rb
Nexpose.APIObject.load_resource
def load_resource(nsc, k, url) obj = class_from_string(k) resp = AJAX.get(nsc, url, AJAX::CONTENT_TYPE::JSON) hash = JSON.parse(resp, symbolize_names: true) if hash.is_a?(Array) resources = hash.map { |e| obj.method(:new).call.object_from_hash(nsc, e) } elsif hash.key?(:resources) resources = hash[:resources].map { |e| obj.method(:new).call.object_from_hash(nsc, e) } else resources = obj.method(:new).call.object_from_hash(nsc, hash) end instance_variable_set("@#{k}", resources) self.class.send(:define_method, k, proc { instance_variable_get("@#{k}") }) resources end
ruby
def load_resource(nsc, k, url) obj = class_from_string(k) resp = AJAX.get(nsc, url, AJAX::CONTENT_TYPE::JSON) hash = JSON.parse(resp, symbolize_names: true) if hash.is_a?(Array) resources = hash.map { |e| obj.method(:new).call.object_from_hash(nsc, e) } elsif hash.key?(:resources) resources = hash[:resources].map { |e| obj.method(:new).call.object_from_hash(nsc, e) } else resources = obj.method(:new).call.object_from_hash(nsc, hash) end instance_variable_set("@#{k}", resources) self.class.send(:define_method, k, proc { instance_variable_get("@#{k}") }) resources end
[ "def", "load_resource", "(", "nsc", ",", "k", ",", "url", ")", "obj", "=", "class_from_string", "(", "k", ")", "resp", "=", "AJAX", ".", "get", "(", "nsc", ",", "url", ",", "AJAX", "::", "CONTENT_TYPE", "::", "JSON", ")", "hash", "=", "JSON", ".", "parse", "(", "resp", ",", "symbolize_names", ":", "true", ")", "if", "hash", ".", "is_a?", "(", "Array", ")", "resources", "=", "hash", ".", "map", "{", "|", "e", "|", "obj", ".", "method", "(", ":new", ")", ".", "call", ".", "object_from_hash", "(", "nsc", ",", "e", ")", "}", "elsif", "hash", ".", "key?", "(", ":resources", ")", "resources", "=", "hash", "[", ":resources", "]", ".", "map", "{", "|", "e", "|", "obj", ".", "method", "(", ":new", ")", ".", "call", ".", "object_from_hash", "(", "nsc", ",", "e", ")", "}", "else", "resources", "=", "obj", ".", "method", "(", ":new", ")", ".", "call", ".", "object_from_hash", "(", "nsc", ",", "hash", ")", "end", "instance_variable_set", "(", "\"@#{k}\"", ",", "resources", ")", "self", ".", "class", ".", "send", "(", ":define_method", ",", "k", ",", "proc", "{", "instance_variable_get", "(", "\"@#{k}\"", ")", "}", ")", "resources", "end" ]
Load a resource from the security console. Once loaded, the value is cached so that it need not be loaded again. @param [Connection] nsc Active connection to the console. @param [Symbol] k Original key name, used to identify the class to load. @param [String] url Truncated URL to use to retrieve the resource. @return [Array[?]] Collection of "k" marshalled object.
[ "Load", "a", "resource", "from", "the", "security", "console", ".", "Once", "loaded", "the", "value", "is", "cached", "so", "that", "it", "need", "not", "be", "loaded", "again", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/api.rb#L54-L68
train
rapid7/nexpose-client
lib/nexpose/api.rb
Nexpose.APIObject.class_from_string
def class_from_string(field) str = field.to_s.split('_').map(&:capitalize!).join str = 'Vulnerability' if str == 'Vulnerabilities' str.chop! if str.end_with?('s') Object.const_get('Nexpose').const_get(str) end
ruby
def class_from_string(field) str = field.to_s.split('_').map(&:capitalize!).join str = 'Vulnerability' if str == 'Vulnerabilities' str.chop! if str.end_with?('s') Object.const_get('Nexpose').const_get(str) end
[ "def", "class_from_string", "(", "field", ")", "str", "=", "field", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize!", ")", ".", "join", "str", "=", "'Vulnerability'", "if", "str", "==", "'Vulnerabilities'", "str", ".", "chop!", "if", "str", ".", "end_with?", "(", "'s'", ")", "Object", ".", "const_get", "(", "'Nexpose'", ")", ".", "const_get", "(", "str", ")", "end" ]
Get the class referred to by a field name. For example, this method will translate a field name like "malware_kits" into to corresponding MalwareKit class. @param [String] field Snake-case name of a field. @return [Class] Class associated with the provided field.
[ "Get", "the", "class", "referred", "to", "by", "a", "field", "name", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/api.rb#L78-L83
train
rapid7/nexpose-client
lib/nexpose/dag.rb
Nexpose.DynamicAssetGroup.save
def save(nsc) # load includes admin users, but save will fail if they are included. admins = nsc.users.select { |u| u.is_admin }.map { |u| u.id } @users.reject! { |id| admins.member? id } params = @id ? { 'entityid' => @id, 'mode' => 'edit' } : { 'entityid' => false, 'mode' => false } uri = AJAX.parameterize_uri('/data/assetGroup/saveAssetGroup', params) data = JSON.parse(AJAX.post(nsc, uri, _to_entity_details, AJAX::CONTENT_TYPE::JSON)) data['response'] == 'success.' end
ruby
def save(nsc) # load includes admin users, but save will fail if they are included. admins = nsc.users.select { |u| u.is_admin }.map { |u| u.id } @users.reject! { |id| admins.member? id } params = @id ? { 'entityid' => @id, 'mode' => 'edit' } : { 'entityid' => false, 'mode' => false } uri = AJAX.parameterize_uri('/data/assetGroup/saveAssetGroup', params) data = JSON.parse(AJAX.post(nsc, uri, _to_entity_details, AJAX::CONTENT_TYPE::JSON)) data['response'] == 'success.' end
[ "def", "save", "(", "nsc", ")", "# load includes admin users, but save will fail if they are included.", "admins", "=", "nsc", ".", "users", ".", "select", "{", "|", "u", "|", "u", ".", "is_admin", "}", ".", "map", "{", "|", "u", "|", "u", ".", "id", "}", "@users", ".", "reject!", "{", "|", "id", "|", "admins", ".", "member?", "id", "}", "params", "=", "@id", "?", "{", "'entityid'", "=>", "@id", ",", "'mode'", "=>", "'edit'", "}", ":", "{", "'entityid'", "=>", "false", ",", "'mode'", "=>", "false", "}", "uri", "=", "AJAX", ".", "parameterize_uri", "(", "'/data/assetGroup/saveAssetGroup'", ",", "params", ")", "data", "=", "JSON", ".", "parse", "(", "AJAX", ".", "post", "(", "nsc", ",", "uri", ",", "_to_entity_details", ",", "AJAX", "::", "CONTENT_TYPE", "::", "JSON", ")", ")", "data", "[", "'response'", "]", "==", "'success.'", "end" ]
Save this dynamic asset group to the Nexpose console. Warning, saving this object does not set the id. It must be retrieved independently. @param [Connection] nsc Connection to a security console. @return [Boolean] Whether the group was successfully saved.
[ "Save", "this", "dynamic", "asset", "group", "to", "the", "Nexpose", "console", ".", "Warning", "saving", "this", "object", "does", "not", "set", "the", "id", ".", "It", "must", "be", "retrieved", "independently", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/dag.rb#L30-L38
train
rapid7/nexpose-client
lib/nexpose/pool.rb
Nexpose.Connection.list_engine_pools
def list_engine_pools response = execute(make_xml('EnginePoolListingRequest'), '1.2') arr = [] if response.success response.res.elements.each('EnginePoolListingResponse/EnginePoolSummary') do |pool| arr << EnginePoolSummary.new(pool.attributes['id'], pool.attributes['name'], pool.attributes['scope']) end end arr end
ruby
def list_engine_pools response = execute(make_xml('EnginePoolListingRequest'), '1.2') arr = [] if response.success response.res.elements.each('EnginePoolListingResponse/EnginePoolSummary') do |pool| arr << EnginePoolSummary.new(pool.attributes['id'], pool.attributes['name'], pool.attributes['scope']) end end arr end
[ "def", "list_engine_pools", "response", "=", "execute", "(", "make_xml", "(", "'EnginePoolListingRequest'", ")", ",", "'1.2'", ")", "arr", "=", "[", "]", "if", "response", ".", "success", "response", ".", "res", ".", "elements", ".", "each", "(", "'EnginePoolListingResponse/EnginePoolSummary'", ")", "do", "|", "pool", "|", "arr", "<<", "EnginePoolSummary", ".", "new", "(", "pool", ".", "attributes", "[", "'id'", "]", ",", "pool", ".", "attributes", "[", "'name'", "]", ",", "pool", ".", "attributes", "[", "'scope'", "]", ")", "end", "end", "arr", "end" ]
Retrieve a list of all Scan Engine Pools managed by the Security Console. @return [Array[EnginePoolSummary]] Array of EnginePoolSummary objects associated with each engine associated with this security console.
[ "Retrieve", "a", "list", "of", "all", "Scan", "Engine", "Pools", "managed", "by", "the", "Security", "Console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/pool.rb#L11-L22
train
rapid7/nexpose-client
lib/nexpose/pool.rb
Nexpose.EnginePool.save
def save(connection) request = @id > 0 ? 'EnginePoolUpdateRequest' : 'EnginePoolCreateRequest' xml = %(<#{request} session-id="#{connection.session_id}">) xml << '<EnginePool' xml << %( id="#{@id}") if @id > 0 xml << %( name="#{@name}" scope="#{@scope}">) @engines.each do |engine| xml << %(<Engine name="#{engine.name}" />) end xml << '</EnginePool>' xml << %(</#{request}>) r = connection.execute(xml, '1.2') if r.success r.res.elements.each(request.gsub('Request', 'Response')) do |v| return @id = v.attributes['id'].to_i end end end
ruby
def save(connection) request = @id > 0 ? 'EnginePoolUpdateRequest' : 'EnginePoolCreateRequest' xml = %(<#{request} session-id="#{connection.session_id}">) xml << '<EnginePool' xml << %( id="#{@id}") if @id > 0 xml << %( name="#{@name}" scope="#{@scope}">) @engines.each do |engine| xml << %(<Engine name="#{engine.name}" />) end xml << '</EnginePool>' xml << %(</#{request}>) r = connection.execute(xml, '1.2') if r.success r.res.elements.each(request.gsub('Request', 'Response')) do |v| return @id = v.attributes['id'].to_i end end end
[ "def", "save", "(", "connection", ")", "request", "=", "@id", ">", "0", "?", "'EnginePoolUpdateRequest'", ":", "'EnginePoolCreateRequest'", "xml", "=", "%(<#{request} session-id=\"#{connection.session_id}\">)", "xml", "<<", "'<EnginePool'", "xml", "<<", "%( id=\"#{@id}\")", "if", "@id", ">", "0", "xml", "<<", "%( name=\"#{@name}\" scope=\"#{@scope}\">)", "@engines", ".", "each", "do", "|", "engine", "|", "xml", "<<", "%(<Engine name=\"#{engine.name}\" />)", "end", "xml", "<<", "'</EnginePool>'", "xml", "<<", "%(</#{request}>)", "r", "=", "connection", ".", "execute", "(", "xml", ",", "'1.2'", ")", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "request", ".", "gsub", "(", "'Request'", ",", "'Response'", ")", ")", "do", "|", "v", "|", "return", "@id", "=", "v", ".", "attributes", "[", "'id'", "]", ".", "to_i", "end", "end", "end" ]
Save an engine pool to a security console. @param [Connection] connection Connection to console where site exists.
[ "Save", "an", "engine", "pool", "to", "a", "security", "console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/pool.rb#L129-L147
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Connection.list_sites
def list_sites r = execute(make_xml('SiteListingRequest')) arr = [] if r.success r.res.elements.each('SiteListingResponse/SiteSummary') do |site| arr << SiteSummary.new(site.attributes['id'].to_i, site.attributes['name'], site.attributes['description'], site.attributes['riskfactor'].to_f, site.attributes['riskscore'].to_f) end end arr end
ruby
def list_sites r = execute(make_xml('SiteListingRequest')) arr = [] if r.success r.res.elements.each('SiteListingResponse/SiteSummary') do |site| arr << SiteSummary.new(site.attributes['id'].to_i, site.attributes['name'], site.attributes['description'], site.attributes['riskfactor'].to_f, site.attributes['riskscore'].to_f) end end arr end
[ "def", "list_sites", "r", "=", "execute", "(", "make_xml", "(", "'SiteListingRequest'", ")", ")", "arr", "=", "[", "]", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'SiteListingResponse/SiteSummary'", ")", "do", "|", "site", "|", "arr", "<<", "SiteSummary", ".", "new", "(", "site", ".", "attributes", "[", "'id'", "]", ".", "to_i", ",", "site", ".", "attributes", "[", "'name'", "]", ",", "site", ".", "attributes", "[", "'description'", "]", ",", "site", ".", "attributes", "[", "'riskfactor'", "]", ".", "to_f", ",", "site", ".", "attributes", "[", "'riskscore'", "]", ".", "to_f", ")", "end", "end", "arr", "end" ]
Retrieve a list of all sites the user is authorized to view or manage. @return [Array[SiteSummary]] Array of SiteSummary objects.
[ "Retrieve", "a", "list", "of", "all", "sites", "the", "user", "is", "authorized", "to", "view", "or", "manage", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L10-L23
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Connection.site_scan_history
def site_scan_history(site_id) r = execute(make_xml('SiteScanHistoryRequest', { 'site-id' => site_id })) scans = [] if r.success r.res.elements.each('SiteScanHistoryResponse/ScanSummary') do |scan_event| scans << ScanSummary.parse(scan_event) end end scans end
ruby
def site_scan_history(site_id) r = execute(make_xml('SiteScanHistoryRequest', { 'site-id' => site_id })) scans = [] if r.success r.res.elements.each('SiteScanHistoryResponse/ScanSummary') do |scan_event| scans << ScanSummary.parse(scan_event) end end scans end
[ "def", "site_scan_history", "(", "site_id", ")", "r", "=", "execute", "(", "make_xml", "(", "'SiteScanHistoryRequest'", ",", "{", "'site-id'", "=>", "site_id", "}", ")", ")", "scans", "=", "[", "]", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'SiteScanHistoryResponse/ScanSummary'", ")", "do", "|", "scan_event", "|", "scans", "<<", "ScanSummary", ".", "parse", "(", "scan_event", ")", "end", "end", "scans", "end" ]
Retrieve a list of all previous scans of the site. @param [FixNum] site_id Site ID to request scan history for. @return [Array[ScanSummary]] Array of ScanSummary objects representing each scan run to date on the site provided.
[ "Retrieve", "a", "list", "of", "all", "previous", "scans", "of", "the", "site", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L42-L51
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Connection.completed_scans
def completed_scans(site_id) table = { 'table-id' => 'site-completed-scans' } data = DataTable._get_json_table(self, "/data/scan/site/#{site_id}", table) data.map(&CompletedScan.method(:parse_json)) end
ruby
def completed_scans(site_id) table = { 'table-id' => 'site-completed-scans' } data = DataTable._get_json_table(self, "/data/scan/site/#{site_id}", table) data.map(&CompletedScan.method(:parse_json)) end
[ "def", "completed_scans", "(", "site_id", ")", "table", "=", "{", "'table-id'", "=>", "'site-completed-scans'", "}", "data", "=", "DataTable", ".", "_get_json_table", "(", "self", ",", "\"/data/scan/site/#{site_id}\"", ",", "table", ")", "data", ".", "map", "(", "CompletedScan", ".", "method", "(", ":parse_json", ")", ")", "end" ]
Retrieve a history of the completed scans for a given site. @param [FixNum] site_id Site ID to find scans for. @return [CompletedScan] details of the completed scans for the site.
[ "Retrieve", "a", "history", "of", "the", "completed", "scans", "for", "a", "given", "site", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L70-L74
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Site.remove_included_ip_range
def remove_included_ip_range(from, to) from_ip = IPAddr.new(from) to_ip = IPAddr.new(to) (from_ip..to_ip) raise 'Invalid IP range specified' if (from_ip..to_ip).to_a.size.zero? @included_scan_targets[:addresses].reject! { |t| t.eql? IPRange.new(from, to) } rescue ArgumentError => e raise "#{e.message} in given IP range" end
ruby
def remove_included_ip_range(from, to) from_ip = IPAddr.new(from) to_ip = IPAddr.new(to) (from_ip..to_ip) raise 'Invalid IP range specified' if (from_ip..to_ip).to_a.size.zero? @included_scan_targets[:addresses].reject! { |t| t.eql? IPRange.new(from, to) } rescue ArgumentError => e raise "#{e.message} in given IP range" end
[ "def", "remove_included_ip_range", "(", "from", ",", "to", ")", "from_ip", "=", "IPAddr", ".", "new", "(", "from", ")", "to_ip", "=", "IPAddr", ".", "new", "(", "to", ")", "(", "from_ip", "..", "to_ip", ")", "raise", "'Invalid IP range specified'", "if", "(", "from_ip", "..", "to_ip", ")", ".", "to_a", ".", "size", ".", "zero?", "@included_scan_targets", "[", ":addresses", "]", ".", "reject!", "{", "|", "t", "|", "t", ".", "eql?", "IPRange", ".", "new", "(", "from", ",", "to", ")", "}", "rescue", "ArgumentError", "=>", "e", "raise", "\"#{e.message} in given IP range\"", "end" ]
Remove assets to this site by IP address range. @param [String] from Beginning IP address of a range. @param [String] to Ending IP address of a range.
[ "Remove", "assets", "to", "this", "site", "by", "IP", "address", "range", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L254-L262
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Site.exclude_ip_range
def exclude_ip_range(from, to) from_ip = IPAddr.new(from) to_ip = IPAddr.new(to) (from_ip..to_ip) raise 'Invalid IP range specified' if (from_ip..to_ip).to_a.size.zero? @excluded_scan_targets[:addresses] << IPRange.new(from, to) rescue ArgumentError => e raise "#{e.message} in given IP range" end
ruby
def exclude_ip_range(from, to) from_ip = IPAddr.new(from) to_ip = IPAddr.new(to) (from_ip..to_ip) raise 'Invalid IP range specified' if (from_ip..to_ip).to_a.size.zero? @excluded_scan_targets[:addresses] << IPRange.new(from, to) rescue ArgumentError => e raise "#{e.message} in given IP range" end
[ "def", "exclude_ip_range", "(", "from", ",", "to", ")", "from_ip", "=", "IPAddr", ".", "new", "(", "from", ")", "to_ip", "=", "IPAddr", ".", "new", "(", "to", ")", "(", "from_ip", "..", "to_ip", ")", "raise", "'Invalid IP range specified'", "if", "(", "from_ip", "..", "to_ip", ")", ".", "to_a", ".", "size", ".", "zero?", "@excluded_scan_targets", "[", ":addresses", "]", "<<", "IPRange", ".", "new", "(", "from", ",", "to", ")", "rescue", "ArgumentError", "=>", "e", "raise", "\"#{e.message} in given IP range\"", "end" ]
Adds assets to this site excluded scan targets by IP address range. @param [String] from Beginning IP address of a range. @param [String] to Ending IP address of a range.
[ "Adds", "assets", "to", "this", "site", "excluded", "scan", "targets", "by", "IP", "address", "range", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L286-L294
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Site.remove_included_asset_group
def remove_included_asset_group(asset_group_id) validate_asset_group(asset_group_id) @included_scan_targets[:asset_groups].reject! { |t| t.eql? asset_group_id.to_i } end
ruby
def remove_included_asset_group(asset_group_id) validate_asset_group(asset_group_id) @included_scan_targets[:asset_groups].reject! { |t| t.eql? asset_group_id.to_i } end
[ "def", "remove_included_asset_group", "(", "asset_group_id", ")", "validate_asset_group", "(", "asset_group_id", ")", "@included_scan_targets", "[", ":asset_groups", "]", ".", "reject!", "{", "|", "t", "|", "t", ".", "eql?", "asset_group_id", ".", "to_i", "}", "end" ]
Adds an asset group ID to this site included scan targets. @param [Integer] asset_group_id Identifier of an assetGroupID.
[ "Adds", "an", "asset", "group", "ID", "to", "this", "site", "included", "scan", "targets", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L341-L344
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Site.remove_excluded_asset_group
def remove_excluded_asset_group(asset_group_id) validate_asset_group(asset_group_id) @excluded_scan_targets[:asset_groups].reject! { |t| t.eql? asset_group_id.to_i } end
ruby
def remove_excluded_asset_group(asset_group_id) validate_asset_group(asset_group_id) @excluded_scan_targets[:asset_groups].reject! { |t| t.eql? asset_group_id.to_i } end
[ "def", "remove_excluded_asset_group", "(", "asset_group_id", ")", "validate_asset_group", "(", "asset_group_id", ")", "@excluded_scan_targets", "[", ":asset_groups", "]", ".", "reject!", "{", "|", "t", "|", "t", ".", "eql?", "asset_group_id", ".", "to_i", "}", "end" ]
Adds an asset group ID to this site excluded scan targets. @param [Integer] asset_group_id Identifier of an assetGroupID.
[ "Adds", "an", "asset", "group", "ID", "to", "this", "site", "excluded", "scan", "targets", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L359-L362
train
rapid7/nexpose-client
lib/nexpose/site.rb
Nexpose.Site.scan
def scan(connection, sync_id = nil, blackout_override = false) xml = REXML::Element.new('SiteScanRequest') xml.add_attributes({ 'session-id' => connection.session_id, 'site-id' => @id, 'sync-id' => sync_id }) xml.add_attributes({ 'force' => true }) if blackout_override response = connection.execute(xml, '1.1', timeout: connection.timeout) Scan.parse(response.res) if response.success end
ruby
def scan(connection, sync_id = nil, blackout_override = false) xml = REXML::Element.new('SiteScanRequest') xml.add_attributes({ 'session-id' => connection.session_id, 'site-id' => @id, 'sync-id' => sync_id }) xml.add_attributes({ 'force' => true }) if blackout_override response = connection.execute(xml, '1.1', timeout: connection.timeout) Scan.parse(response.res) if response.success end
[ "def", "scan", "(", "connection", ",", "sync_id", "=", "nil", ",", "blackout_override", "=", "false", ")", "xml", "=", "REXML", "::", "Element", ".", "new", "(", "'SiteScanRequest'", ")", "xml", ".", "add_attributes", "(", "{", "'session-id'", "=>", "connection", ".", "session_id", ",", "'site-id'", "=>", "@id", ",", "'sync-id'", "=>", "sync_id", "}", ")", "xml", ".", "add_attributes", "(", "{", "'force'", "=>", "true", "}", ")", "if", "blackout_override", "response", "=", "connection", ".", "execute", "(", "xml", ",", "'1.1'", ",", "timeout", ":", "connection", ".", "timeout", ")", "Scan", ".", "parse", "(", "response", ".", "res", ")", "if", "response", ".", "success", "end" ]
Scan this site. @param [Connection] connection Connection to console where scan will be launched. @param [String] sync_id Optional synchronization token. @param [Boolean] blackout_override Optional. Given suffencent permissions, force bypass blackout and start scan. @return [Scan] Scan launch information.
[ "Scan", "this", "site", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/site.rb#L546-L555
train
rapid7/nexpose-client
lib/nexpose/silo_profile.rb
Nexpose.SiloProfile.update
def update(connection) xml = connection.make_xml('SiloProfileUpdateRequest') xml.add_element(as_xml) r = connection.execute(xml, '1.2') @id = r.attributes['silo-profile-id'] if r.success end
ruby
def update(connection) xml = connection.make_xml('SiloProfileUpdateRequest') xml.add_element(as_xml) r = connection.execute(xml, '1.2') @id = r.attributes['silo-profile-id'] if r.success end
[ "def", "update", "(", "connection", ")", "xml", "=", "connection", ".", "make_xml", "(", "'SiloProfileUpdateRequest'", ")", "xml", ".", "add_element", "(", "as_xml", ")", "r", "=", "connection", ".", "execute", "(", "xml", ",", "'1.2'", ")", "@id", "=", "r", ".", "attributes", "[", "'silo-profile-id'", "]", "if", "r", ".", "success", "end" ]
Updates an existing silo profile on a Nexpose console. @param [Connection] connection Connection to console where this silo profile will be saved. @return [String] Silo Profile ID assigned to this configuration, if successful.
[ "Updates", "an", "existing", "silo", "profile", "on", "a", "Nexpose", "console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/silo_profile.rb#L118-L123
train
rapid7/nexpose-client
lib/nexpose/report.rb
Nexpose.Connection.list_reports
def list_reports r = execute(make_xml('ReportListingRequest')) reports = [] if r.success r.res.elements.each('//ReportConfigSummary') do |report| reports << ReportConfigSummary.parse(report) end end reports end
ruby
def list_reports r = execute(make_xml('ReportListingRequest')) reports = [] if r.success r.res.elements.each('//ReportConfigSummary') do |report| reports << ReportConfigSummary.parse(report) end end reports end
[ "def", "list_reports", "r", "=", "execute", "(", "make_xml", "(", "'ReportListingRequest'", ")", ")", "reports", "=", "[", "]", "if", "r", ".", "success", "r", ".", "res", ".", "elements", ".", "each", "(", "'//ReportConfigSummary'", ")", "do", "|", "report", "|", "reports", "<<", "ReportConfigSummary", ".", "parse", "(", "report", ")", "end", "end", "reports", "end" ]
Provide a listing of all report definitions the user can access on the Security Console. @return [Array[ReportConfigSummary]] List of current report configuration.
[ "Provide", "a", "listing", "of", "all", "report", "definitions", "the", "user", "can", "access", "on", "the", "Security", "Console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report.rb#L11-L20
train
rapid7/nexpose-client
lib/nexpose/report.rb
Nexpose.Connection.generate_report
def generate_report(report_id, wait = false) xml = make_xml('ReportGenerateRequest', { 'report-id' => report_id }) response = execute(xml) if response.success response.res.elements.each('//ReportSummary') do |summary| summary = ReportSummary.parse(summary) # If not waiting or the report is finished, return now. return summary unless wait && summary.status == 'Started' end end so_far = 0 while wait summary = last_report(report_id) return summary unless summary.status == 'Started' sleep 5 so_far += 5 if (so_far % 60).zero? puts "Still waiting. Current status: #{summary.status}" end end nil end
ruby
def generate_report(report_id, wait = false) xml = make_xml('ReportGenerateRequest', { 'report-id' => report_id }) response = execute(xml) if response.success response.res.elements.each('//ReportSummary') do |summary| summary = ReportSummary.parse(summary) # If not waiting or the report is finished, return now. return summary unless wait && summary.status == 'Started' end end so_far = 0 while wait summary = last_report(report_id) return summary unless summary.status == 'Started' sleep 5 so_far += 5 if (so_far % 60).zero? puts "Still waiting. Current status: #{summary.status}" end end nil end
[ "def", "generate_report", "(", "report_id", ",", "wait", "=", "false", ")", "xml", "=", "make_xml", "(", "'ReportGenerateRequest'", ",", "{", "'report-id'", "=>", "report_id", "}", ")", "response", "=", "execute", "(", "xml", ")", "if", "response", ".", "success", "response", ".", "res", ".", "elements", ".", "each", "(", "'//ReportSummary'", ")", "do", "|", "summary", "|", "summary", "=", "ReportSummary", ".", "parse", "(", "summary", ")", "# If not waiting or the report is finished, return now.", "return", "summary", "unless", "wait", "&&", "summary", ".", "status", "==", "'Started'", "end", "end", "so_far", "=", "0", "while", "wait", "summary", "=", "last_report", "(", "report_id", ")", "return", "summary", "unless", "summary", ".", "status", "==", "'Started'", "sleep", "5", "so_far", "+=", "5", "if", "(", "so_far", "%", "60", ")", ".", "zero?", "puts", "\"Still waiting. Current status: #{summary.status}\"", "end", "end", "nil", "end" ]
Generate a new report using the specified report definition.
[ "Generate", "a", "new", "report", "using", "the", "specified", "report", "definition", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report.rb#L25-L46
train
rapid7/nexpose-client
lib/nexpose/report.rb
Nexpose.Connection.last_report
def last_report(report_config_id) history = report_history(report_config_id) history.sort { |a, b| b.generated_on <=> a.generated_on }.first end
ruby
def last_report(report_config_id) history = report_history(report_config_id) history.sort { |a, b| b.generated_on <=> a.generated_on }.first end
[ "def", "last_report", "(", "report_config_id", ")", "history", "=", "report_history", "(", "report_config_id", ")", "history", ".", "sort", "{", "|", "a", ",", "b", "|", "b", ".", "generated_on", "<=>", "a", ".", "generated_on", "}", ".", "first", "end" ]
Get details of the last report generated with the specified report id.
[ "Get", "details", "of", "the", "last", "report", "generated", "with", "the", "specified", "report", "id", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report.rb#L56-L59
train
rapid7/nexpose-client
lib/nexpose/report.rb
Nexpose.AdhocReportConfig.generate
def generate(connection, timeout = 300, raw = false) xml = %(<ReportAdhocGenerateRequest session-id="#{connection.session_id}">) xml << to_xml xml << '</ReportAdhocGenerateRequest>' response = connection.execute(xml, '1.1', timeout: timeout, raw: raw) if response.success content_type_response = response.raw_response.header['Content-Type'] if content_type_response =~ /multipart\/mixed;\s*boundary=([^\s]+)/ # Nexpose sends an incorrect boundary format which breaks parsing # e.g., boundary=XXX; charset=XXX # Fix by removing everything from the last semi-colon onward. last_semi_colon_index = content_type_response.index(/;/, content_type_response.index(/boundary/)) content_type_response = content_type_response[0, last_semi_colon_index] data = 'Content-Type: ' + content_type_response + "\r\n\r\n" + response.raw_response_data doc = Rexlite::MIME::Message.new(data) doc.parts.each do |part| if /.*base64.*/ =~ part.header.to_s if @format =~ /(?:ht|x)ml/ if part.header.to_s =~ %r(text/xml) return part.content.unpack('m*')[0].to_s elsif part.header.to_s =~ %r(text/html) return part.content.unpack('m*')[0].to_s end else # text|pdf|csv|rtf return part.content.unpack('m*')[0] end end end end end end
ruby
def generate(connection, timeout = 300, raw = false) xml = %(<ReportAdhocGenerateRequest session-id="#{connection.session_id}">) xml << to_xml xml << '</ReportAdhocGenerateRequest>' response = connection.execute(xml, '1.1', timeout: timeout, raw: raw) if response.success content_type_response = response.raw_response.header['Content-Type'] if content_type_response =~ /multipart\/mixed;\s*boundary=([^\s]+)/ # Nexpose sends an incorrect boundary format which breaks parsing # e.g., boundary=XXX; charset=XXX # Fix by removing everything from the last semi-colon onward. last_semi_colon_index = content_type_response.index(/;/, content_type_response.index(/boundary/)) content_type_response = content_type_response[0, last_semi_colon_index] data = 'Content-Type: ' + content_type_response + "\r\n\r\n" + response.raw_response_data doc = Rexlite::MIME::Message.new(data) doc.parts.each do |part| if /.*base64.*/ =~ part.header.to_s if @format =~ /(?:ht|x)ml/ if part.header.to_s =~ %r(text/xml) return part.content.unpack('m*')[0].to_s elsif part.header.to_s =~ %r(text/html) return part.content.unpack('m*')[0].to_s end else # text|pdf|csv|rtf return part.content.unpack('m*')[0] end end end end end end
[ "def", "generate", "(", "connection", ",", "timeout", "=", "300", ",", "raw", "=", "false", ")", "xml", "=", "%(<ReportAdhocGenerateRequest session-id=\"#{connection.session_id}\">)", "xml", "<<", "to_xml", "xml", "<<", "'</ReportAdhocGenerateRequest>'", "response", "=", "connection", ".", "execute", "(", "xml", ",", "'1.1'", ",", "timeout", ":", "timeout", ",", "raw", ":", "raw", ")", "if", "response", ".", "success", "content_type_response", "=", "response", ".", "raw_response", ".", "header", "[", "'Content-Type'", "]", "if", "content_type_response", "=~", "/", "\\/", "\\s", "\\s", "/", "# Nexpose sends an incorrect boundary format which breaks parsing", "# e.g., boundary=XXX; charset=XXX", "# Fix by removing everything from the last semi-colon onward.", "last_semi_colon_index", "=", "content_type_response", ".", "index", "(", "/", "/", ",", "content_type_response", ".", "index", "(", "/", "/", ")", ")", "content_type_response", "=", "content_type_response", "[", "0", ",", "last_semi_colon_index", "]", "data", "=", "'Content-Type: '", "+", "content_type_response", "+", "\"\\r\\n\\r\\n\"", "+", "response", ".", "raw_response_data", "doc", "=", "Rexlite", "::", "MIME", "::", "Message", ".", "new", "(", "data", ")", "doc", ".", "parts", ".", "each", "do", "|", "part", "|", "if", "/", "/", "=~", "part", ".", "header", ".", "to_s", "if", "@format", "=~", "/", "/", "if", "part", ".", "header", ".", "to_s", "=~", "%r(", ")", "return", "part", ".", "content", ".", "unpack", "(", "'m*'", ")", "[", "0", "]", ".", "to_s", "elsif", "part", ".", "header", ".", "to_s", "=~", "%r(", ")", "return", "part", ".", "content", ".", "unpack", "(", "'m*'", ")", "[", "0", "]", ".", "to_s", "end", "else", "# text|pdf|csv|rtf", "return", "part", ".", "content", ".", "unpack", "(", "'m*'", ")", "[", "0", "]", "end", "end", "end", "end", "end", "end" ]
Generate a report once using a simple configuration. For XML-based reports, only the textual report is returned and not any images. @param [Connection] connection Nexpose connection. @param [Fixnum] timeout How long, in seconds, to wait for the report to generate. Larger reports can take a significant amount of time. @param [Boolean] raw Whether to bypass response parsing an use the raw response. If this option is used, error will only be exposed by examining Connection#response_xml. @return Report in text format except for PDF, which returns binary data.
[ "Generate", "a", "report", "once", "using", "a", "simple", "configuration", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report.rb#L247-L278
train
rapid7/nexpose-client
lib/nexpose/report.rb
Nexpose.ReportConfig.save
def save(connection, generate_now = false) xml = %(<ReportSaveRequest session-id="#{connection.session_id}" generate-now="#{generate_now ? 1 : 0}">) xml << to_xml xml << '</ReportSaveRequest>' response = connection.execute(xml) if response.success @id = response.attributes['reportcfg-id'].to_i end end
ruby
def save(connection, generate_now = false) xml = %(<ReportSaveRequest session-id="#{connection.session_id}" generate-now="#{generate_now ? 1 : 0}">) xml << to_xml xml << '</ReportSaveRequest>' response = connection.execute(xml) if response.success @id = response.attributes['reportcfg-id'].to_i end end
[ "def", "save", "(", "connection", ",", "generate_now", "=", "false", ")", "xml", "=", "%(<ReportSaveRequest session-id=\"#{connection.session_id}\" generate-now=\"#{generate_now ? 1 : 0}\">)", "xml", "<<", "to_xml", "xml", "<<", "'</ReportSaveRequest>'", "response", "=", "connection", ".", "execute", "(", "xml", ")", "if", "response", ".", "success", "@id", "=", "response", ".", "attributes", "[", "'reportcfg-id'", "]", ".", "to_i", "end", "end" ]
Save the configuration of this report definition.
[ "Save", "the", "configuration", "of", "this", "report", "definition", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/report.rb#L334-L342
train
rapid7/nexpose-client
lib/nexpose/vuln.rb
Nexpose.Connection.list_vulns
def list_vulns(full = false) xml = make_xml('VulnerabilityListingRequest') # TODO: Add a flag to do stream parsing of the XML to improve performance. response = execute(xml, '1.2') vulns = [] if response.success response.res.elements.each('VulnerabilityListingResponse/VulnerabilitySummary') do |vuln| if full vulns << XML::VulnerabilitySummary.parse(vuln) else vulns << XML::Vulnerability.new(vuln.attributes['id'], vuln.attributes['title'], vuln.attributes['severity'].to_i) end end end vulns end
ruby
def list_vulns(full = false) xml = make_xml('VulnerabilityListingRequest') # TODO: Add a flag to do stream parsing of the XML to improve performance. response = execute(xml, '1.2') vulns = [] if response.success response.res.elements.each('VulnerabilityListingResponse/VulnerabilitySummary') do |vuln| if full vulns << XML::VulnerabilitySummary.parse(vuln) else vulns << XML::Vulnerability.new(vuln.attributes['id'], vuln.attributes['title'], vuln.attributes['severity'].to_i) end end end vulns end
[ "def", "list_vulns", "(", "full", "=", "false", ")", "xml", "=", "make_xml", "(", "'VulnerabilityListingRequest'", ")", "# TODO: Add a flag to do stream parsing of the XML to improve performance.", "response", "=", "execute", "(", "xml", ",", "'1.2'", ")", "vulns", "=", "[", "]", "if", "response", ".", "success", "response", ".", "res", ".", "elements", ".", "each", "(", "'VulnerabilityListingResponse/VulnerabilitySummary'", ")", "do", "|", "vuln", "|", "if", "full", "vulns", "<<", "XML", "::", "VulnerabilitySummary", ".", "parse", "(", "vuln", ")", "else", "vulns", "<<", "XML", "::", "Vulnerability", ".", "new", "(", "vuln", ".", "attributes", "[", "'id'", "]", ",", "vuln", ".", "attributes", "[", "'title'", "]", ",", "vuln", ".", "attributes", "[", "'severity'", "]", ".", "to_i", ")", "end", "end", "end", "vulns", "end" ]
Retrieve summary details of all vulnerabilities. @param [Boolean] full Whether or not to gather the full summary. Without the flag, only id, title, and severity are returned. It can take twice a long to retrieve full summary information. @return [Array[Vulnerability|VulnerabilitySummary]] Collection of all known vulnerabilities.
[ "Retrieve", "summary", "details", "of", "all", "vulnerabilities", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/vuln.rb#L12-L29
train
rapid7/nexpose-client
lib/nexpose/vuln.rb
Nexpose.Connection.vuln_details
def vuln_details(vuln_id) xml = make_xml('VulnerabilityDetailsRequest', { 'vuln-id' => vuln_id }) response = execute(xml, '1.2') if response.success response.res.elements.each('VulnerabilityDetailsResponse/Vulnerability') do |vuln| return XML::VulnerabilityDetail.parse(vuln) end end end
ruby
def vuln_details(vuln_id) xml = make_xml('VulnerabilityDetailsRequest', { 'vuln-id' => vuln_id }) response = execute(xml, '1.2') if response.success response.res.elements.each('VulnerabilityDetailsResponse/Vulnerability') do |vuln| return XML::VulnerabilityDetail.parse(vuln) end end end
[ "def", "vuln_details", "(", "vuln_id", ")", "xml", "=", "make_xml", "(", "'VulnerabilityDetailsRequest'", ",", "{", "'vuln-id'", "=>", "vuln_id", "}", ")", "response", "=", "execute", "(", "xml", ",", "'1.2'", ")", "if", "response", ".", "success", "response", ".", "res", ".", "elements", ".", "each", "(", "'VulnerabilityDetailsResponse/Vulnerability'", ")", "do", "|", "vuln", "|", "return", "XML", "::", "VulnerabilityDetail", ".", "parse", "(", "vuln", ")", "end", "end", "end" ]
Retrieve details for a vulnerability. @param [String] vuln_id Nexpose vulnerability ID, such as 'windows-duqu-cve-2011-3402'. @return [VulnerabilityDetail] Details of the requested vulnerability.
[ "Retrieve", "details", "for", "a", "vulnerability", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/vuln.rb#L59-L67
train
rapid7/nexpose-client
lib/nexpose/vuln.rb
Nexpose.Connection.find_vuln_check
def find_vuln_check(search_term, partial_words = true, all_words = true) uri = "/data/vulnerability/vulnerabilities/dyntable.xml?tableID=VulnCheckSynopsis&phrase=#{URI.encode(search_term)}&allWords=#{all_words}" data = DataTable._get_dyn_table(self, uri) data.map do |vuln| XML::VulnCheck.new(vuln) end end
ruby
def find_vuln_check(search_term, partial_words = true, all_words = true) uri = "/data/vulnerability/vulnerabilities/dyntable.xml?tableID=VulnCheckSynopsis&phrase=#{URI.encode(search_term)}&allWords=#{all_words}" data = DataTable._get_dyn_table(self, uri) data.map do |vuln| XML::VulnCheck.new(vuln) end end
[ "def", "find_vuln_check", "(", "search_term", ",", "partial_words", "=", "true", ",", "all_words", "=", "true", ")", "uri", "=", "\"/data/vulnerability/vulnerabilities/dyntable.xml?tableID=VulnCheckSynopsis&phrase=#{URI.encode(search_term)}&allWords=#{all_words}\"", "data", "=", "DataTable", ".", "_get_dyn_table", "(", "self", ",", "uri", ")", "data", ".", "map", "do", "|", "vuln", "|", "XML", "::", "VulnCheck", ".", "new", "(", "vuln", ")", "end", "end" ]
Search for Vulnerability Checks. @param [String] search_term Search terms to search for. @param [Boolean] partial_words Allow partial word matches. @param [Boolean] all_words All words must be present. @return [Array[VulnCheck]] List of matching Vulnerability Checks.
[ "Search", "for", "Vulnerability", "Checks", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/vuln.rb#L76-L82
train
rapid7/nexpose-client
lib/nexpose/vuln.rb
Nexpose.Connection.find_vulns_by_date
def find_vulns_by_date(from, to = nil) uri = "/data/vulnerability/synopsis/dyntable.xml?addedMin=#{from}" uri += "&addedMax=#{to}" if to DataTable._get_dyn_table(self, uri).map { |v| VulnSynopsis.new(v) } end
ruby
def find_vulns_by_date(from, to = nil) uri = "/data/vulnerability/synopsis/dyntable.xml?addedMin=#{from}" uri += "&addedMax=#{to}" if to DataTable._get_dyn_table(self, uri).map { |v| VulnSynopsis.new(v) } end
[ "def", "find_vulns_by_date", "(", "from", ",", "to", "=", "nil", ")", "uri", "=", "\"/data/vulnerability/synopsis/dyntable.xml?addedMin=#{from}\"", "uri", "+=", "\"&addedMax=#{to}\"", "if", "to", "DataTable", ".", "_get_dyn_table", "(", "self", ",", "uri", ")", ".", "map", "{", "|", "v", "|", "VulnSynopsis", ".", "new", "(", "v", ")", "}", "end" ]
Find vulnerabilities by date available in Nexpose. This is not the date the original vulnerability was published, but the date the check was made available in Nexpose. @param [String] from Vulnerability publish date in format YYYY-MM-DD. @param [String] to Vulnerability publish date in format YYYY-MM-DD. @return [Array[VulnSynopsis]] List of vulnerabilities published in Nexpose between the provided dates.
[ "Find", "vulnerabilities", "by", "date", "available", "in", "Nexpose", ".", "This", "is", "not", "the", "date", "the", "original", "vulnerability", "was", "published", "but", "the", "date", "the", "check", "was", "made", "available", "in", "Nexpose", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/vuln.rb#L93-L97
train
rapid7/nexpose-client
lib/nexpose/ticket.rb
Nexpose.Connection.delete_tickets
def delete_tickets(tickets) # TODO: Take Ticket objects, too, and pull out IDs. xml = make_xml('TicketDeleteRequest') tickets.each do |id| xml.add_element('Ticket', { 'id' => id }) end (execute xml, '1.2').success end
ruby
def delete_tickets(tickets) # TODO: Take Ticket objects, too, and pull out IDs. xml = make_xml('TicketDeleteRequest') tickets.each do |id| xml.add_element('Ticket', { 'id' => id }) end (execute xml, '1.2').success end
[ "def", "delete_tickets", "(", "tickets", ")", "# TODO: Take Ticket objects, too, and pull out IDs.", "xml", "=", "make_xml", "(", "'TicketDeleteRequest'", ")", "tickets", ".", "each", "do", "|", "id", "|", "xml", ".", "add_element", "(", "'Ticket'", ",", "{", "'id'", "=>", "id", "}", ")", "end", "(", "execute", "xml", ",", "'1.2'", ")", ".", "success", "end" ]
Deletes a Nexpose ticket. @param [Array[Fixnum]] tickets Array of unique IDs of tickets to delete. @return [Boolean] Whether or not the ticket deletions succeeded.
[ "Deletes", "a", "Nexpose", "ticket", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/ticket.rb#L36-L44
train
rapid7/nexpose-client
lib/nexpose/ticket.rb
Nexpose.Ticket.save
def save(connection) xml = connection.make_xml('TicketCreateRequest') xml.add_element(to_xml) response = connection.execute(xml, '1.2') @id = response.attributes['id'].to_i if response.success end
ruby
def save(connection) xml = connection.make_xml('TicketCreateRequest') xml.add_element(to_xml) response = connection.execute(xml, '1.2') @id = response.attributes['id'].to_i if response.success end
[ "def", "save", "(", "connection", ")", "xml", "=", "connection", ".", "make_xml", "(", "'TicketCreateRequest'", ")", "xml", ".", "add_element", "(", "to_xml", ")", "response", "=", "connection", ".", "execute", "(", "xml", ",", "'1.2'", ")", "@id", "=", "response", ".", "attributes", "[", "'id'", "]", ".", "to_i", "if", "response", ".", "success", "end" ]
Save this ticket to a Nexpose console. @param [Connection] connection Connection to console where ticket exists. @return [Fixnum] Unique ticket ID assigned to this ticket.
[ "Save", "this", "ticket", "to", "a", "Nexpose", "console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/ticket.rb#L147-L153
train
rapid7/nexpose-client
lib/nexpose/console.rb
Nexpose.Console.save
def save(connection) nsc = REXML::XPath.first(@xml, 'NeXposeSecurityConsole') nsc.attributes['scanThreadsLimit'] = @scan_threads_limit.to_i nsc.attributes['realtimeIntegration'] = @incremental_scan_results ? '1' : '0' web_server = REXML::XPath.first(nsc, 'WebServer') web_server.attributes['sessionTimeout'] = @session_timeout.to_i response = REXML::Document.new(Nexpose::AJAX.post(connection, '/data/admin/config/nsc', @xml)) saved = REXML::XPath.first(response, 'SaveConfig') saved.attributes['success'] == '1' end
ruby
def save(connection) nsc = REXML::XPath.first(@xml, 'NeXposeSecurityConsole') nsc.attributes['scanThreadsLimit'] = @scan_threads_limit.to_i nsc.attributes['realtimeIntegration'] = @incremental_scan_results ? '1' : '0' web_server = REXML::XPath.first(nsc, 'WebServer') web_server.attributes['sessionTimeout'] = @session_timeout.to_i response = REXML::Document.new(Nexpose::AJAX.post(connection, '/data/admin/config/nsc', @xml)) saved = REXML::XPath.first(response, 'SaveConfig') saved.attributes['success'] == '1' end
[ "def", "save", "(", "connection", ")", "nsc", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'NeXposeSecurityConsole'", ")", "nsc", ".", "attributes", "[", "'scanThreadsLimit'", "]", "=", "@scan_threads_limit", ".", "to_i", "nsc", ".", "attributes", "[", "'realtimeIntegration'", "]", "=", "@incremental_scan_results", "?", "'1'", ":", "'0'", "web_server", "=", "REXML", "::", "XPath", ".", "first", "(", "nsc", ",", "'WebServer'", ")", "web_server", ".", "attributes", "[", "'sessionTimeout'", "]", "=", "@session_timeout", ".", "to_i", "response", "=", "REXML", "::", "Document", ".", "new", "(", "Nexpose", "::", "AJAX", ".", "post", "(", "connection", ",", "'/data/admin/config/nsc'", ",", "@xml", ")", ")", "saved", "=", "REXML", "::", "XPath", ".", "first", "(", "response", ",", "'SaveConfig'", ")", "saved", ".", "attributes", "[", "'success'", "]", "==", "'1'", "end" ]
Save modifications to the Nexpose security console. @param [Connection] connection Nexpose connection. @return [Boolean] true if configuration successfully saved.
[ "Save", "modifications", "to", "the", "Nexpose", "security", "console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/console.rb#L58-L69
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.Connection.list_scan_templates
def list_scan_templates templates = JSON.parse(AJAX.get(self, '/api/2.0/scan_templates')) templates['resources'].map { |t| ScanTemplateSummary.new(t) } end
ruby
def list_scan_templates templates = JSON.parse(AJAX.get(self, '/api/2.0/scan_templates')) templates['resources'].map { |t| ScanTemplateSummary.new(t) } end
[ "def", "list_scan_templates", "templates", "=", "JSON", ".", "parse", "(", "AJAX", ".", "get", "(", "self", ",", "'/api/2.0/scan_templates'", ")", ")", "templates", "[", "'resources'", "]", ".", "map", "{", "|", "t", "|", "ScanTemplateSummary", ".", "new", "(", "t", ")", "}", "end" ]
List the scan templates currently configured on the console. @return [Array[ScanTemplateSummary]] list of scan template summary objects.
[ "List", "the", "scan", "templates", "currently", "configured", "on", "the", "console", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L9-L12
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.name=
def name=(name) desc = REXML::XPath.first(@xml, 'ScanTemplate/templateDescription') if desc desc.attributes['title'] = replace_entities(name) else root = REXML::XPath.first(xml, 'ScanTemplate') desc = REXML::Element.new('templateDescription') desc.add_attribute('title', name) root.add_element(desc) end end
ruby
def name=(name) desc = REXML::XPath.first(@xml, 'ScanTemplate/templateDescription') if desc desc.attributes['title'] = replace_entities(name) else root = REXML::XPath.first(xml, 'ScanTemplate') desc = REXML::Element.new('templateDescription') desc.add_attribute('title', name) root.add_element(desc) end end
[ "def", "name", "=", "(", "name", ")", "desc", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/templateDescription'", ")", "if", "desc", "desc", ".", "attributes", "[", "'title'", "]", "=", "replace_entities", "(", "name", ")", "else", "root", "=", "REXML", "::", "XPath", ".", "first", "(", "xml", ",", "'ScanTemplate'", ")", "desc", "=", "REXML", "::", "Element", ".", "new", "(", "'templateDescription'", ")", "desc", ".", "add_attribute", "(", "'title'", ",", "name", ")", "root", ".", "add_element", "(", "desc", ")", "end", "end" ]
Assign name to this scan template. Required attribute. @param [String] name Title to assign.
[ "Assign", "name", "to", "this", "scan", "template", ".", "Required", "attribute", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L78-L88
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.description=
def description=(description) desc = REXML::XPath.first(@xml, 'ScanTemplate/templateDescription') if desc desc.text = replace_entities(description) else root = REXML::XPath.first(xml, 'ScanTemplate') desc = REXML::Element.new('templateDescription') desc.add_text(description) root.add_element(desc) end end
ruby
def description=(description) desc = REXML::XPath.first(@xml, 'ScanTemplate/templateDescription') if desc desc.text = replace_entities(description) else root = REXML::XPath.first(xml, 'ScanTemplate') desc = REXML::Element.new('templateDescription') desc.add_text(description) root.add_element(desc) end end
[ "def", "description", "=", "(", "description", ")", "desc", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/templateDescription'", ")", "if", "desc", "desc", ".", "text", "=", "replace_entities", "(", "description", ")", "else", "root", "=", "REXML", "::", "XPath", ".", "first", "(", "xml", ",", "'ScanTemplate'", ")", "desc", "=", "REXML", "::", "Element", ".", "new", "(", "'templateDescription'", ")", "desc", ".", "add_text", "(", "description", ")", "root", ".", "add_element", "(", "desc", ")", "end", "end" ]
Assign a description to this scan template. Require attribute. @param [String] description Description of the scan template.
[ "Assign", "a", "description", "to", "this", "scan", "template", ".", "Require", "attribute", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L98-L108
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.scan_threads=
def scan_threads=(threads) scan_threads = REXML::XPath.first(@xml, 'ScanTemplate/General/scanThreads') scan_threads.text = threads.to_s end
ruby
def scan_threads=(threads) scan_threads = REXML::XPath.first(@xml, 'ScanTemplate/General/scanThreads') scan_threads.text = threads.to_s end
[ "def", "scan_threads", "=", "(", "threads", ")", "scan_threads", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/General/scanThreads'", ")", "scan_threads", ".", "text", "=", "threads", ".", "to_s", "end" ]
Adjust the number of threads to use per scan engine for this template @param [Integer] threads the number of threads to use per engine
[ "Adjust", "the", "number", "of", "threads", "to", "use", "per", "scan", "engine", "for", "this", "template" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L167-L170
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.host_threads=
def host_threads=(threads) host_threads = REXML::XPath.first(@xml, 'ScanTemplate/General/hostThreads') host_threads.text = threads.to_s end
ruby
def host_threads=(threads) host_threads = REXML::XPath.first(@xml, 'ScanTemplate/General/hostThreads') host_threads.text = threads.to_s end
[ "def", "host_threads", "=", "(", "threads", ")", "host_threads", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/General/hostThreads'", ")", "host_threads", ".", "text", "=", "threads", ".", "to_s", "end" ]
Adjust the number of threads to use per asset for this template @param [Integer] threads the number of threads to use per asset
[ "Adjust", "the", "number", "of", "threads", "to", "use", "per", "asset", "for", "this", "template" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L174-L177
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.tcp_device_discovery_ports=
def tcp_device_discovery_ports=(ports) tcp = REXML::XPath.first(@xml, 'ScanTemplate/DeviceDiscovery/CheckHosts/TCPHostCheck') REXML::XPath.first(tcp, './portList').text = ports.join(',') end
ruby
def tcp_device_discovery_ports=(ports) tcp = REXML::XPath.first(@xml, 'ScanTemplate/DeviceDiscovery/CheckHosts/TCPHostCheck') REXML::XPath.first(tcp, './portList').text = ports.join(',') end
[ "def", "tcp_device_discovery_ports", "=", "(", "ports", ")", "tcp", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/DeviceDiscovery/CheckHosts/TCPHostCheck'", ")", "REXML", "::", "XPath", ".", "first", "(", "tcp", ",", "'./portList'", ")", ".", "text", "=", "ports", ".", "join", "(", "','", ")", "end" ]
Set custom TCP ports to scan for device discovery @param [Array] ports Ports to scan for device discovery
[ "Set", "custom", "TCP", "ports", "to", "scan", "for", "device", "discovery" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L210-L213
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.udp_device_discovery_ports=
def udp_device_discovery_ports=(ports) udp = REXML::XPath.first(@xml, 'ScanTemplate/DeviceDiscovery/CheckHosts/UDPHostCheck') REXML::XPath.first(udp, './portList').text = ports.join(',') end
ruby
def udp_device_discovery_ports=(ports) udp = REXML::XPath.first(@xml, 'ScanTemplate/DeviceDiscovery/CheckHosts/UDPHostCheck') REXML::XPath.first(udp, './portList').text = ports.join(',') end
[ "def", "udp_device_discovery_ports", "=", "(", "ports", ")", "udp", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/DeviceDiscovery/CheckHosts/UDPHostCheck'", ")", "REXML", "::", "XPath", ".", "first", "(", "udp", ",", "'./portList'", ")", ".", "text", "=", "ports", ".", "join", "(", "','", ")", "end" ]
Set custom UDP ports to scan for UDP device discovery @param [Array] ports Ports to scan for UDP device discovery
[ "Set", "custom", "UDP", "ports", "to", "scan", "for", "UDP", "device", "discovery" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L224-L227
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.tcp_service_discovery_ports=
def tcp_service_discovery_ports=(ports) service_ports = REXML::XPath.first(@xml, 'ScanTemplate/ServiceDiscovery/TCPPortScan') service_ports.attributes['mode'] = 'custom' service_ports.attributes['method'] = 'syn' REXML::XPath.first(service_ports, './portList').text = ports.join(',') end
ruby
def tcp_service_discovery_ports=(ports) service_ports = REXML::XPath.first(@xml, 'ScanTemplate/ServiceDiscovery/TCPPortScan') service_ports.attributes['mode'] = 'custom' service_ports.attributes['method'] = 'syn' REXML::XPath.first(service_ports, './portList').text = ports.join(',') end
[ "def", "tcp_service_discovery_ports", "=", "(", "ports", ")", "service_ports", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/ServiceDiscovery/TCPPortScan'", ")", "service_ports", ".", "attributes", "[", "'mode'", "]", "=", "'custom'", "service_ports", ".", "attributes", "[", "'method'", "]", "=", "'syn'", "REXML", "::", "XPath", ".", "first", "(", "service_ports", ",", "'./portList'", ")", ".", "text", "=", "ports", ".", "join", "(", "','", ")", "end" ]
Set custom TCP ports to scan for TCP service discovery @param [Array] ports Ports to scan for TCP service discovery
[ "Set", "custom", "TCP", "ports", "to", "scan", "for", "TCP", "service", "discovery" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L238-L243
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.exclude_tcp_service_discovery_ports=
def exclude_tcp_service_discovery_ports=(ports) service_ports = REXML::XPath.first(@xml, 'ScanTemplate/ServiceDiscovery/ExcludedTCPPortScan') REXML::XPath.first(service_ports, './portList').text = ports.join(',') end
ruby
def exclude_tcp_service_discovery_ports=(ports) service_ports = REXML::XPath.first(@xml, 'ScanTemplate/ServiceDiscovery/ExcludedTCPPortScan') REXML::XPath.first(service_ports, './portList').text = ports.join(',') end
[ "def", "exclude_tcp_service_discovery_ports", "=", "(", "ports", ")", "service_ports", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/ServiceDiscovery/ExcludedTCPPortScan'", ")", "REXML", "::", "XPath", ".", "first", "(", "service_ports", ",", "'./portList'", ")", ".", "text", "=", "ports", ".", "join", "(", "','", ")", "end" ]
Exclude TCP ports during TCP service discovery @param [Array] ports TCP ports to exclude from TCP service discovery
[ "Exclude", "TCP", "ports", "during", "TCP", "service", "discovery" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L247-L250
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.exclude_udp_service_discovery_ports=
def exclude_udp_service_discovery_ports=(ports) service_ports = REXML::XPath.first(@xml, 'ScanTemplate/ServiceDiscovery/ExcludedUDPPortScan') REXML::XPath.first(service_ports, './portList').text = ports.join(',') end
ruby
def exclude_udp_service_discovery_ports=(ports) service_ports = REXML::XPath.first(@xml, 'ScanTemplate/ServiceDiscovery/ExcludedUDPPortScan') REXML::XPath.first(service_ports, './portList').text = ports.join(',') end
[ "def", "exclude_udp_service_discovery_ports", "=", "(", "ports", ")", "service_ports", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'ScanTemplate/ServiceDiscovery/ExcludedUDPPortScan'", ")", "REXML", "::", "XPath", ".", "first", "(", "service_ports", ",", "'./portList'", ")", ".", "text", "=", "ports", ".", "join", "(", "','", ")", "end" ]
Exclude UDP ports when performing UDP service discovery @param [Array] ports UDP ports to exclude from UDP service discovery
[ "Exclude", "UDP", "ports", "when", "performing", "UDP", "service", "discovery" ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L262-L265
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.enabled_vuln_checks
def enabled_vuln_checks checks = REXML::XPath.first(@xml, '//VulnerabilityChecks/Enabled') checks ? checks.elements.to_a('Check').map { |c| c.attributes['id'] } : [] end
ruby
def enabled_vuln_checks checks = REXML::XPath.first(@xml, '//VulnerabilityChecks/Enabled') checks ? checks.elements.to_a('Check').map { |c| c.attributes['id'] } : [] end
[ "def", "enabled_vuln_checks", "checks", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'//VulnerabilityChecks/Enabled'", ")", "checks", "?", "checks", ".", "elements", ".", "to_a", "(", "'Check'", ")", ".", "map", "{", "|", "c", "|", "c", ".", "attributes", "[", "'id'", "]", "}", ":", "[", "]", "end" ]
Get a list of the individual vuln checks enabled for this scan template. @return [Array[String]] List of enabled vulnerability checks.
[ "Get", "a", "list", "of", "the", "individual", "vuln", "checks", "enabled", "for", "this", "scan", "template", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L425-L428
train
rapid7/nexpose-client
lib/nexpose/scan_template.rb
Nexpose.ScanTemplate.enable_vuln_check
def enable_vuln_check(check_id) checks = REXML::XPath.first(@xml, '//VulnerabilityChecks') checks.elements.delete("Disabled/Check[@id='#{check_id}']") enabled_checks = checks.elements['Enabled'] || checks.add_element('Enabled') enabled_checks.add_element('Check', { 'id' => check_id }) end
ruby
def enable_vuln_check(check_id) checks = REXML::XPath.first(@xml, '//VulnerabilityChecks') checks.elements.delete("Disabled/Check[@id='#{check_id}']") enabled_checks = checks.elements['Enabled'] || checks.add_element('Enabled') enabled_checks.add_element('Check', { 'id' => check_id }) end
[ "def", "enable_vuln_check", "(", "check_id", ")", "checks", "=", "REXML", "::", "XPath", ".", "first", "(", "@xml", ",", "'//VulnerabilityChecks'", ")", "checks", ".", "elements", ".", "delete", "(", "\"Disabled/Check[@id='#{check_id}']\"", ")", "enabled_checks", "=", "checks", ".", "elements", "[", "'Enabled'", "]", "||", "checks", ".", "add_element", "(", "'Enabled'", ")", "enabled_checks", ".", "add_element", "(", "'Check'", ",", "{", "'id'", "=>", "check_id", "}", ")", "end" ]
Enable individual check for this template. @param [String] check_id Unique identifier of vuln check.
[ "Enable", "individual", "check", "for", "this", "template", "." ]
933fc8c0c85ba11d3e17db1d7f4542816f400d71
https://github.com/rapid7/nexpose-client/blob/933fc8c0c85ba11d3e17db1d7f4542816f400d71/lib/nexpose/scan_template.rb#L443-L448
train