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
WeAreFarmGeek/diplomat
lib/diplomat/query.rb
Diplomat.Query.create
def create(definition, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil @raw = send_post_request(@conn, ['/v1/query'], options, definition, custom_params) parse_body rescue Faraday::ClientError raise Diplomat::QueryAlreadyExists end
ruby
def create(definition, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil @raw = send_post_request(@conn, ['/v1/query'], options, definition, custom_params) parse_body rescue Faraday::ClientError raise Diplomat::QueryAlreadyExists end
[ "def", "create", "(", "definition", ",", "options", "=", "{", "}", ")", "custom_params", "=", "options", "[", ":dc", "]", "?", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", ":", "nil", "@raw", "=", "send_post_request", "(", "@conn", ",", "[", "'/v1/query'", "]", ",", "options", ",", "definition", ",", "custom_params", ")", "parse_body", "rescue", "Faraday", "::", "ClientError", "raise", "Diplomat", "::", "QueryAlreadyExists", "end" ]
Create a prepared query or prepared query template @param definition [Hash] Hash containing definition of prepared query @param options [Hash] :dc Consul datacenter to query @return [String] the ID of the prepared query created
[ "Create", "a", "prepared", "query", "or", "prepared", "query", "template" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/query.rb#L29-L35
train
WeAreFarmGeek/diplomat
lib/diplomat/query.rb
Diplomat.Query.delete
def delete(key, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil ret = send_delete_request(@conn, ["/v1/query/#{key}"], options, custom_params) ret.status == 200 end
ruby
def delete(key, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil ret = send_delete_request(@conn, ["/v1/query/#{key}"], options, custom_params) ret.status == 200 end
[ "def", "delete", "(", "key", ",", "options", "=", "{", "}", ")", "custom_params", "=", "options", "[", ":dc", "]", "?", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", ":", "nil", "ret", "=", "send_delete_request", "(", "@conn", ",", "[", "\"/v1/query/#{key}\"", "]", ",", "options", ",", "custom_params", ")", "ret", ".", "status", "==", "200", "end" ]
Delete a prepared query or prepared query template @param key [String] the prepared query ID @param options [Hash] :dc Consul datacenter to query @return [Boolean]
[ "Delete", "a", "prepared", "query", "or", "prepared", "query", "template" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/query.rb#L41-L45
train
WeAreFarmGeek/diplomat
lib/diplomat/query.rb
Diplomat.Query.update
def update(key, definition, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil ret = send_put_request(@conn, ["/v1/query/#{key}"], options, definition, custom_params) ret.status == 200 end
ruby
def update(key, definition, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil ret = send_put_request(@conn, ["/v1/query/#{key}"], options, definition, custom_params) ret.status == 200 end
[ "def", "update", "(", "key", ",", "definition", ",", "options", "=", "{", "}", ")", "custom_params", "=", "options", "[", ":dc", "]", "?", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", ":", "nil", "ret", "=", "send_put_request", "(", "@conn", ",", "[", "\"/v1/query/#{key}\"", "]", ",", "options", ",", "definition", ",", "custom_params", ")", "ret", ".", "status", "==", "200", "end" ]
Update a prepared query or prepared query template @param key [String] the prepared query ID @param definition [Hash] Hash containing updated definition of prepared query @param options [Hash] :dc Consul datacenter to query @return [Boolean]
[ "Update", "a", "prepared", "query", "or", "prepared", "query", "template" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/query.rb#L52-L56
train
WeAreFarmGeek/diplomat
lib/diplomat/query.rb
Diplomat.Query.execute
def execute(key, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('near', options[:near]) if options[:near] custom_params << use_named_parameter('limit', options[:limit]) if options[:limit] ret = send_get_request(@conn, ["/v1/query/#{key}/execute"], options, custom_params) OpenStruct.new JSON.parse(ret.body) end
ruby
def execute(key, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('near', options[:near]) if options[:near] custom_params << use_named_parameter('limit', options[:limit]) if options[:limit] ret = send_get_request(@conn, ["/v1/query/#{key}/execute"], options, custom_params) OpenStruct.new JSON.parse(ret.body) end
[ "def", "execute", "(", "key", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "custom_params", "<<", "use_named_parameter", "(", "'near'", ",", "options", "[", ":near", "]", ")", "if", "options", "[", ":near", "]", "custom_params", "<<", "use_named_parameter", "(", "'limit'", ",", "options", "[", ":limit", "]", ")", "if", "options", "[", ":limit", "]", "ret", "=", "send_get_request", "(", "@conn", ",", "[", "\"/v1/query/#{key}/execute\"", "]", ",", "options", ",", "custom_params", ")", "OpenStruct", ".", "new", "JSON", ".", "parse", "(", "ret", ".", "body", ")", "end" ]
Execute a prepared query or prepared query template @param key [String] the prepared query ID or name @param options [Hash] prepared query execution options @option dc [String] :dc Consul datacenter to query @option near [String] node name to sort the resulting list in ascending order based on the estimated round trip time from that node @option limit [Integer] to limit the size of the return list to the given number of results @return [OpenStruct] the list of results from the prepared query or prepared query template rubocop:disable PerceivedComplexity
[ "Execute", "a", "prepared", "query", "or", "prepared", "query", "template" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/query.rb#L67-L74
train
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
Diplomat.Check.register_script
def register_script(check_id, name, notes, args, interval, options = {}) unless args.is_a?(Array) raise(Diplomat::DeprecatedArgument, 'Script usage is deprecated, replace by an array of args') end definition = JSON.generate( 'ID' => check_id, 'Name' => name, 'Notes' => notes, 'Args' => args, 'Interval' => interval ) ret = send_put_request(@conn, ['/v1/agent/check/register'], options, definition) ret.status == 200 end
ruby
def register_script(check_id, name, notes, args, interval, options = {}) unless args.is_a?(Array) raise(Diplomat::DeprecatedArgument, 'Script usage is deprecated, replace by an array of args') end definition = JSON.generate( 'ID' => check_id, 'Name' => name, 'Notes' => notes, 'Args' => args, 'Interval' => interval ) ret = send_put_request(@conn, ['/v1/agent/check/register'], options, definition) ret.status == 200 end
[ "def", "register_script", "(", "check_id", ",", "name", ",", "notes", ",", "args", ",", "interval", ",", "options", "=", "{", "}", ")", "unless", "args", ".", "is_a?", "(", "Array", ")", "raise", "(", "Diplomat", "::", "DeprecatedArgument", ",", "'Script usage is deprecated, replace by an array of args'", ")", "end", "definition", "=", "JSON", ".", "generate", "(", "'ID'", "=>", "check_id", ",", "'Name'", "=>", "name", ",", "'Notes'", "=>", "notes", ",", "'Args'", "=>", "args", ",", "'Interval'", "=>", "interval", ")", "ret", "=", "send_put_request", "(", "@conn", ",", "[", "'/v1/agent/check/register'", "]", ",", "options", ",", "definition", ")", "ret", ".", "status", "==", "200", "end" ]
Register a check @param check_id [String] the unique id of the check @param name [String] the name @param notes [String] notes about the check @param args [String[]] command to be run for check @param interval [String] frequency (with units) of the check execution @param options [Hash] options parameter hash @return [Integer] Status code rubocop:disable ParameterLists
[ "Register", "a", "check" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/check.rb#L23-L37
train
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
Diplomat.Check.update_ttl
def update_ttl(check_id, status, output = nil, options = {}) definition = JSON.generate( 'Status' => status, 'Output' => output ) ret = send_put_request(@conn, ["/v1/agent/check/update/#{check_id}"], options, definition) ret.status == 200 end
ruby
def update_ttl(check_id, status, output = nil, options = {}) definition = JSON.generate( 'Status' => status, 'Output' => output ) ret = send_put_request(@conn, ["/v1/agent/check/update/#{check_id}"], options, definition) ret.status == 200 end
[ "def", "update_ttl", "(", "check_id", ",", "status", ",", "output", "=", "nil", ",", "options", "=", "{", "}", ")", "definition", "=", "JSON", ".", "generate", "(", "'Status'", "=>", "status", ",", "'Output'", "=>", "output", ")", "ret", "=", "send_put_request", "(", "@conn", ",", "[", "\"/v1/agent/check/update/#{check_id}\"", "]", ",", "options", ",", "definition", ")", "ret", ".", "status", "==", "200", "end" ]
Update a TTL check @param check_id [String] the unique id of the check @param status [String] status of the check. Valid values are "passing", "warning", and "critical" @param output [String] human-readable message will be passed through to the check's Output field @param options [Hash] options parameter hash @return [Integer] Status code
[ "Update", "a", "TTL", "check" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/check.rb#L73-L80
train
WeAreFarmGeek/diplomat
lib/diplomat/kv.rb
Diplomat.Kv.get
def get(key, options = {}, not_found = :reject, found = :return) key_subst = if key.start_with? '/' key[1..-1] else key.freeze end @key = key_subst @options = options custom_params = [] custom_params << recurse_get(@options) custom_params << use_consistency(options) custom_params << dc(@options) custom_params << keys(@options) custom_params << separator(@options) return_nil_values = @options && @options[:nil_values] transformation = @options && @options[:transformation] && @options[:transformation].methods.find_index(:call) ? @options[:transformation] : nil raw = send_get_request(@conn_no_err, ["/v1/kv/#{@key}"], options, custom_params) if raw.status == 404 case not_found when :reject raise Diplomat::KeyNotFound, key when :return return @value = '' when :wait index = raw.headers['x-consul-index'] end elsif raw.status == 200 case found when :reject raise Diplomat::KeyAlreadyExists, key when :return @raw = raw @raw = parse_body return @raw.first['ModifyIndex'] if @options && @options[:modify_index] return @raw.first['Session'] if @options && @options[:session] return decode_values if @options && @options[:decode_values] return convert_to_hash(return_value(return_nil_values, transformation, true)) if @options && @options[:convert_to_hash] return return_value(return_nil_values, transformation) when :wait index = raw.headers['x-consul-index'] end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end # Wait for first/next value custom_params << use_named_parameter('index', index) if options.nil? options = { timeout: 86_400 } else options[:timeout] = 86_400 end @raw = send_get_request(@conn, ["/v1/kv/#{@key}"], options, custom_params) @raw = parse_body return_value(return_nil_values, transformation) end
ruby
def get(key, options = {}, not_found = :reject, found = :return) key_subst = if key.start_with? '/' key[1..-1] else key.freeze end @key = key_subst @options = options custom_params = [] custom_params << recurse_get(@options) custom_params << use_consistency(options) custom_params << dc(@options) custom_params << keys(@options) custom_params << separator(@options) return_nil_values = @options && @options[:nil_values] transformation = @options && @options[:transformation] && @options[:transformation].methods.find_index(:call) ? @options[:transformation] : nil raw = send_get_request(@conn_no_err, ["/v1/kv/#{@key}"], options, custom_params) if raw.status == 404 case not_found when :reject raise Diplomat::KeyNotFound, key when :return return @value = '' when :wait index = raw.headers['x-consul-index'] end elsif raw.status == 200 case found when :reject raise Diplomat::KeyAlreadyExists, key when :return @raw = raw @raw = parse_body return @raw.first['ModifyIndex'] if @options && @options[:modify_index] return @raw.first['Session'] if @options && @options[:session] return decode_values if @options && @options[:decode_values] return convert_to_hash(return_value(return_nil_values, transformation, true)) if @options && @options[:convert_to_hash] return return_value(return_nil_values, transformation) when :wait index = raw.headers['x-consul-index'] end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end # Wait for first/next value custom_params << use_named_parameter('index', index) if options.nil? options = { timeout: 86_400 } else options[:timeout] = 86_400 end @raw = send_get_request(@conn, ["/v1/kv/#{@key}"], options, custom_params) @raw = parse_body return_value(return_nil_values, transformation) end
[ "def", "get", "(", "key", ",", "options", "=", "{", "}", ",", "not_found", "=", ":reject", ",", "found", "=", ":return", ")", "key_subst", "=", "if", "key", ".", "start_with?", "'/'", "key", "[", "1", "..", "-", "1", "]", "else", "key", ".", "freeze", "end", "@key", "=", "key_subst", "@options", "=", "options", "custom_params", "=", "[", "]", "custom_params", "<<", "recurse_get", "(", "@options", ")", "custom_params", "<<", "use_consistency", "(", "options", ")", "custom_params", "<<", "dc", "(", "@options", ")", "custom_params", "<<", "keys", "(", "@options", ")", "custom_params", "<<", "separator", "(", "@options", ")", "return_nil_values", "=", "@options", "&&", "@options", "[", ":nil_values", "]", "transformation", "=", "@options", "&&", "@options", "[", ":transformation", "]", "&&", "@options", "[", ":transformation", "]", ".", "methods", ".", "find_index", "(", ":call", ")", "?", "@options", "[", ":transformation", "]", ":", "nil", "raw", "=", "send_get_request", "(", "@conn_no_err", ",", "[", "\"/v1/kv/#{@key}\"", "]", ",", "options", ",", "custom_params", ")", "if", "raw", ".", "status", "==", "404", "case", "not_found", "when", ":reject", "raise", "Diplomat", "::", "KeyNotFound", ",", "key", "when", ":return", "return", "@value", "=", "''", "when", ":wait", "index", "=", "raw", ".", "headers", "[", "'x-consul-index'", "]", "end", "elsif", "raw", ".", "status", "==", "200", "case", "found", "when", ":reject", "raise", "Diplomat", "::", "KeyAlreadyExists", ",", "key", "when", ":return", "@raw", "=", "raw", "@raw", "=", "parse_body", "return", "@raw", ".", "first", "[", "'ModifyIndex'", "]", "if", "@options", "&&", "@options", "[", ":modify_index", "]", "return", "@raw", ".", "first", "[", "'Session'", "]", "if", "@options", "&&", "@options", "[", ":session", "]", "return", "decode_values", "if", "@options", "&&", "@options", "[", ":decode_values", "]", "return", "convert_to_hash", "(", "return_value", "(", "return_nil_values", ",", "transformation", ",", "true", ")", ")", "if", "@options", "&&", "@options", "[", ":convert_to_hash", "]", "return", "return_value", "(", "return_nil_values", ",", "transformation", ")", "when", ":wait", "index", "=", "raw", ".", "headers", "[", "'x-consul-index'", "]", "end", "else", "raise", "Diplomat", "::", "UnknownStatus", ",", "\"status #{raw.status}: #{raw.body}\"", "end", "# Wait for first/next value", "custom_params", "<<", "use_named_parameter", "(", "'index'", ",", "index", ")", "if", "options", ".", "nil?", "options", "=", "{", "timeout", ":", "86_400", "}", "else", "options", "[", ":timeout", "]", "=", "86_400", "end", "@raw", "=", "send_get_request", "(", "@conn", ",", "[", "\"/v1/kv/#{@key}\"", "]", ",", "options", ",", "custom_params", ")", "@raw", "=", "parse_body", "return_value", "(", "return_nil_values", ",", "transformation", ")", "end" ]
Get a value by its key, potentially blocking for the first or next value @param key [String] the key @param options [Hash] the query params @option options [Boolean] :recurse If to make recursive get or not @option options [String] :consistency The read consistency type @option options [String] :dc Target datacenter @option options [Boolean] :keys Only return key names. @option options [Boolean] :modify_index Only return ModifyIndex value. @option options [Boolean] :session Only return Session value. @option options [Boolean] :decode_values Return consul response with decoded values. @option options [String] :separator List only up to a given separator. Only applies when combined with :keys option. @option options [Boolean] :nil_values If to return keys/dirs with nil values @option options [Boolean] :convert_to_hash Take the data returned from consul and build a hash @option options [Callable] :transformation funnction to invoke on keys values @param not_found [Symbol] behaviour if the key doesn't exist; :reject with exception, :return degenerate value, or :wait for it to appear @param found [Symbol] behaviour if the key does exist; :reject with exception, :return its current value, or :wait for its next value @return [String] The base64-decoded value associated with the key @note When trying to access a key, there are two possibilites: - The key doesn't (yet) exist - The key exists. This may be its first value, there is no way to tell The combination of not_found and found behaviour gives maximum possible flexibility. For X: reject, R: return, W: wait - X X - meaningless; never return a value - X R - "normal" non-blocking get operation. Default - X W - get the next value only (must have a current value) - R X - meaningless; never return a meaningful value - R R - "safe" non-blocking, non-throwing get-or-default operation - R W - get the next value or a default - W X - get the first value only (must not have a current value) - W R - get the first or current value; always return something, but block only when necessary - W W - get the first or next value; wait until there is an update rubocop:disable PerceivedComplexity, MethodLength, LineLength, CyclomaticComplexity
[ "Get", "a", "value", "by", "its", "key", "potentially", "blocking", "for", "the", "first", "or", "next", "value" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/kv.rb#L44-L102
train
WeAreFarmGeek/diplomat
lib/diplomat/kv.rb
Diplomat.Kv.delete
def delete(key, options = {}) @key = key @options = options custom_params = [] custom_params << recurse_get(@options) custom_params << dc(@options) @raw = send_delete_request(@conn, ["/v1/kv/#{@key}"], options, custom_params) end
ruby
def delete(key, options = {}) @key = key @options = options custom_params = [] custom_params << recurse_get(@options) custom_params << dc(@options) @raw = send_delete_request(@conn, ["/v1/kv/#{@key}"], options, custom_params) end
[ "def", "delete", "(", "key", ",", "options", "=", "{", "}", ")", "@key", "=", "key", "@options", "=", "options", "custom_params", "=", "[", "]", "custom_params", "<<", "recurse_get", "(", "@options", ")", "custom_params", "<<", "dc", "(", "@options", ")", "@raw", "=", "send_delete_request", "(", "@conn", ",", "[", "\"/v1/kv/#{@key}\"", "]", ",", "options", ",", "custom_params", ")", "end" ]
Delete a value by its key @param key [String] the key @param options [Hash] the query params @option options [String] :dc Target datacenter @option options [Boolean] :recurse If to make recursive get or not @return [OpenStruct]
[ "Delete", "a", "value", "by", "its", "key" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/kv.rb#L134-L141
train
WeAreFarmGeek/diplomat
lib/diplomat/event.rb
Diplomat.Event.fire
def fire(name, value = nil, service = nil, node = nil, tag = nil, dc = nil, options = {}) custom_params = [] custom_params << use_named_parameter('service', service) if service custom_params << use_named_parameter('node', node) if node custom_params << use_named_parameter('tag', tag) if tag custom_params << use_named_parameter('dc', dc) if dc send_put_request(@conn, ["/v1/event/fire/#{name}"], options, value, custom_params) nil end
ruby
def fire(name, value = nil, service = nil, node = nil, tag = nil, dc = nil, options = {}) custom_params = [] custom_params << use_named_parameter('service', service) if service custom_params << use_named_parameter('node', node) if node custom_params << use_named_parameter('tag', tag) if tag custom_params << use_named_parameter('dc', dc) if dc send_put_request(@conn, ["/v1/event/fire/#{name}"], options, value, custom_params) nil end
[ "def", "fire", "(", "name", ",", "value", "=", "nil", ",", "service", "=", "nil", ",", "node", "=", "nil", ",", "tag", "=", "nil", ",", "dc", "=", "nil", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'service'", ",", "service", ")", "if", "service", "custom_params", "<<", "use_named_parameter", "(", "'node'", ",", "node", ")", "if", "node", "custom_params", "<<", "use_named_parameter", "(", "'tag'", ",", "tag", ")", "if", "tag", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "dc", ")", "if", "dc", "send_put_request", "(", "@conn", ",", "[", "\"/v1/event/fire/#{name}\"", "]", ",", "options", ",", "value", ",", "custom_params", ")", "nil", "end" ]
Send an event @param name [String] the event name @param value [String] the payload of the event @param service [String] the target service name @param node [String] the target node name @param tag [String] the target tag name, must only be used with service @param dc [String] the dc to target @param options [Hash] options parameter hash @return [nil] rubocop:disable Metrics/ParameterLists
[ "Send", "an", "event" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/event.rb#L16-L25
train
WeAreFarmGeek/diplomat
lib/diplomat/event.rb
Diplomat.Event.get
def get(name = nil, token = :last, not_found = :wait, found = :return, options = {}) @raw = send_get_request(@conn, ['/v1/event/list'], options, use_named_parameter('name', name)) body = JSON.parse(@raw.body) # TODO: deal with unknown symbols, invalid indices (find_index will return nil) idx = case token when :first then 0 when :last then body.length - 1 when :next then body.length else body.find_index { |e| e['ID'] == token } + 1 end if JSON.parse(@raw.body).count.zero? || idx == body.length case not_found when :reject raise Diplomat::EventNotFound, name when :return event_name = '' event_payload = '' event_token = :last when :wait @raw = wait_for_next_event(['/v1/event/list'], options, use_named_parameter('name', name)) @raw = parse_body # If it's possible for two events to arrive at once, # this needs to #find again: event = @raw.last event_name = event['Name'] event_payload = Base64.decode64(event['Payload']) event_token = event['ID'] end else case found when :reject raise Diplomat::EventAlreadyExits, name when :return event = body[idx] event_name = event['Name'] event_payload = event['Payload'].nil? ? nil : Base64.decode64(event['Payload']) event_token = event['ID'] end end { value: { name: event_name, payload: event_payload }, token: event_token } end
ruby
def get(name = nil, token = :last, not_found = :wait, found = :return, options = {}) @raw = send_get_request(@conn, ['/v1/event/list'], options, use_named_parameter('name', name)) body = JSON.parse(@raw.body) # TODO: deal with unknown symbols, invalid indices (find_index will return nil) idx = case token when :first then 0 when :last then body.length - 1 when :next then body.length else body.find_index { |e| e['ID'] == token } + 1 end if JSON.parse(@raw.body).count.zero? || idx == body.length case not_found when :reject raise Diplomat::EventNotFound, name when :return event_name = '' event_payload = '' event_token = :last when :wait @raw = wait_for_next_event(['/v1/event/list'], options, use_named_parameter('name', name)) @raw = parse_body # If it's possible for two events to arrive at once, # this needs to #find again: event = @raw.last event_name = event['Name'] event_payload = Base64.decode64(event['Payload']) event_token = event['ID'] end else case found when :reject raise Diplomat::EventAlreadyExits, name when :return event = body[idx] event_name = event['Name'] event_payload = event['Payload'].nil? ? nil : Base64.decode64(event['Payload']) event_token = event['ID'] end end { value: { name: event_name, payload: event_payload }, token: event_token } end
[ "def", "get", "(", "name", "=", "nil", ",", "token", "=", ":last", ",", "not_found", "=", ":wait", ",", "found", "=", ":return", ",", "options", "=", "{", "}", ")", "@raw", "=", "send_get_request", "(", "@conn", ",", "[", "'/v1/event/list'", "]", ",", "options", ",", "use_named_parameter", "(", "'name'", ",", "name", ")", ")", "body", "=", "JSON", ".", "parse", "(", "@raw", ".", "body", ")", "# TODO: deal with unknown symbols, invalid indices (find_index will return nil)", "idx", "=", "case", "token", "when", ":first", "then", "0", "when", ":last", "then", "body", ".", "length", "-", "1", "when", ":next", "then", "body", ".", "length", "else", "body", ".", "find_index", "{", "|", "e", "|", "e", "[", "'ID'", "]", "==", "token", "}", "+", "1", "end", "if", "JSON", ".", "parse", "(", "@raw", ".", "body", ")", ".", "count", ".", "zero?", "||", "idx", "==", "body", ".", "length", "case", "not_found", "when", ":reject", "raise", "Diplomat", "::", "EventNotFound", ",", "name", "when", ":return", "event_name", "=", "''", "event_payload", "=", "''", "event_token", "=", ":last", "when", ":wait", "@raw", "=", "wait_for_next_event", "(", "[", "'/v1/event/list'", "]", ",", "options", ",", "use_named_parameter", "(", "'name'", ",", "name", ")", ")", "@raw", "=", "parse_body", "# If it's possible for two events to arrive at once,", "# this needs to #find again:", "event", "=", "@raw", ".", "last", "event_name", "=", "event", "[", "'Name'", "]", "event_payload", "=", "Base64", ".", "decode64", "(", "event", "[", "'Payload'", "]", ")", "event_token", "=", "event", "[", "'ID'", "]", "end", "else", "case", "found", "when", ":reject", "raise", "Diplomat", "::", "EventAlreadyExits", ",", "name", "when", ":return", "event", "=", "body", "[", "idx", "]", "event_name", "=", "event", "[", "'Name'", "]", "event_payload", "=", "event", "[", "'Payload'", "]", ".", "nil?", "?", "nil", ":", "Base64", ".", "decode64", "(", "event", "[", "'Payload'", "]", ")", "event_token", "=", "event", "[", "'ID'", "]", "end", "end", "{", "value", ":", "{", "name", ":", "event_name", ",", "payload", ":", "event_payload", "}", ",", "token", ":", "event_token", "}", "end" ]
Get a specific event in the sequence matching name @param name [String] the name of the event (regex) @param token [String|Symbol] the ordinate of the event in the sequence; String are tokens returned by previous calls to this function Symbols are the special tokens :first, :last, and :next @param not_found [Symbol] behaviour if there is no matching event; :reject with exception, :return degenerate value, or :wait for event @param found [Symbol] behaviour if there is a matching event; :reject with exception, or :return its current value @return [hash] A hash with keys :value and :token; :value is a further hash of the :name and :payload of the event, :token is the event's ordinate in the sequence and can be passed to future calls to get the subsequent event @param options [Hash] options parameter hash @note Whereas the consul API for events returns all past events that match name, this method allows retrieval of individual events from that sequence. However, because consul's API isn't conducive to this, we can offer first, last, next (last + 1) events, or arbitrary events in the middle, though these can only be identified relative to the preceding event. However, this is ideal for iterating through the sequence of events (while being sure that none are missed). rubocop:disable PerceivedComplexity
[ "Get", "a", "specific", "event", "in", "the", "sequence", "matching", "name" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/event.rb#L106-L150
train
WeAreFarmGeek/diplomat
lib/diplomat/service.rb
Diplomat.Service.get
def get(key, scope = :first, options = {}, meta = nil) custom_params = [] custom_params << use_named_parameter('wait', options[:wait]) if options[:wait] custom_params << use_named_parameter('index', options[:index]) if options[:index] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] if options[:tag] # tag can be either a String, or an array of strings # by splatting it is guaranteed to be an array of strings [*options[:tag]].each do |value| custom_params << use_named_parameter('tag', value) end end # We have to provide a custom params encoder here because Faraday - by default - assumes that # list keys have [] as part of their name. This is however not the case for consul tags, which # just use repeated occurences of the same key. # # So faraday reduces this: http://localhost:8500?a=1&a=2 to http://localhost:8500?a=2 unless you # explicitly tell it not to. options[:params_encoder] = Faraday::FlatParamsEncoder ret = send_get_request(@conn, ["/v1/catalog/service/#{key}"], options, custom_params) if meta && ret.headers meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index'] meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader'] meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact'] end if scope == :all JSON.parse(ret.body).map { |service| OpenStruct.new service } else OpenStruct.new JSON.parse(ret.body).first end end
ruby
def get(key, scope = :first, options = {}, meta = nil) custom_params = [] custom_params << use_named_parameter('wait', options[:wait]) if options[:wait] custom_params << use_named_parameter('index', options[:index]) if options[:index] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] if options[:tag] # tag can be either a String, or an array of strings # by splatting it is guaranteed to be an array of strings [*options[:tag]].each do |value| custom_params << use_named_parameter('tag', value) end end # We have to provide a custom params encoder here because Faraday - by default - assumes that # list keys have [] as part of their name. This is however not the case for consul tags, which # just use repeated occurences of the same key. # # So faraday reduces this: http://localhost:8500?a=1&a=2 to http://localhost:8500?a=2 unless you # explicitly tell it not to. options[:params_encoder] = Faraday::FlatParamsEncoder ret = send_get_request(@conn, ["/v1/catalog/service/#{key}"], options, custom_params) if meta && ret.headers meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index'] meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader'] meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact'] end if scope == :all JSON.parse(ret.body).map { |service| OpenStruct.new service } else OpenStruct.new JSON.parse(ret.body).first end end
[ "def", "get", "(", "key", ",", "scope", "=", ":first", ",", "options", "=", "{", "}", ",", "meta", "=", "nil", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'wait'", ",", "options", "[", ":wait", "]", ")", "if", "options", "[", ":wait", "]", "custom_params", "<<", "use_named_parameter", "(", "'index'", ",", "options", "[", ":index", "]", ")", "if", "options", "[", ":index", "]", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "if", "options", "[", ":tag", "]", "# tag can be either a String, or an array of strings", "# by splatting it is guaranteed to be an array of strings", "[", "options", "[", ":tag", "]", "]", ".", "each", "do", "|", "value", "|", "custom_params", "<<", "use_named_parameter", "(", "'tag'", ",", "value", ")", "end", "end", "# We have to provide a custom params encoder here because Faraday - by default - assumes that", "# list keys have [] as part of their name. This is however not the case for consul tags, which", "# just use repeated occurences of the same key.", "#", "# So faraday reduces this: http://localhost:8500?a=1&a=2 to http://localhost:8500?a=2 unless you", "# explicitly tell it not to.", "options", "[", ":params_encoder", "]", "=", "Faraday", "::", "FlatParamsEncoder", "ret", "=", "send_get_request", "(", "@conn", ",", "[", "\"/v1/catalog/service/#{key}\"", "]", ",", "options", ",", "custom_params", ")", "if", "meta", "&&", "ret", ".", "headers", "meta", "[", ":index", "]", "=", "ret", ".", "headers", "[", "'x-consul-index'", "]", "if", "ret", ".", "headers", "[", "'x-consul-index'", "]", "meta", "[", ":knownleader", "]", "=", "ret", ".", "headers", "[", "'x-consul-knownleader'", "]", "if", "ret", ".", "headers", "[", "'x-consul-knownleader'", "]", "meta", "[", ":lastcontact", "]", "=", "ret", ".", "headers", "[", "'x-consul-lastcontact'", "]", "if", "ret", ".", "headers", "[", "'x-consul-lastcontact'", "]", "end", "if", "scope", "==", ":all", "JSON", ".", "parse", "(", "ret", ".", "body", ")", ".", "map", "{", "|", "service", "|", "OpenStruct", ".", "new", "service", "}", "else", "OpenStruct", ".", "new", "JSON", ".", "parse", "(", "ret", ".", "body", ")", ".", "first", "end", "end" ]
Get a service by it's key @param key [String] the key @param scope [Symbol] :first or :all results @param options [Hash] options parameter hash @param meta [Hash] output structure containing header information about the request (index) @return [OpenStruct] all data associated with the service rubocop:disable PerceivedComplexity
[ "Get", "a", "service", "by", "it", "s", "key" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/service.rb#L13-L46
train
WeAreFarmGeek/diplomat
lib/diplomat/service.rb
Diplomat.Service.register
def register(definition, options = {}) url = options[:path] || ['/v1/agent/service/register'] register = send_put_request(@conn, url, options, definition) register.status == 200 end
ruby
def register(definition, options = {}) url = options[:path] || ['/v1/agent/service/register'] register = send_put_request(@conn, url, options, definition) register.status == 200 end
[ "def", "register", "(", "definition", ",", "options", "=", "{", "}", ")", "url", "=", "options", "[", ":path", "]", "||", "[", "'/v1/agent/service/register'", "]", "register", "=", "send_put_request", "(", "@conn", ",", "url", ",", "options", ",", "definition", ")", "register", ".", "status", "==", "200", "end" ]
Register a service @param definition [Hash] Hash containing definition of service @param options [Hash] options parameter hash @return [Boolean]
[ "Register", "a", "service" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/service.rb#L62-L66
train
WeAreFarmGeek/diplomat
lib/diplomat/service.rb
Diplomat.Service.maintenance
def maintenance(service_id, options = { enable: true }) custom_params = [] custom_params << ["enable=#{options[:enable]}"] custom_params << ["reason=#{options[:reason].split(' ').join('+')}"] if options[:reason] maintenance = send_put_request(@conn, ["/v1/agent/service/maintenance/#{service_id}"], options, nil, custom_params) maintenance.status == 200 end
ruby
def maintenance(service_id, options = { enable: true }) custom_params = [] custom_params << ["enable=#{options[:enable]}"] custom_params << ["reason=#{options[:reason].split(' ').join('+')}"] if options[:reason] maintenance = send_put_request(@conn, ["/v1/agent/service/maintenance/#{service_id}"], options, nil, custom_params) maintenance.status == 200 end
[ "def", "maintenance", "(", "service_id", ",", "options", "=", "{", "enable", ":", "true", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "[", "\"enable=#{options[:enable]}\"", "]", "custom_params", "<<", "[", "\"reason=#{options[:reason].split(' ').join('+')}\"", "]", "if", "options", "[", ":reason", "]", "maintenance", "=", "send_put_request", "(", "@conn", ",", "[", "\"/v1/agent/service/maintenance/#{service_id}\"", "]", ",", "options", ",", "nil", ",", "custom_params", ")", "maintenance", ".", "status", "==", "200", "end" ]
Enable or disable maintenance for a service @param service_id [String] id of the service @param options [Hash] opts the options for enabling or disabling maintenance for a service @options opts [Boolean] :enable (true) whether to enable or disable maintenance @options opts [String] :reason reason for the service maintenance @raise [Diplomat::PathNotFound] if the request fails @return [Boolean] if the request was successful or not
[ "Enable", "or", "disable", "maintenance", "for", "a", "service" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/service.rb#L102-L109
train
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
Diplomat.Health.node
def node(n, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] ret = send_get_request(@conn, ["/v1/health/node/#{n}"], options, custom_params) JSON.parse(ret.body).map { |node| OpenStruct.new node } end
ruby
def node(n, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] ret = send_get_request(@conn, ["/v1/health/node/#{n}"], options, custom_params) JSON.parse(ret.body).map { |node| OpenStruct.new node } end
[ "def", "node", "(", "n", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "ret", "=", "send_get_request", "(", "@conn", ",", "[", "\"/v1/health/node/#{n}\"", "]", ",", "options", ",", "custom_params", ")", "JSON", ".", "parse", "(", "ret", ".", "body", ")", ".", "map", "{", "|", "node", "|", "OpenStruct", ".", "new", "node", "}", "end" ]
Get node health @param n [String] the node @param options [Hash] :dc string for dc specific query @return [OpenStruct] all data associated with the node
[ "Get", "node", "health" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/health.rb#L11-L17
train
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
Diplomat.Health.checks
def checks(s, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] ret = send_get_request(@conn, ["/v1/health/checks/#{s}"], options, custom_params) JSON.parse(ret.body).map { |check| OpenStruct.new check } end
ruby
def checks(s, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] ret = send_get_request(@conn, ["/v1/health/checks/#{s}"], options, custom_params) JSON.parse(ret.body).map { |check| OpenStruct.new check } end
[ "def", "checks", "(", "s", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "ret", "=", "send_get_request", "(", "@conn", ",", "[", "\"/v1/health/checks/#{s}\"", "]", ",", "options", ",", "custom_params", ")", "JSON", ".", "parse", "(", "ret", ".", "body", ")", ".", "map", "{", "|", "check", "|", "OpenStruct", ".", "new", "check", "}", "end" ]
Get service checks @param s [String] the service @param options [Hash] :dc string for dc specific query @return [OpenStruct] all data associated with the node
[ "Get", "service", "checks" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/health.rb#L23-L29
train
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
Diplomat.Health.service
def service(s, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << ['passing'] if options[:passing] custom_params << use_named_parameter('tag', options[:tag]) if options[:tag] custom_params << use_named_parameter('near', options[:near]) if options[:near] ret = send_get_request(@conn, ["/v1/health/service/#{s}"], options, custom_params) JSON.parse(ret.body).map { |service| OpenStruct.new service } end
ruby
def service(s, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << ['passing'] if options[:passing] custom_params << use_named_parameter('tag', options[:tag]) if options[:tag] custom_params << use_named_parameter('near', options[:near]) if options[:near] ret = send_get_request(@conn, ["/v1/health/service/#{s}"], options, custom_params) JSON.parse(ret.body).map { |service| OpenStruct.new service } end
[ "def", "service", "(", "s", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "custom_params", "<<", "[", "'passing'", "]", "if", "options", "[", ":passing", "]", "custom_params", "<<", "use_named_parameter", "(", "'tag'", ",", "options", "[", ":tag", "]", ")", "if", "options", "[", ":tag", "]", "custom_params", "<<", "use_named_parameter", "(", "'near'", ",", "options", "[", ":near", "]", ")", "if", "options", "[", ":near", "]", "ret", "=", "send_get_request", "(", "@conn", ",", "[", "\"/v1/health/service/#{s}\"", "]", ",", "options", ",", "custom_params", ")", "JSON", ".", "parse", "(", "ret", ".", "body", ")", ".", "map", "{", "|", "service", "|", "OpenStruct", ".", "new", "service", "}", "end" ]
Get service health @param s [String] the service @param options [Hash] options parameter hash @return [OpenStruct] all data associated with the node rubocop:disable PerceivedComplexity
[ "Get", "service", "health" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/health.rb#L36-L45
train
WeAreFarmGeek/diplomat
lib/diplomat/lock.rb
Diplomat.Lock.acquire
def acquire(key, session, value = nil, options = {}) custom_params = [] custom_params << use_named_parameter('acquire', session) custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('flags', options[:flags]) if options && options[:flags] data = value unless value.nil? raw = send_put_request(@conn, ["/v1/kv/#{key}"], options, data, custom_params) raw.body.chomp == 'true' end
ruby
def acquire(key, session, value = nil, options = {}) custom_params = [] custom_params << use_named_parameter('acquire', session) custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('flags', options[:flags]) if options && options[:flags] data = value unless value.nil? raw = send_put_request(@conn, ["/v1/kv/#{key}"], options, data, custom_params) raw.body.chomp == 'true' end
[ "def", "acquire", "(", "key", ",", "session", ",", "value", "=", "nil", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'acquire'", ",", "session", ")", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "custom_params", "<<", "use_named_parameter", "(", "'flags'", ",", "options", "[", ":flags", "]", ")", "if", "options", "&&", "options", "[", ":flags", "]", "data", "=", "value", "unless", "value", ".", "nil?", "raw", "=", "send_put_request", "(", "@conn", ",", "[", "\"/v1/kv/#{key}\"", "]", ",", "options", ",", "data", ",", "custom_params", ")", "raw", ".", "body", ".", "chomp", "==", "'true'", "end" ]
Acquire a lock @param key [String] the key @param session [String] the session, generated from Diplomat::Session.create @param value [String] the value for the key @param options [Hash] options parameter hash @return [Boolean] If the lock was acquired
[ "Acquire", "a", "lock" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/lock.rb#L12-L20
train
WeAreFarmGeek/diplomat
lib/diplomat/lock.rb
Diplomat.Lock.wait_to_acquire
def wait_to_acquire(key, session, value = nil, check_interval = 10, options = {}) acquired = false until acquired acquired = acquire(key, session, value, options) sleep(check_interval) unless acquired return true if acquired end end
ruby
def wait_to_acquire(key, session, value = nil, check_interval = 10, options = {}) acquired = false until acquired acquired = acquire(key, session, value, options) sleep(check_interval) unless acquired return true if acquired end end
[ "def", "wait_to_acquire", "(", "key", ",", "session", ",", "value", "=", "nil", ",", "check_interval", "=", "10", ",", "options", "=", "{", "}", ")", "acquired", "=", "false", "until", "acquired", "acquired", "=", "acquire", "(", "key", ",", "session", ",", "value", ",", "options", ")", "sleep", "(", "check_interval", ")", "unless", "acquired", "return", "true", "if", "acquired", "end", "end" ]
wait to aquire a lock @param key [String] the key @param session [String] the session, generated from Diplomat::Session.create @param value [String] the value for the key @param check_interval [Integer] number of seconds to wait between retries @param options [Hash] options parameter hash @return [Boolean] If the lock was acquired
[ "wait", "to", "aquire", "a", "lock" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/lock.rb#L29-L36
train
WeAreFarmGeek/diplomat
lib/diplomat/lock.rb
Diplomat.Lock.release
def release(key, session, options = {}) custom_params = [] custom_params << use_named_parameter('release', session) custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('flags', options[:flags]) if options && options[:flags] raw = send_put_request(@conn, ["/v1/kv/#{key}"], options, nil, custom_params) raw.body end
ruby
def release(key, session, options = {}) custom_params = [] custom_params << use_named_parameter('release', session) custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('flags', options[:flags]) if options && options[:flags] raw = send_put_request(@conn, ["/v1/kv/#{key}"], options, nil, custom_params) raw.body end
[ "def", "release", "(", "key", ",", "session", ",", "options", "=", "{", "}", ")", "custom_params", "=", "[", "]", "custom_params", "<<", "use_named_parameter", "(", "'release'", ",", "session", ")", "custom_params", "<<", "use_named_parameter", "(", "'dc'", ",", "options", "[", ":dc", "]", ")", "if", "options", "[", ":dc", "]", "custom_params", "<<", "use_named_parameter", "(", "'flags'", ",", "options", "[", ":flags", "]", ")", "if", "options", "&&", "options", "[", ":flags", "]", "raw", "=", "send_put_request", "(", "@conn", ",", "[", "\"/v1/kv/#{key}\"", "]", ",", "options", ",", "nil", ",", "custom_params", ")", "raw", ".", "body", "end" ]
Release a lock @param key [String] the key @param session [String] the session, generated from Diplomat::Session.create @param options [Hash] :dc string for dc specific query @return [nil] rubocop:disable AbcSize
[ "Release", "a", "lock" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/lock.rb#L44-L51
train
WeAreFarmGeek/diplomat
lib/diplomat/rest_client.rb
Diplomat.RestClient.concat_url
def concat_url(parts) parts.reject!(&:empty?) if parts.length > 1 parts.first + '?' + parts.drop(1).join('&') else parts.first end end
ruby
def concat_url(parts) parts.reject!(&:empty?) if parts.length > 1 parts.first + '?' + parts.drop(1).join('&') else parts.first end end
[ "def", "concat_url", "(", "parts", ")", "parts", ".", "reject!", "(", ":empty?", ")", "if", "parts", ".", "length", ">", "1", "parts", ".", "first", "+", "'?'", "+", "parts", ".", "drop", "(", "1", ")", ".", "join", "(", "'&'", ")", "else", "parts", ".", "first", "end", "end" ]
Assemble a url from an array of parts. @param parts [Array] the url chunks to be assembled @return [String] the resultant url string
[ "Assemble", "a", "url", "from", "an", "array", "of", "parts", "." ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/rest_client.rb#L34-L41
train
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
Diplomat.Acl.info
def info(id, options = {}, not_found = :reject, found = :return) @id = id @options = options custom_params = [] custom_params << use_consistency(options) raw = send_get_request(@conn_no_err, ["/v1/acl/info/#{id}"], options, custom_params) if raw.status == 200 && raw.body.chomp != 'null' case found when :reject raise Diplomat::AclAlreadyExists, id when :return @raw = raw return parse_body end elsif raw.status == 200 && raw.body.chomp == 'null' case not_found when :reject raise Diplomat::AclNotFound, id when :return return nil end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end end
ruby
def info(id, options = {}, not_found = :reject, found = :return) @id = id @options = options custom_params = [] custom_params << use_consistency(options) raw = send_get_request(@conn_no_err, ["/v1/acl/info/#{id}"], options, custom_params) if raw.status == 200 && raw.body.chomp != 'null' case found when :reject raise Diplomat::AclAlreadyExists, id when :return @raw = raw return parse_body end elsif raw.status == 200 && raw.body.chomp == 'null' case not_found when :reject raise Diplomat::AclNotFound, id when :return return nil end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end end
[ "def", "info", "(", "id", ",", "options", "=", "{", "}", ",", "not_found", "=", ":reject", ",", "found", "=", ":return", ")", "@id", "=", "id", "@options", "=", "options", "custom_params", "=", "[", "]", "custom_params", "<<", "use_consistency", "(", "options", ")", "raw", "=", "send_get_request", "(", "@conn_no_err", ",", "[", "\"/v1/acl/info/#{id}\"", "]", ",", "options", ",", "custom_params", ")", "if", "raw", ".", "status", "==", "200", "&&", "raw", ".", "body", ".", "chomp", "!=", "'null'", "case", "found", "when", ":reject", "raise", "Diplomat", "::", "AclAlreadyExists", ",", "id", "when", ":return", "@raw", "=", "raw", "return", "parse_body", "end", "elsif", "raw", ".", "status", "==", "200", "&&", "raw", ".", "body", ".", "chomp", "==", "'null'", "case", "not_found", "when", ":reject", "raise", "Diplomat", "::", "AclNotFound", ",", "id", "when", ":return", "return", "nil", "end", "else", "raise", "Diplomat", "::", "UnknownStatus", ",", "\"status #{raw.status}: #{raw.body}\"", "end", "end" ]
Get Acl info by ID @param id [String] ID of the Acl to get @param options [Hash] options parameter hash @return [Hash] rubocop:disable PerceivedComplexity
[ "Get", "Acl", "info", "by", "ID" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/acl.rb#L12-L38
train
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
Diplomat.Acl.update
def update(value, options = {}) raise Diplomat::IdParameterRequired unless value['ID'] || value[:ID] custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/update'], options, value, custom_params) parse_body end
ruby
def update(value, options = {}) raise Diplomat::IdParameterRequired unless value['ID'] || value[:ID] custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/update'], options, value, custom_params) parse_body end
[ "def", "update", "(", "value", ",", "options", "=", "{", "}", ")", "raise", "Diplomat", "::", "IdParameterRequired", "unless", "value", "[", "'ID'", "]", "||", "value", "[", ":ID", "]", "custom_params", "=", "use_cas", "(", "@options", ")", "@raw", "=", "send_put_request", "(", "@conn", ",", "[", "'/v1/acl/update'", "]", ",", "options", ",", "value", ",", "custom_params", ")", "parse_body", "end" ]
Update an Acl definition, create if not present @param value [Hash] Acl definition, ID field is mandatory @param options [Hash] options parameter hash @return [Hash] The result Acl
[ "Update", "an", "Acl", "definition", "create", "if", "not", "present" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/acl.rb#L53-L59
train
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
Diplomat.Acl.create
def create(value, options = {}) custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/create'], options, value, custom_params) parse_body end
ruby
def create(value, options = {}) custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/create'], options, value, custom_params) parse_body end
[ "def", "create", "(", "value", ",", "options", "=", "{", "}", ")", "custom_params", "=", "use_cas", "(", "@options", ")", "@raw", "=", "send_put_request", "(", "@conn", ",", "[", "'/v1/acl/create'", "]", ",", "options", ",", "value", ",", "custom_params", ")", "parse_body", "end" ]
Create an Acl definition @param value [Hash] Acl definition, ID field is mandatory @param options [Hash] options parameter hash @return [Hash] The result Acl
[ "Create", "an", "Acl", "definition" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/acl.rb#L65-L69
train
WeAreFarmGeek/diplomat
lib/diplomat/datacenter.rb
Diplomat.Datacenter.get
def get(meta = nil, options = {}) ret = send_get_request(@conn, ['/v1/catalog/datacenters'], options) if meta && ret.headers meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index'] meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader'] meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact'] end JSON.parse(ret.body) end
ruby
def get(meta = nil, options = {}) ret = send_get_request(@conn, ['/v1/catalog/datacenters'], options) if meta && ret.headers meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index'] meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader'] meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact'] end JSON.parse(ret.body) end
[ "def", "get", "(", "meta", "=", "nil", ",", "options", "=", "{", "}", ")", "ret", "=", "send_get_request", "(", "@conn", ",", "[", "'/v1/catalog/datacenters'", "]", ",", "options", ")", "if", "meta", "&&", "ret", ".", "headers", "meta", "[", ":index", "]", "=", "ret", ".", "headers", "[", "'x-consul-index'", "]", "if", "ret", ".", "headers", "[", "'x-consul-index'", "]", "meta", "[", ":knownleader", "]", "=", "ret", ".", "headers", "[", "'x-consul-knownleader'", "]", "if", "ret", ".", "headers", "[", "'x-consul-knownleader'", "]", "meta", "[", ":lastcontact", "]", "=", "ret", ".", "headers", "[", "'x-consul-lastcontact'", "]", "if", "ret", ".", "headers", "[", "'x-consul-lastcontact'", "]", "end", "JSON", ".", "parse", "(", "ret", ".", "body", ")", "end" ]
Get an array of all avaliable datacenters accessible by the local consul agent @param meta [Hash] output structure containing header information about the request (index) @param options [Hash] options parameter hash @return [OpenStruct] all datacenters avaliable to this consul agent
[ "Get", "an", "array", "of", "all", "avaliable", "datacenters", "accessible", "by", "the", "local", "consul", "agent" ]
cb6d06dc4ec965c30bbaf22017fd0db64b9b7677
https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/datacenter.rb#L10-L19
train
bundler/gemstash
lib/gemstash/storage.rb
Gemstash.Resource.update_properties
def update_properties(props) load_properties(true) deep_merge = proc do |_, old_value, new_value| if old_value.is_a?(Hash) && new_value.is_a?(Hash) old_value.merge(new_value, &deep_merge) else new_value end end props = properties.merge(props || {}, &deep_merge) save_properties(properties.merge(props || {})) self end
ruby
def update_properties(props) load_properties(true) deep_merge = proc do |_, old_value, new_value| if old_value.is_a?(Hash) && new_value.is_a?(Hash) old_value.merge(new_value, &deep_merge) else new_value end end props = properties.merge(props || {}, &deep_merge) save_properties(properties.merge(props || {})) self end
[ "def", "update_properties", "(", "props", ")", "load_properties", "(", "true", ")", "deep_merge", "=", "proc", "do", "|", "_", ",", "old_value", ",", "new_value", "|", "if", "old_value", ".", "is_a?", "(", "Hash", ")", "&&", "new_value", ".", "is_a?", "(", "Hash", ")", "old_value", ".", "merge", "(", "new_value", ",", "deep_merge", ")", "else", "new_value", "end", "end", "props", "=", "properties", ".", "merge", "(", "props", "||", "{", "}", ",", "deep_merge", ")", "save_properties", "(", "properties", ".", "merge", "(", "props", "||", "{", "}", ")", ")", "self", "end" ]
Update the metadata properties of this resource. The +props+ will be merged with any existing properties. Nested hashes in the properties will also be merged. @param props [Hash] the properties to add @return [Gemstash::Resource] self for chaining purposes
[ "Update", "the", "metadata", "properties", "of", "this", "resource", ".", "The", "+", "props", "+", "will", "be", "merged", "with", "any", "existing", "properties", ".", "Nested", "hashes", "in", "the", "properties", "will", "also", "be", "merged", "." ]
930cef65cebd92b2295fcbcfc9cfe1a592f09840
https://github.com/bundler/gemstash/blob/930cef65cebd92b2295fcbcfc9cfe1a592f09840/lib/gemstash/storage.rb#L197-L211
train
bundler/gemstash
lib/gemstash/storage.rb
Gemstash.Resource.property?
def property?(*keys) keys.inject(node: properties, result: true) do |memo, key| if memo[:result] memo[:result] = memo[:node].is_a?(Hash) && memo[:node].include?(key) memo[:node] = memo[:node][key] if memo[:result] end memo end[:result] end
ruby
def property?(*keys) keys.inject(node: properties, result: true) do |memo, key| if memo[:result] memo[:result] = memo[:node].is_a?(Hash) && memo[:node].include?(key) memo[:node] = memo[:node][key] if memo[:result] end memo end[:result] end
[ "def", "property?", "(", "*", "keys", ")", "keys", ".", "inject", "(", "node", ":", "properties", ",", "result", ":", "true", ")", "do", "|", "memo", ",", "key", "|", "if", "memo", "[", ":result", "]", "memo", "[", ":result", "]", "=", "memo", "[", ":node", "]", ".", "is_a?", "(", "Hash", ")", "&&", "memo", "[", ":node", "]", ".", "include?", "(", "key", ")", "memo", "[", ":node", "]", "=", "memo", "[", ":node", "]", "[", "key", "]", "if", "memo", "[", ":result", "]", "end", "memo", "end", "[", ":result", "]", "end" ]
Check if the metadata properties includes the +keys+. The +keys+ represent a nested path in the properties to check. Examples: resource = Gemstash::Storage.for("x").resource("y") resource.save({ file: "content" }, foo: "one", bar: { baz: "qux" }) resource.has_property?(:foo) # true resource.has_property?(:bar, :baz) # true resource.has_property?(:missing) # false resource.has_property?(:foo, :bar) # false @param keys [Array<Object>] one or more keys pointing to a property @return [Boolean] whether the nested keys points to a valid property
[ "Check", "if", "the", "metadata", "properties", "includes", "the", "+", "keys", "+", ".", "The", "+", "keys", "+", "represent", "a", "nested", "path", "in", "the", "properties", "to", "check", "." ]
930cef65cebd92b2295fcbcfc9cfe1a592f09840
https://github.com/bundler/gemstash/blob/930cef65cebd92b2295fcbcfc9cfe1a592f09840/lib/gemstash/storage.rb#L227-L236
train
ruby-grape/grape-entity
lib/grape_entity/entity.rb
Grape.Entity.serializable_hash
def serializable_hash(runtime_options = {}) return nil if object.nil? opts = options.merge(runtime_options || {}) root_exposure.serializable_value(self, opts) end
ruby
def serializable_hash(runtime_options = {}) return nil if object.nil? opts = options.merge(runtime_options || {}) root_exposure.serializable_value(self, opts) end
[ "def", "serializable_hash", "(", "runtime_options", "=", "{", "}", ")", "return", "nil", "if", "object", ".", "nil?", "opts", "=", "options", ".", "merge", "(", "runtime_options", "||", "{", "}", ")", "root_exposure", ".", "serializable_value", "(", "self", ",", "opts", ")", "end" ]
The serializable hash is the Entity's primary output. It is the transformed hash for the given data model and is used as the basis for serialization to JSON and other formats. @param runtime_options [Hash] Any options you pass in here will be known to the entity representation, this is where you can trigger things from conditional options etc.
[ "The", "serializable", "hash", "is", "the", "Entity", "s", "primary", "output", ".", "It", "is", "the", "transformed", "hash", "for", "the", "given", "data", "model", "and", "is", "used", "as", "the", "basis", "for", "serialization", "to", "JSON", "and", "other", "formats", "." ]
1443468f6593360b44d2ca6da5f03b19e51a2be1
https://github.com/ruby-grape/grape-entity/blob/1443468f6593360b44d2ca6da5f03b19e51a2be1/lib/grape_entity/entity.rb#L489-L495
train
jmazzi/crypt_keeper
spec/support/active_record.rb
CryptKeeper.LoggedQueries.logged_queries
def logged_queries(&block) queries = [] subscriber = ActiveSupport::Notifications .subscribe('sql.active_record') do |name, started, finished, id, payload| queries << payload[:sql] end block.call queries ensure ActiveSupport::Notifications.unsubscribe(subscriber) end
ruby
def logged_queries(&block) queries = [] subscriber = ActiveSupport::Notifications .subscribe('sql.active_record') do |name, started, finished, id, payload| queries << payload[:sql] end block.call queries ensure ActiveSupport::Notifications.unsubscribe(subscriber) end
[ "def", "logged_queries", "(", "&", "block", ")", "queries", "=", "[", "]", "subscriber", "=", "ActiveSupport", "::", "Notifications", ".", "subscribe", "(", "'sql.active_record'", ")", "do", "|", "name", ",", "started", ",", "finished", ",", "id", ",", "payload", "|", "queries", "<<", "payload", "[", ":sql", "]", "end", "block", ".", "call", "queries", "ensure", "ActiveSupport", "::", "Notifications", ".", "unsubscribe", "(", "subscriber", ")", "end" ]
Logs the queries run inside the block, and return them.
[ "Logs", "the", "queries", "run", "inside", "the", "block", "and", "return", "them", "." ]
61aff33712b5ac3559a9332253e3890baee4c6f3
https://github.com/jmazzi/crypt_keeper/blob/61aff33712b5ac3559a9332253e3890baee4c6f3/spec/support/active_record.rb#L75-L88
train
jekyll/classifier-reborn
lib/classifier-reborn/extensions/hasher.rb
ClassifierReborn.Hasher.word_hash
def word_hash(str, enable_stemmer = true, tokenizer: Tokenizer::Whitespace, token_filters: [TokenFilter::Stopword]) if token_filters.include?(TokenFilter::Stemmer) unless enable_stemmer token_filters.reject! do |token_filter| token_filter == TokenFilter::Stemmer end end else token_filters << TokenFilter::Stemmer if enable_stemmer end words = tokenizer.call(str) token_filters.each do |token_filter| words = token_filter.call(words) end d = Hash.new(0) words.each do |word| d[word.intern] += 1 end d end
ruby
def word_hash(str, enable_stemmer = true, tokenizer: Tokenizer::Whitespace, token_filters: [TokenFilter::Stopword]) if token_filters.include?(TokenFilter::Stemmer) unless enable_stemmer token_filters.reject! do |token_filter| token_filter == TokenFilter::Stemmer end end else token_filters << TokenFilter::Stemmer if enable_stemmer end words = tokenizer.call(str) token_filters.each do |token_filter| words = token_filter.call(words) end d = Hash.new(0) words.each do |word| d[word.intern] += 1 end d end
[ "def", "word_hash", "(", "str", ",", "enable_stemmer", "=", "true", ",", "tokenizer", ":", "Tokenizer", "::", "Whitespace", ",", "token_filters", ":", "[", "TokenFilter", "::", "Stopword", "]", ")", "if", "token_filters", ".", "include?", "(", "TokenFilter", "::", "Stemmer", ")", "unless", "enable_stemmer", "token_filters", ".", "reject!", "do", "|", "token_filter", "|", "token_filter", "==", "TokenFilter", "::", "Stemmer", "end", "end", "else", "token_filters", "<<", "TokenFilter", "::", "Stemmer", "if", "enable_stemmer", "end", "words", "=", "tokenizer", ".", "call", "(", "str", ")", "token_filters", ".", "each", "do", "|", "token_filter", "|", "words", "=", "token_filter", ".", "call", "(", "words", ")", "end", "d", "=", "Hash", ".", "new", "(", "0", ")", "words", ".", "each", "do", "|", "word", "|", "d", "[", "word", ".", "intern", "]", "+=", "1", "end", "d", "end" ]
Return a Hash of strings => ints. Each word in the string is stemmed, interned, and indexes to its frequency in the document.
[ "Return", "a", "Hash", "of", "strings", "=", ">", "ints", ".", "Each", "word", "in", "the", "string", "is", "stemmed", "interned", "and", "indexes", "to", "its", "frequency", "in", "the", "document", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/extensions/hasher.rb#L17-L38
train
jekyll/classifier-reborn
lib/classifier-reborn/bayes.rb
ClassifierReborn.Bayes.classify
def classify(text) result, score = classify_with_score(text) result = nil if threshold_enabled? && (score < @threshold || score == Float::INFINITY) result end
ruby
def classify(text) result, score = classify_with_score(text) result = nil if threshold_enabled? && (score < @threshold || score == Float::INFINITY) result end
[ "def", "classify", "(", "text", ")", "result", ",", "score", "=", "classify_with_score", "(", "text", ")", "result", "=", "nil", "if", "threshold_enabled?", "&&", "(", "score", "<", "@threshold", "||", "score", "==", "Float", "::", "INFINITY", ")", "result", "end" ]
Return the classification without the score
[ "Return", "the", "classification", "without", "the", "score" ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/bayes.rb#L163-L167
train
jekyll/classifier-reborn
lib/classifier-reborn/bayes.rb
ClassifierReborn.Bayes.custom_stopwords
def custom_stopwords(stopwords) unless stopwords.is_a?(Enumerable) if stopwords.strip.empty? stopwords = [] elsif File.exist?(stopwords) stopwords = File.read(stopwords).force_encoding('utf-8').split else return # Do not overwrite the default end end TokenFilter::Stopword::STOPWORDS[@language] = Set.new stopwords end
ruby
def custom_stopwords(stopwords) unless stopwords.is_a?(Enumerable) if stopwords.strip.empty? stopwords = [] elsif File.exist?(stopwords) stopwords = File.read(stopwords).force_encoding('utf-8').split else return # Do not overwrite the default end end TokenFilter::Stopword::STOPWORDS[@language] = Set.new stopwords end
[ "def", "custom_stopwords", "(", "stopwords", ")", "unless", "stopwords", ".", "is_a?", "(", "Enumerable", ")", "if", "stopwords", ".", "strip", ".", "empty?", "stopwords", "=", "[", "]", "elsif", "File", ".", "exist?", "(", "stopwords", ")", "stopwords", "=", "File", ".", "read", "(", "stopwords", ")", ".", "force_encoding", "(", "'utf-8'", ")", ".", "split", "else", "return", "# Do not overwrite the default", "end", "end", "TokenFilter", "::", "Stopword", "::", "STOPWORDS", "[", "@language", "]", "=", "Set", ".", "new", "stopwords", "end" ]
Overwrites the default stopwords for current language with supplied list of stopwords or file
[ "Overwrites", "the", "default", "stopwords", "for", "current", "language", "with", "supplied", "list", "of", "stopwords", "or", "file" ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/bayes.rb#L269-L280
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.build_index
def build_index(cutoff = 0.75) return unless needs_rebuild? make_word_list doc_list = @items.values tda = doc_list.collect { |node| node.raw_vector_with(@word_list) } if $GSL tdm = GSL::Matrix.alloc(*tda).trans ntdm = build_reduced_matrix(tdm, cutoff) ntdm.size[1].times do |col| vec = GSL::Vector.alloc(ntdm.column(col)).row doc_list[col].lsi_vector = vec doc_list[col].lsi_norm = vec.normalize end else tdm = Matrix.rows(tda).trans ntdm = build_reduced_matrix(tdm, cutoff) ntdm.column_size.times do |col| doc_list[col].lsi_vector = ntdm.column(col) if doc_list[col] if ntdm.column(col).zero? doc_list[col].lsi_norm = ntdm.column(col) if doc_list[col] else doc_list[col].lsi_norm = ntdm.column(col).normalize if doc_list[col] end end end @built_at_version = @version end
ruby
def build_index(cutoff = 0.75) return unless needs_rebuild? make_word_list doc_list = @items.values tda = doc_list.collect { |node| node.raw_vector_with(@word_list) } if $GSL tdm = GSL::Matrix.alloc(*tda).trans ntdm = build_reduced_matrix(tdm, cutoff) ntdm.size[1].times do |col| vec = GSL::Vector.alloc(ntdm.column(col)).row doc_list[col].lsi_vector = vec doc_list[col].lsi_norm = vec.normalize end else tdm = Matrix.rows(tda).trans ntdm = build_reduced_matrix(tdm, cutoff) ntdm.column_size.times do |col| doc_list[col].lsi_vector = ntdm.column(col) if doc_list[col] if ntdm.column(col).zero? doc_list[col].lsi_norm = ntdm.column(col) if doc_list[col] else doc_list[col].lsi_norm = ntdm.column(col).normalize if doc_list[col] end end end @built_at_version = @version end
[ "def", "build_index", "(", "cutoff", "=", "0.75", ")", "return", "unless", "needs_rebuild?", "make_word_list", "doc_list", "=", "@items", ".", "values", "tda", "=", "doc_list", ".", "collect", "{", "|", "node", "|", "node", ".", "raw_vector_with", "(", "@word_list", ")", "}", "if", "$GSL", "tdm", "=", "GSL", "::", "Matrix", ".", "alloc", "(", "tda", ")", ".", "trans", "ntdm", "=", "build_reduced_matrix", "(", "tdm", ",", "cutoff", ")", "ntdm", ".", "size", "[", "1", "]", ".", "times", "do", "|", "col", "|", "vec", "=", "GSL", "::", "Vector", ".", "alloc", "(", "ntdm", ".", "column", "(", "col", ")", ")", ".", "row", "doc_list", "[", "col", "]", ".", "lsi_vector", "=", "vec", "doc_list", "[", "col", "]", ".", "lsi_norm", "=", "vec", ".", "normalize", "end", "else", "tdm", "=", "Matrix", ".", "rows", "(", "tda", ")", ".", "trans", "ntdm", "=", "build_reduced_matrix", "(", "tdm", ",", "cutoff", ")", "ntdm", ".", "column_size", ".", "times", "do", "|", "col", "|", "doc_list", "[", "col", "]", ".", "lsi_vector", "=", "ntdm", ".", "column", "(", "col", ")", "if", "doc_list", "[", "col", "]", "if", "ntdm", ".", "column", "(", "col", ")", ".", "zero?", "doc_list", "[", "col", "]", ".", "lsi_norm", "=", "ntdm", ".", "column", "(", "col", ")", "if", "doc_list", "[", "col", "]", "else", "doc_list", "[", "col", "]", ".", "lsi_norm", "=", "ntdm", ".", "column", "(", "col", ")", ".", "normalize", "if", "doc_list", "[", "col", "]", "end", "end", "end", "@built_at_version", "=", "@version", "end" ]
This function rebuilds the index if needs_rebuild? returns true. For very large document spaces, this indexing operation may take some time to complete, so it may be wise to place the operation in another thread. As a rule, indexing will be fairly swift on modern machines until you have well over 500 documents indexed, or have an incredibly diverse vocabulary for your documents. The optional parameter "cutoff" is a tuning parameter. When the index is built, a certain number of s-values are discarded from the system. The cutoff parameter tells the indexer how many of these values to keep. A value of 1 for cutoff means that no semantic analysis will take place, turning the LSI class into a simple vector search engine.
[ "This", "function", "rebuilds", "the", "index", "if", "needs_rebuild?", "returns", "true", ".", "For", "very", "large", "document", "spaces", "this", "indexing", "operation", "may", "take", "some", "time", "to", "complete", "so", "it", "may", "be", "wise", "to", "place", "the", "operation", "in", "another", "thread", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L133-L165
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.highest_relative_content
def highest_relative_content(max_chunks = 10) return [] if needs_rebuild? avg_density = {} @items.each_key { |item| avg_density[item] = proximity_array_for_content(item).inject(0.0) { |x, y| x + y[1] } } avg_density.keys.sort_by { |x| avg_density[x] }.reverse[0..max_chunks - 1].map end
ruby
def highest_relative_content(max_chunks = 10) return [] if needs_rebuild? avg_density = {} @items.each_key { |item| avg_density[item] = proximity_array_for_content(item).inject(0.0) { |x, y| x + y[1] } } avg_density.keys.sort_by { |x| avg_density[x] }.reverse[0..max_chunks - 1].map end
[ "def", "highest_relative_content", "(", "max_chunks", "=", "10", ")", "return", "[", "]", "if", "needs_rebuild?", "avg_density", "=", "{", "}", "@items", ".", "each_key", "{", "|", "item", "|", "avg_density", "[", "item", "]", "=", "proximity_array_for_content", "(", "item", ")", ".", "inject", "(", "0.0", ")", "{", "|", "x", ",", "y", "|", "x", "+", "y", "[", "1", "]", "}", "}", "avg_density", ".", "keys", ".", "sort_by", "{", "|", "x", "|", "avg_density", "[", "x", "]", "}", ".", "reverse", "[", "0", "..", "max_chunks", "-", "1", "]", ".", "map", "end" ]
This method returns max_chunks entries, ordered by their average semantic rating. Essentially, the average distance of each entry from all other entries is calculated, the highest are returned. This can be used to build a summary service, or to provide more information about your dataset's general content. For example, if you were to use categorize on the results of this data, you could gather information on what your dataset is generally about.
[ "This", "method", "returns", "max_chunks", "entries", "ordered", "by", "their", "average", "semantic", "rating", ".", "Essentially", "the", "average", "distance", "of", "each", "entry", "from", "all", "other", "entries", "is", "calculated", "the", "highest", "are", "returned", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L175-L182
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.proximity_array_for_content
def proximity_array_for_content(doc, &block) return [] if needs_rebuild? content_node = node_for_content(doc, &block) result = @items.keys.collect do |item| val = if $GSL content_node.search_vector * @items[item].transposed_search_vector else (Matrix[content_node.search_vector] * @items[item].search_vector)[0] end [item, val] end result.sort_by { |x| x[1] }.reverse end
ruby
def proximity_array_for_content(doc, &block) return [] if needs_rebuild? content_node = node_for_content(doc, &block) result = @items.keys.collect do |item| val = if $GSL content_node.search_vector * @items[item].transposed_search_vector else (Matrix[content_node.search_vector] * @items[item].search_vector)[0] end [item, val] end result.sort_by { |x| x[1] }.reverse end
[ "def", "proximity_array_for_content", "(", "doc", ",", "&", "block", ")", "return", "[", "]", "if", "needs_rebuild?", "content_node", "=", "node_for_content", "(", "doc", ",", "block", ")", "result", "=", "@items", ".", "keys", ".", "collect", "do", "|", "item", "|", "val", "=", "if", "$GSL", "content_node", ".", "search_vector", "*", "@items", "[", "item", "]", ".", "transposed_search_vector", "else", "(", "Matrix", "[", "content_node", ".", "search_vector", "]", "*", "@items", "[", "item", "]", ".", "search_vector", ")", "[", "0", "]", "end", "[", "item", ",", "val", "]", "end", "result", ".", "sort_by", "{", "|", "x", "|", "x", "[", "1", "]", "}", ".", "reverse", "end" ]
This function is the primitive that find_related and classify build upon. It returns an array of 2-element arrays. The first element of this array is a document, and the second is its "score", defining how "close" it is to other indexed items. These values are somewhat arbitrary, having to do with the vector space created by your content, so the magnitude is interpretable but not always meaningful between indexes. The parameter doc is the content to compare. If that content is not indexed, you can pass an optional block to define how to create the text data. See add_item for examples of how this works.
[ "This", "function", "is", "the", "primitive", "that", "find_related", "and", "classify", "build", "upon", ".", "It", "returns", "an", "array", "of", "2", "-", "element", "arrays", ".", "The", "first", "element", "of", "this", "array", "is", "a", "document", "and", "the", "second", "is", "its", "score", "defining", "how", "close", "it", "is", "to", "other", "indexed", "items", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L196-L210
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.proximity_norms_for_content
def proximity_norms_for_content(doc, &block) return [] if needs_rebuild? content_node = node_for_content(doc, &block) if $GSL && content_node.raw_norm.isnan?.all? puts "There are no documents that are similar to #{doc}" else content_node_norms(content_node) end end
ruby
def proximity_norms_for_content(doc, &block) return [] if needs_rebuild? content_node = node_for_content(doc, &block) if $GSL && content_node.raw_norm.isnan?.all? puts "There are no documents that are similar to #{doc}" else content_node_norms(content_node) end end
[ "def", "proximity_norms_for_content", "(", "doc", ",", "&", "block", ")", "return", "[", "]", "if", "needs_rebuild?", "content_node", "=", "node_for_content", "(", "doc", ",", "block", ")", "if", "$GSL", "&&", "content_node", ".", "raw_norm", ".", "isnan?", ".", "all?", "puts", "\"There are no documents that are similar to #{doc}\"", "else", "content_node_norms", "(", "content_node", ")", "end", "end" ]
Similar to proximity_array_for_content, this function takes similar arguments and returns a similar array. However, it uses the normalized calculated vectors instead of their full versions. This is useful when you're trying to perform operations on content that is much smaller than the text you're working with. search uses this primitive.
[ "Similar", "to", "proximity_array_for_content", "this", "function", "takes", "similar", "arguments", "and", "returns", "a", "similar", "array", ".", "However", "it", "uses", "the", "normalized", "calculated", "vectors", "instead", "of", "their", "full", "versions", ".", "This", "is", "useful", "when", "you", "re", "trying", "to", "perform", "operations", "on", "content", "that", "is", "much", "smaller", "than", "the", "text", "you", "re", "working", "with", ".", "search", "uses", "this", "primitive", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L217-L226
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.search
def search(string, max_nearest = 3) return [] if needs_rebuild? carry = proximity_norms_for_content(string) unless carry.nil? result = carry.collect { |x| x[0] } result[0..max_nearest - 1] end end
ruby
def search(string, max_nearest = 3) return [] if needs_rebuild? carry = proximity_norms_for_content(string) unless carry.nil? result = carry.collect { |x| x[0] } result[0..max_nearest - 1] end end
[ "def", "search", "(", "string", ",", "max_nearest", "=", "3", ")", "return", "[", "]", "if", "needs_rebuild?", "carry", "=", "proximity_norms_for_content", "(", "string", ")", "unless", "carry", ".", "nil?", "result", "=", "carry", ".", "collect", "{", "|", "x", "|", "x", "[", "0", "]", "}", "result", "[", "0", "..", "max_nearest", "-", "1", "]", "end", "end" ]
This function allows for text-based search of your index. Unlike other functions like find_related and classify, search only takes short strings. It will also ignore factors like repeated words. It is best for short, google-like search terms. A search will first priortize lexical relationships, then semantic ones. While this may seem backwards compared to the other functions that LSI supports, it is actually the same algorithm, just applied on a smaller document.
[ "This", "function", "allows", "for", "text", "-", "based", "search", "of", "your", "index", ".", "Unlike", "other", "functions", "like", "find_related", "and", "classify", "search", "only", "takes", "short", "strings", ".", "It", "will", "also", "ignore", "factors", "like", "repeated", "words", ".", "It", "is", "best", "for", "short", "google", "-", "like", "search", "terms", ".", "A", "search", "will", "first", "priortize", "lexical", "relationships", "then", "semantic", "ones", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L248-L256
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.find_related
def find_related(doc, max_nearest = 3, &block) carry = proximity_array_for_content(doc, &block).reject { |pair| pair[0].eql? doc } result = carry.collect { |x| x[0] } result[0..max_nearest - 1] end
ruby
def find_related(doc, max_nearest = 3, &block) carry = proximity_array_for_content(doc, &block).reject { |pair| pair[0].eql? doc } result = carry.collect { |x| x[0] } result[0..max_nearest - 1] end
[ "def", "find_related", "(", "doc", ",", "max_nearest", "=", "3", ",", "&", "block", ")", "carry", "=", "proximity_array_for_content", "(", "doc", ",", "block", ")", ".", "reject", "{", "|", "pair", "|", "pair", "[", "0", "]", ".", "eql?", "doc", "}", "result", "=", "carry", ".", "collect", "{", "|", "x", "|", "x", "[", "0", "]", "}", "result", "[", "0", "..", "max_nearest", "-", "1", "]", "end" ]
This function takes content and finds other documents that are semantically "close", returning an array of documents sorted from most to least relavant. max_nearest specifies the number of documents to return. A value of 0 means that it returns all the indexed documents, sorted by relavence. This is particularly useful for identifing clusters in your document space. For example you may want to identify several "What's Related" items for weblog articles, or find paragraphs that relate to each other in an essay.
[ "This", "function", "takes", "content", "and", "finds", "other", "documents", "that", "are", "semantically", "close", "returning", "an", "array", "of", "documents", "sorted", "from", "most", "to", "least", "relavant", ".", "max_nearest", "specifies", "the", "number", "of", "documents", "to", "return", ".", "A", "value", "of", "0", "means", "that", "it", "returns", "all", "the", "indexed", "documents", "sorted", "by", "relavence", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L267-L272
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.classify
def classify(doc, cutoff = 0.30, &block) scored_categories(doc, cutoff, &block).last.first end
ruby
def classify(doc, cutoff = 0.30, &block) scored_categories(doc, cutoff, &block).last.first end
[ "def", "classify", "(", "doc", ",", "cutoff", "=", "0.30", ",", "&", "block", ")", "scored_categories", "(", "doc", ",", "cutoff", ",", "block", ")", ".", "last", ".", "first", "end" ]
Return the most obvious category without the score
[ "Return", "the", "most", "obvious", "category", "without", "the", "score" ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L280-L282
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.scored_categories
def scored_categories(doc, cutoff = 0.30, &block) icutoff = (@items.size * cutoff).round carry = proximity_array_for_content(doc, &block) carry = carry[0..icutoff - 1] votes = Hash.new(0.0) carry.each do |pair| @items[pair[0]].categories.each do |category| votes[category] += pair[1] end end votes.sort_by { |_, score| score } end
ruby
def scored_categories(doc, cutoff = 0.30, &block) icutoff = (@items.size * cutoff).round carry = proximity_array_for_content(doc, &block) carry = carry[0..icutoff - 1] votes = Hash.new(0.0) carry.each do |pair| @items[pair[0]].categories.each do |category| votes[category] += pair[1] end end votes.sort_by { |_, score| score } end
[ "def", "scored_categories", "(", "doc", ",", "cutoff", "=", "0.30", ",", "&", "block", ")", "icutoff", "=", "(", "@items", ".", "size", "*", "cutoff", ")", ".", "round", "carry", "=", "proximity_array_for_content", "(", "doc", ",", "block", ")", "carry", "=", "carry", "[", "0", "..", "icutoff", "-", "1", "]", "votes", "=", "Hash", ".", "new", "(", "0.0", ")", "carry", ".", "each", "do", "|", "pair", "|", "@items", "[", "pair", "[", "0", "]", "]", ".", "categories", ".", "each", "do", "|", "category", "|", "votes", "[", "category", "]", "+=", "pair", "[", "1", "]", "end", "end", "votes", ".", "sort_by", "{", "|", "_", ",", "score", "|", "score", "}", "end" ]
This function uses a voting system to categorize documents, based on the categories of other documents. It uses the same logic as the find_related function to find related documents, then returns the list of sorted categories. cutoff signifies the number of documents to consider when clasifying text. A cutoff of 1 means that every document in the index votes on what category the document is in. This may not always make sense.
[ "This", "function", "uses", "a", "voting", "system", "to", "categorize", "documents", "based", "on", "the", "categories", "of", "other", "documents", ".", "It", "uses", "the", "same", "logic", "as", "the", "find_related", "function", "to", "find", "related", "documents", "then", "returns", "the", "list", "of", "sorted", "categories", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L293-L305
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi.rb
ClassifierReborn.LSI.highest_ranked_stems
def highest_ranked_stems(doc, count = 3) raise 'Requested stem ranking on non-indexed content!' unless @items[doc] content_vector_array = node_for_content(doc).lsi_vector.to_a top_n = content_vector_array.sort.reverse[0..count - 1] top_n.collect { |x| @word_list.word_for_index(content_vector_array.index(x)) } end
ruby
def highest_ranked_stems(doc, count = 3) raise 'Requested stem ranking on non-indexed content!' unless @items[doc] content_vector_array = node_for_content(doc).lsi_vector.to_a top_n = content_vector_array.sort.reverse[0..count - 1] top_n.collect { |x| @word_list.word_for_index(content_vector_array.index(x)) } end
[ "def", "highest_ranked_stems", "(", "doc", ",", "count", "=", "3", ")", "raise", "'Requested stem ranking on non-indexed content!'", "unless", "@items", "[", "doc", "]", "content_vector_array", "=", "node_for_content", "(", "doc", ")", ".", "lsi_vector", ".", "to_a", "top_n", "=", "content_vector_array", ".", "sort", ".", "reverse", "[", "0", "..", "count", "-", "1", "]", "top_n", ".", "collect", "{", "|", "x", "|", "@word_list", ".", "word_for_index", "(", "content_vector_array", ".", "index", "(", "x", ")", ")", "}", "end" ]
Prototype, only works on indexed documents. I have no clue if this is going to work, but in theory it's supposed to.
[ "Prototype", "only", "works", "on", "indexed", "documents", ".", "I", "have", "no", "clue", "if", "this", "is", "going", "to", "work", "but", "in", "theory", "it", "s", "supposed", "to", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi.rb#L310-L316
train
jekyll/classifier-reborn
lib/classifier-reborn/lsi/content_node.rb
ClassifierReborn.ContentNode.raw_vector_with
def raw_vector_with(word_list) vec = if $GSL GSL::Vector.alloc(word_list.size) else Array.new(word_list.size, 0) end @word_hash.each_key do |word| vec[word_list[word]] = @word_hash[word] if word_list[word] end # Perform the scaling transform and force floating point arithmetic if $GSL sum = 0.0 vec.each { |v| sum += v } total_words = sum else total_words = vec.reduce(0, :+).to_f end total_unique_words = 0 if $GSL vec.each { |word| total_unique_words += 1 if word != 0.0 } else total_unique_words = vec.count { |word| word != 0 } end # Perform first-order association transform if this vector has more # then one word in it. if total_words > 1.0 && total_unique_words > 1 weighted_total = 0.0 # Cache calculations, this takes too long on large indexes cached_calcs = Hash.new do |hash, term| hash[term] = ((term / total_words) * Math.log(term / total_words)) end vec.each do |term| weighted_total += cached_calcs[term] if term > 0.0 end # Cache calculations, this takes too long on large indexes cached_calcs = Hash.new do |hash, val| hash[val] = Math.log(val + 1) / -weighted_total end vec.collect! do |val| cached_calcs[val] end end if $GSL @raw_norm = vec.normalize @raw_vector = vec else @raw_norm = Vector[*vec].normalize @raw_vector = Vector[*vec] end end
ruby
def raw_vector_with(word_list) vec = if $GSL GSL::Vector.alloc(word_list.size) else Array.new(word_list.size, 0) end @word_hash.each_key do |word| vec[word_list[word]] = @word_hash[word] if word_list[word] end # Perform the scaling transform and force floating point arithmetic if $GSL sum = 0.0 vec.each { |v| sum += v } total_words = sum else total_words = vec.reduce(0, :+).to_f end total_unique_words = 0 if $GSL vec.each { |word| total_unique_words += 1 if word != 0.0 } else total_unique_words = vec.count { |word| word != 0 } end # Perform first-order association transform if this vector has more # then one word in it. if total_words > 1.0 && total_unique_words > 1 weighted_total = 0.0 # Cache calculations, this takes too long on large indexes cached_calcs = Hash.new do |hash, term| hash[term] = ((term / total_words) * Math.log(term / total_words)) end vec.each do |term| weighted_total += cached_calcs[term] if term > 0.0 end # Cache calculations, this takes too long on large indexes cached_calcs = Hash.new do |hash, val| hash[val] = Math.log(val + 1) / -weighted_total end vec.collect! do |val| cached_calcs[val] end end if $GSL @raw_norm = vec.normalize @raw_vector = vec else @raw_norm = Vector[*vec].normalize @raw_vector = Vector[*vec] end end
[ "def", "raw_vector_with", "(", "word_list", ")", "vec", "=", "if", "$GSL", "GSL", "::", "Vector", ".", "alloc", "(", "word_list", ".", "size", ")", "else", "Array", ".", "new", "(", "word_list", ".", "size", ",", "0", ")", "end", "@word_hash", ".", "each_key", "do", "|", "word", "|", "vec", "[", "word_list", "[", "word", "]", "]", "=", "@word_hash", "[", "word", "]", "if", "word_list", "[", "word", "]", "end", "# Perform the scaling transform and force floating point arithmetic", "if", "$GSL", "sum", "=", "0.0", "vec", ".", "each", "{", "|", "v", "|", "sum", "+=", "v", "}", "total_words", "=", "sum", "else", "total_words", "=", "vec", ".", "reduce", "(", "0", ",", ":+", ")", ".", "to_f", "end", "total_unique_words", "=", "0", "if", "$GSL", "vec", ".", "each", "{", "|", "word", "|", "total_unique_words", "+=", "1", "if", "word", "!=", "0.0", "}", "else", "total_unique_words", "=", "vec", ".", "count", "{", "|", "word", "|", "word", "!=", "0", "}", "end", "# Perform first-order association transform if this vector has more", "# then one word in it.", "if", "total_words", ">", "1.0", "&&", "total_unique_words", ">", "1", "weighted_total", "=", "0.0", "# Cache calculations, this takes too long on large indexes", "cached_calcs", "=", "Hash", ".", "new", "do", "|", "hash", ",", "term", "|", "hash", "[", "term", "]", "=", "(", "(", "term", "/", "total_words", ")", "*", "Math", ".", "log", "(", "term", "/", "total_words", ")", ")", "end", "vec", ".", "each", "do", "|", "term", "|", "weighted_total", "+=", "cached_calcs", "[", "term", "]", "if", "term", ">", "0.0", "end", "# Cache calculations, this takes too long on large indexes", "cached_calcs", "=", "Hash", ".", "new", "do", "|", "hash", ",", "val", "|", "hash", "[", "val", "]", "=", "Math", ".", "log", "(", "val", "+", "1", ")", "/", "-", "weighted_total", "end", "vec", ".", "collect!", "do", "|", "val", "|", "cached_calcs", "[", "val", "]", "end", "end", "if", "$GSL", "@raw_norm", "=", "vec", ".", "normalize", "@raw_vector", "=", "vec", "else", "@raw_norm", "=", "Vector", "[", "vec", "]", ".", "normalize", "@raw_vector", "=", "Vector", "[", "vec", "]", "end", "end" ]
Creates the raw vector out of word_hash using word_list as the key for mapping the vector space.
[ "Creates", "the", "raw", "vector", "out", "of", "word_hash", "using", "word_list", "as", "the", "key", "for", "mapping", "the", "vector", "space", "." ]
849ba0834c5a9be78147a9072e599187e2203fce
https://github.com/jekyll/classifier-reborn/blob/849ba0834c5a9be78147a9072e599187e2203fce/lib/classifier-reborn/lsi/content_node.rb#L40-L98
train
piotrmurach/tty-table
lib/tty/table.rb
TTY.Table.rotate_horizontal
def rotate_horizontal return unless rotated? head, body = orientation.slice(self) if header && header.empty? @header = head[0] @rows = body.map { |row| to_row(row, @header) } else @rows = body.map { |row| to_row(row) } end end
ruby
def rotate_horizontal return unless rotated? head, body = orientation.slice(self) if header && header.empty? @header = head[0] @rows = body.map { |row| to_row(row, @header) } else @rows = body.map { |row| to_row(row) } end end
[ "def", "rotate_horizontal", "return", "unless", "rotated?", "head", ",", "body", "=", "orientation", ".", "slice", "(", "self", ")", "if", "header", "&&", "header", ".", "empty?", "@header", "=", "head", "[", "0", "]", "@rows", "=", "body", ".", "map", "{", "|", "row", "|", "to_row", "(", "row", ",", "@header", ")", "}", "else", "@rows", "=", "body", ".", "map", "{", "|", "row", "|", "to_row", "(", "row", ")", "}", "end", "end" ]
Rotate the table horizontally @api private
[ "Rotate", "the", "table", "horizontally" ]
b89bc3615bc1e834e089e4451e7444ff90bce4a8
https://github.com/piotrmurach/tty-table/blob/b89bc3615bc1e834e089e4451e7444ff90bce4a8/lib/tty/table.rb#L190-L199
train
piotrmurach/tty-table
lib/tty/table.rb
TTY.Table.row
def row(index, &block) if block_given? rows.fetch(index) { return self }.each(&block) self else rows.fetch(index) { return nil } end end
ruby
def row(index, &block) if block_given? rows.fetch(index) { return self }.each(&block) self else rows.fetch(index) { return nil } end end
[ "def", "row", "(", "index", ",", "&", "block", ")", "if", "block_given?", "rows", ".", "fetch", "(", "index", ")", "{", "return", "self", "}", ".", "each", "(", "block", ")", "self", "else", "rows", ".", "fetch", "(", "index", ")", "{", "return", "nil", "}", "end", "end" ]
Return a row number at the index of the table as an Array. When a block is given, the elements of that Array are iterated over. @example rows = [['a1', 'a2'], ['b1', 'b2']] table = TTY::Table.new rows: rows table.row(1) { |row| ... } @param [Integer] index @yield [] optional block to execute in the iteration operation @return [self] @api public
[ "Return", "a", "row", "number", "at", "the", "index", "of", "the", "table", "as", "an", "Array", ".", "When", "a", "block", "is", "given", "the", "elements", "of", "that", "Array", "are", "iterated", "over", "." ]
b89bc3615bc1e834e089e4451e7444ff90bce4a8
https://github.com/piotrmurach/tty-table/blob/b89bc3615bc1e834e089e4451e7444ff90bce4a8/lib/tty/table.rb#L249-L256
train
piotrmurach/tty-table
lib/tty/table.rb
TTY.Table.column
def column(index) index_unknown = index.is_a?(Integer) && (index >= columns_size || index < 0) if block_given? return self if index_unknown rows.map { |row| yield row[index] } else return nil if index_unknown rows.map { |row| row[index] }.compact end end
ruby
def column(index) index_unknown = index.is_a?(Integer) && (index >= columns_size || index < 0) if block_given? return self if index_unknown rows.map { |row| yield row[index] } else return nil if index_unknown rows.map { |row| row[index] }.compact end end
[ "def", "column", "(", "index", ")", "index_unknown", "=", "index", ".", "is_a?", "(", "Integer", ")", "&&", "(", "index", ">=", "columns_size", "||", "index", "<", "0", ")", "if", "block_given?", "return", "self", "if", "index_unknown", "rows", ".", "map", "{", "|", "row", "|", "yield", "row", "[", "index", "]", "}", "else", "return", "nil", "if", "index_unknown", "rows", ".", "map", "{", "|", "row", "|", "row", "[", "index", "]", "}", ".", "compact", "end", "end" ]
Return a column number at the index of the table as an Array. If the table has a header then column can be searched by header name. When a block is given, the elements of that Array are iterated over. @example header = [:h1, :h2] rows = [ ['a1', 'a2'], ['b1', 'b2'] ] table = TTY::Table.new :rows => rows, :header => header table.column(1) table.column(1) { |element| ... } table.column(:h1) table.column(:h1) { |element| ... } @param [Integer, String, Symbol] index @yield [] optional block to execute in the iteration operation @return [self] @api public
[ "Return", "a", "column", "number", "at", "the", "index", "of", "the", "table", "as", "an", "Array", ".", "If", "the", "table", "has", "a", "header", "then", "column", "can", "be", "searched", "by", "header", "name", ".", "When", "a", "block", "is", "given", "the", "elements", "of", "that", "Array", "are", "iterated", "over", "." ]
b89bc3615bc1e834e089e4451e7444ff90bce4a8
https://github.com/piotrmurach/tty-table/blob/b89bc3615bc1e834e089e4451e7444ff90bce4a8/lib/tty/table.rb#L279-L288
train
piotrmurach/tty-table
lib/tty/table.rb
TTY.Table.<<
def <<(row) if row == Border::SEPARATOR separators << columns_size - (header ? 0 : 2) else rows_copy = rows.dup assert_row_sizes rows_copy << row rows << to_row(row) end self end
ruby
def <<(row) if row == Border::SEPARATOR separators << columns_size - (header ? 0 : 2) else rows_copy = rows.dup assert_row_sizes rows_copy << row rows << to_row(row) end self end
[ "def", "<<", "(", "row", ")", "if", "row", "==", "Border", "::", "SEPARATOR", "separators", "<<", "columns_size", "-", "(", "header", "?", "0", ":", "2", ")", "else", "rows_copy", "=", "rows", ".", "dup", "assert_row_sizes", "rows_copy", "<<", "row", "rows", "<<", "to_row", "(", "row", ")", "end", "self", "end" ]
Add row to table @param [Array] row @return [self] @api public
[ "Add", "row", "to", "table" ]
b89bc3615bc1e834e089e4451e7444ff90bce4a8
https://github.com/piotrmurach/tty-table/blob/b89bc3615bc1e834e089e4451e7444ff90bce4a8/lib/tty/table.rb#L297-L306
train
piotrmurach/tty-table
lib/tty/table.rb
TTY.Table.render_with
def render_with(border_class, renderer_type=(not_set=true), options={}, &block) unless not_set if renderer_type.respond_to?(:to_hash) options = renderer_type else options[:renderer] = renderer_type end end Renderer.render_with(border_class, self, options, &block) end
ruby
def render_with(border_class, renderer_type=(not_set=true), options={}, &block) unless not_set if renderer_type.respond_to?(:to_hash) options = renderer_type else options[:renderer] = renderer_type end end Renderer.render_with(border_class, self, options, &block) end
[ "def", "render_with", "(", "border_class", ",", "renderer_type", "=", "(", "not_set", "=", "true", ")", ",", "options", "=", "{", "}", ",", "&", "block", ")", "unless", "not_set", "if", "renderer_type", ".", "respond_to?", "(", ":to_hash", ")", "options", "=", "renderer_type", "else", "options", "[", ":renderer", "]", "=", "renderer_type", "end", "end", "Renderer", ".", "render_with", "(", "border_class", ",", "self", ",", "options", ",", "block", ")", "end" ]
Render a given table using custom border class. @param [TTY::Table::Border] border_class @param [Symbol] renderer_type @param [Hash] options @yield [renderer] @yieldparam [TTY::Table::Renderer] renderer the renderer for the table @return [String] @api public
[ "Render", "a", "given", "table", "using", "custom", "border", "class", "." ]
b89bc3615bc1e834e089e4451e7444ff90bce4a8
https://github.com/piotrmurach/tty-table/blob/b89bc3615bc1e834e089e4451e7444ff90bce4a8/lib/tty/table.rb#L459-L469
train
piotrmurach/tty-table
lib/tty/table.rb
TTY.Table.coerce
def coerce(rows) coerced_rows = [] @converter.convert(rows).to(:array).each do |row| if row == Border::SEPARATOR separators << coerced_rows.length - (header ? 0 : 1) else coerced_rows << to_row(row, header) end end coerced_rows end
ruby
def coerce(rows) coerced_rows = [] @converter.convert(rows).to(:array).each do |row| if row == Border::SEPARATOR separators << coerced_rows.length - (header ? 0 : 1) else coerced_rows << to_row(row, header) end end coerced_rows end
[ "def", "coerce", "(", "rows", ")", "coerced_rows", "=", "[", "]", "@converter", ".", "convert", "(", "rows", ")", ".", "to", "(", ":array", ")", ".", "each", "do", "|", "row", "|", "if", "row", "==", "Border", "::", "SEPARATOR", "separators", "<<", "coerced_rows", ".", "length", "-", "(", "header", "?", "0", ":", "1", ")", "else", "coerced_rows", "<<", "to_row", "(", "row", ",", "header", ")", "end", "end", "coerced_rows", "end" ]
Coerce an Enumerable into a Table This coercion mechanism is used by Table to handle Enumerable types and force them into array type. @param [Enumerable] rows the object to coerce @return [Array] @api public
[ "Coerce", "an", "Enumerable", "into", "a", "Table", "This", "coercion", "mechanism", "is", "used", "by", "Table", "to", "handle", "Enumerable", "types", "and", "force", "them", "into", "array", "type", "." ]
b89bc3615bc1e834e089e4451e7444ff90bce4a8
https://github.com/piotrmurach/tty-table/blob/b89bc3615bc1e834e089e4451e7444ff90bce4a8/lib/tty/table.rb#L481-L491
train
Shopify/statsd-instrument
lib/statsd/instrument.rb
StatsD.Instrument.statsd_measure
def statsd_measure(method, name, *metric_options) add_to_method(method, name, :measure) do define_method(method) do |*args, &block| StatsD.measure(StatsD::Instrument.generate_metric_name(name, self, *args), *metric_options) { super(*args, &block) } end end end
ruby
def statsd_measure(method, name, *metric_options) add_to_method(method, name, :measure) do define_method(method) do |*args, &block| StatsD.measure(StatsD::Instrument.generate_metric_name(name, self, *args), *metric_options) { super(*args, &block) } end end end
[ "def", "statsd_measure", "(", "method", ",", "name", ",", "*", "metric_options", ")", "add_to_method", "(", "method", ",", "name", ",", ":measure", ")", "do", "define_method", "(", "method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "StatsD", ".", "measure", "(", "StatsD", "::", "Instrument", ".", "generate_metric_name", "(", "name", ",", "self", ",", "args", ")", ",", "metric_options", ")", "{", "super", "(", "args", ",", "block", ")", "}", "end", "end", "end" ]
Adds execution duration instrumentation to a method as a timing. @param method [Symbol] The name of the method to instrument. @param name [String, #call] The name of the metric to use. You can also pass in a callable to dynamically generate a metric name @param metric_options (see StatsD#measure) @return [void]
[ "Adds", "execution", "duration", "instrumentation", "to", "a", "method", "as", "a", "timing", "." ]
f1a96b4f86811ea1505a34e10a738dc22b19effa
https://github.com/Shopify/statsd-instrument/blob/f1a96b4f86811ea1505a34e10a738dc22b19effa/lib/statsd/instrument.rb#L78-L84
train
Shopify/statsd-instrument
lib/statsd/instrument.rb
StatsD.Instrument.statsd_distribution
def statsd_distribution(method, name, *metric_options) add_to_method(method, name, :distribution) do define_method(method) do |*args, &block| StatsD.distribution(StatsD::Instrument.generate_metric_name(name, self, *args), *metric_options) { super(*args, &block) } end end end
ruby
def statsd_distribution(method, name, *metric_options) add_to_method(method, name, :distribution) do define_method(method) do |*args, &block| StatsD.distribution(StatsD::Instrument.generate_metric_name(name, self, *args), *metric_options) { super(*args, &block) } end end end
[ "def", "statsd_distribution", "(", "method", ",", "name", ",", "*", "metric_options", ")", "add_to_method", "(", "method", ",", "name", ",", ":distribution", ")", "do", "define_method", "(", "method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "StatsD", ".", "distribution", "(", "StatsD", "::", "Instrument", ".", "generate_metric_name", "(", "name", ",", "self", ",", "args", ")", ",", "metric_options", ")", "{", "super", "(", "args", ",", "block", ")", "}", "end", "end", "end" ]
Adds execution duration instrumentation to a method as a distribution. @param method [Symbol] The name of the method to instrument. @param name [String, #call] The name of the metric to use. You can also pass in a callable to dynamically generate a metric name @param metric_options (see StatsD#measure) @return [void] @note Supported by the datadog implementation only (in beta)
[ "Adds", "execution", "duration", "instrumentation", "to", "a", "method", "as", "a", "distribution", "." ]
f1a96b4f86811ea1505a34e10a738dc22b19effa
https://github.com/Shopify/statsd-instrument/blob/f1a96b4f86811ea1505a34e10a738dc22b19effa/lib/statsd/instrument.rb#L94-L100
train
Shopify/statsd-instrument
lib/statsd/instrument.rb
StatsD.Instrument.statsd_count
def statsd_count(method, name, *metric_options) add_to_method(method, name, :count) do define_method(method) do |*args, &block| StatsD.increment(StatsD::Instrument.generate_metric_name(name, self, *args), 1, *metric_options) super(*args, &block) end end end
ruby
def statsd_count(method, name, *metric_options) add_to_method(method, name, :count) do define_method(method) do |*args, &block| StatsD.increment(StatsD::Instrument.generate_metric_name(name, self, *args), 1, *metric_options) super(*args, &block) end end end
[ "def", "statsd_count", "(", "method", ",", "name", ",", "*", "metric_options", ")", "add_to_method", "(", "method", ",", "name", ",", ":count", ")", "do", "define_method", "(", "method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "StatsD", ".", "increment", "(", "StatsD", "::", "Instrument", ".", "generate_metric_name", "(", "name", ",", "self", ",", "args", ")", ",", "1", ",", "metric_options", ")", "super", "(", "args", ",", "block", ")", "end", "end", "end" ]
Adds counter instrumentation to a method. The metric will be incremented for every call of the instrumented method, no matter whether what the method returns, or whether it raises an exception. @param method (see #statsd_measure) @param name (see #statsd_measure) @param metric_options (see #statsd_measure) @return [void]
[ "Adds", "counter", "instrumentation", "to", "a", "method", "." ]
f1a96b4f86811ea1505a34e10a738dc22b19effa
https://github.com/Shopify/statsd-instrument/blob/f1a96b4f86811ea1505a34e10a738dc22b19effa/lib/statsd/instrument.rb#L176-L183
train
chef/mixlib-shellout
lib/mixlib/shellout.rb
Mixlib.ShellOut.format_for_exception
def format_for_exception return "Command execution failed. STDOUT/STDERR suppressed for sensitive resource" if sensitive msg = "" msg << "#{@terminate_reason}\n" if @terminate_reason msg << "---- Begin output of #{command} ----\n" msg << "STDOUT: #{stdout.strip}\n" msg << "STDERR: #{stderr.strip}\n" msg << "---- End output of #{command} ----\n" msg << "Ran #{command} returned #{status.exitstatus}" if status msg end
ruby
def format_for_exception return "Command execution failed. STDOUT/STDERR suppressed for sensitive resource" if sensitive msg = "" msg << "#{@terminate_reason}\n" if @terminate_reason msg << "---- Begin output of #{command} ----\n" msg << "STDOUT: #{stdout.strip}\n" msg << "STDERR: #{stderr.strip}\n" msg << "---- End output of #{command} ----\n" msg << "Ran #{command} returned #{status.exitstatus}" if status msg end
[ "def", "format_for_exception", "return", "\"Command execution failed. STDOUT/STDERR suppressed for sensitive resource\"", "if", "sensitive", "msg", "=", "\"\"", "msg", "<<", "\"#{@terminate_reason}\\n\"", "if", "@terminate_reason", "msg", "<<", "\"---- Begin output of #{command} ----\\n\"", "msg", "<<", "\"STDOUT: #{stdout.strip}\\n\"", "msg", "<<", "\"STDERR: #{stderr.strip}\\n\"", "msg", "<<", "\"---- End output of #{command} ----\\n\"", "msg", "<<", "\"Ran #{command} returned #{status.exitstatus}\"", "if", "status", "msg", "end" ]
Creates a String showing the output of the command, including a banner showing the exact command executed. Used by +invalid!+ to show command results when the command exited with an unexpected status.
[ "Creates", "a", "String", "showing", "the", "output", "of", "the", "command", "including", "a", "banner", "showing", "the", "exact", "command", "executed", ".", "Used", "by", "+", "invalid!", "+", "to", "show", "command", "results", "when", "the", "command", "exited", "with", "an", "unexpected", "status", "." ]
35f1d3636974838cd623c65f18b861fa2d16b777
https://github.com/chef/mixlib-shellout/blob/35f1d3636974838cd623c65f18b861fa2d16b777/lib/mixlib/shellout.rb#L232-L242
train
kneath/kss
lib/kss/comment_parser.rb
Kss.CommentParser.normalize
def normalize(text_block) return text_block if @options[:preserve_whitespace] # Strip out any preceding [whitespace]* that occur on every line. Not # the smartest, but I wonder if I care. text_block = text_block.gsub(/^(\s*\*+)/, '') # Strip consistent indenting by measuring first line's whitespace indent_size = nil unindented = text_block.split("\n").collect do |line| preceding_whitespace = line.scan(/^\s*/)[0].to_s.size indent_size = preceding_whitespace if indent_size.nil? if line == "" "" elsif indent_size <= preceding_whitespace && indent_size > 0 line.slice(indent_size, line.length - 1) else line end end.join("\n") unindented.strip end
ruby
def normalize(text_block) return text_block if @options[:preserve_whitespace] # Strip out any preceding [whitespace]* that occur on every line. Not # the smartest, but I wonder if I care. text_block = text_block.gsub(/^(\s*\*+)/, '') # Strip consistent indenting by measuring first line's whitespace indent_size = nil unindented = text_block.split("\n").collect do |line| preceding_whitespace = line.scan(/^\s*/)[0].to_s.size indent_size = preceding_whitespace if indent_size.nil? if line == "" "" elsif indent_size <= preceding_whitespace && indent_size > 0 line.slice(indent_size, line.length - 1) else line end end.join("\n") unindented.strip end
[ "def", "normalize", "(", "text_block", ")", "return", "text_block", "if", "@options", "[", ":preserve_whitespace", "]", "# Strip out any preceding [whitespace]* that occur on every line. Not", "# the smartest, but I wonder if I care.", "text_block", "=", "text_block", ".", "gsub", "(", "/", "\\s", "\\*", "/", ",", "''", ")", "# Strip consistent indenting by measuring first line's whitespace", "indent_size", "=", "nil", "unindented", "=", "text_block", ".", "split", "(", "\"\\n\"", ")", ".", "collect", "do", "|", "line", "|", "preceding_whitespace", "=", "line", ".", "scan", "(", "/", "\\s", "/", ")", "[", "0", "]", ".", "to_s", ".", "size", "indent_size", "=", "preceding_whitespace", "if", "indent_size", ".", "nil?", "if", "line", "==", "\"\"", "\"\"", "elsif", "indent_size", "<=", "preceding_whitespace", "&&", "indent_size", ">", "0", "line", ".", "slice", "(", "indent_size", ",", "line", ".", "length", "-", "1", ")", "else", "line", "end", "end", ".", "join", "(", "\"\\n\"", ")", "unindented", ".", "strip", "end" ]
Normalizes the comment block to ignore any consistent preceding whitespace. Consistent means the same amount of whitespace on every line of the comment block. Also strips any whitespace at the start and end of the whole block. Returns a String of normalized text.
[ "Normalizes", "the", "comment", "block", "to", "ignore", "any", "consistent", "preceding", "whitespace", ".", "Consistent", "means", "the", "same", "amount", "of", "whitespace", "on", "every", "line", "of", "the", "comment", "block", ".", "Also", "strips", "any", "whitespace", "at", "the", "start", "and", "end", "of", "the", "whole", "block", "." ]
b0791708cb397f5e8995a855af0d1a8b0aa89a2e
https://github.com/kneath/kss/blob/b0791708cb397f5e8995a855af0d1a8b0aa89a2e/lib/kss/comment_parser.rb#L151-L173
train
GoogleCloudPlatform/fluent-plugin-detect-exceptions
lib/fluent/plugin/exception_detector.rb
Fluent.ExceptionDetector.transition
def transition(line) @rules[@state].each do |r| next unless line =~ r.pattern @state = r.to_state return true end @state = :start_state false end
ruby
def transition(line) @rules[@state].each do |r| next unless line =~ r.pattern @state = r.to_state return true end @state = :start_state false end
[ "def", "transition", "(", "line", ")", "@rules", "[", "@state", "]", ".", "each", "do", "|", "r", "|", "next", "unless", "line", "=~", "r", ".", "pattern", "@state", "=", "r", ".", "to_state", "return", "true", "end", "@state", "=", ":start_state", "false", "end" ]
Executes a transition of the state machine for the given line. Returns false if the line does not match any transition rule and the state machine was reset to the initial state.
[ "Executes", "a", "transition", "of", "the", "state", "machine", "for", "the", "given", "line", ".", "Returns", "false", "if", "the", "line", "does", "not", "match", "any", "transition", "rule", "and", "the", "state", "machine", "was", "reset", "to", "the", "initial", "state", "." ]
69d95d2d46820095da7aa5d351257df625dd4d10
https://github.com/GoogleCloudPlatform/fluent-plugin-detect-exceptions/blob/69d95d2d46820095da7aa5d351257df625dd4d10/lib/fluent/plugin/exception_detector.rb#L222-L230
train
treasure-data/serverengine
lib/serverengine/daemon_logger.rb
ServerEngine.DaemonLogger.add
def add(severity, message = nil, progname = nil, &block) if severity < @level return true end if message.nil? if block_given? message = yield else message = progname progname = nil end end progname ||= @progname self << format_message(SEVERITY_FORMATS_[severity+1], Time.now, progname, message) true end
ruby
def add(severity, message = nil, progname = nil, &block) if severity < @level return true end if message.nil? if block_given? message = yield else message = progname progname = nil end end progname ||= @progname self << format_message(SEVERITY_FORMATS_[severity+1], Time.now, progname, message) true end
[ "def", "add", "(", "severity", ",", "message", "=", "nil", ",", "progname", "=", "nil", ",", "&", "block", ")", "if", "severity", "<", "@level", "return", "true", "end", "if", "message", ".", "nil?", "if", "block_given?", "message", "=", "yield", "else", "message", "=", "progname", "progname", "=", "nil", "end", "end", "progname", "||=", "@progname", "self", "<<", "format_message", "(", "SEVERITY_FORMATS_", "[", "severity", "+", "1", "]", ",", "Time", ".", "now", ",", "progname", ",", "message", ")", "true", "end" ]
override add method
[ "override", "add", "method" ]
400b4b818fda4f98d4c71b1fb06ffdc74bb4bf4a
https://github.com/treasure-data/serverengine/blob/400b4b818fda4f98d4c71b1fb06ffdc74bb4bf4a/lib/serverengine/daemon_logger.rb#L65-L80
train
thesp0nge/dawnscanner
lib/dawn/knowledge_base_experimental.rb
Dawn.KnowledgeBaseExperimental.__packed?
def __packed? FILES.each do |fn| return true if fn.end_with? 'tar.gz' and File.exists?(File.join($path, fn)) end return false end
ruby
def __packed? FILES.each do |fn| return true if fn.end_with? 'tar.gz' and File.exists?(File.join($path, fn)) end return false end
[ "def", "__packed?", "FILES", ".", "each", "do", "|", "fn", "|", "return", "true", "if", "fn", ".", "end_with?", "'tar.gz'", "and", "File", ".", "exists?", "(", "File", ".", "join", "(", "$path", ",", "fn", ")", ")", "end", "return", "false", "end" ]
Check if the local KB is packet or not. Returns true if at least one KB tarball file it has been found in the local DB path
[ "Check", "if", "the", "local", "KB", "is", "packet", "or", "not", "." ]
ac3eba58fa9adf563ecf01807d29066cb72cdeec
https://github.com/thesp0nge/dawnscanner/blob/ac3eba58fa9adf563ecf01807d29066cb72cdeec/lib/dawn/knowledge_base_experimental.rb#L222-L227
train
thesp0nge/dawnscanner
lib/dawn/engine.rb
Dawn.Engine.output_dir
def output_dir @output_dir_name = File.join(Dir.home, 'dawnscanner', 'results', File.basename(@target), Time.now.strftime('%Y%m%d')) if Dir.exist?(@output_dir_name) i=1 while (Dir.exist?(@output_dir_name)) do @output_dir_name = File.join(Dir.home, 'dawnscanner', 'results', File.basename(@target), "#{Time.now.strftime('%Y%m%d')}_#{i}") i+=1 end end @output_dir_name end
ruby
def output_dir @output_dir_name = File.join(Dir.home, 'dawnscanner', 'results', File.basename(@target), Time.now.strftime('%Y%m%d')) if Dir.exist?(@output_dir_name) i=1 while (Dir.exist?(@output_dir_name)) do @output_dir_name = File.join(Dir.home, 'dawnscanner', 'results', File.basename(@target), "#{Time.now.strftime('%Y%m%d')}_#{i}") i+=1 end end @output_dir_name end
[ "def", "output_dir", "@output_dir_name", "=", "File", ".", "join", "(", "Dir", ".", "home", ",", "'dawnscanner'", ",", "'results'", ",", "File", ".", "basename", "(", "@target", ")", ",", "Time", ".", "now", ".", "strftime", "(", "'%Y%m%d'", ")", ")", "if", "Dir", ".", "exist?", "(", "@output_dir_name", ")", "i", "=", "1", "while", "(", "Dir", ".", "exist?", "(", "@output_dir_name", ")", ")", "do", "@output_dir_name", "=", "File", ".", "join", "(", "Dir", ".", "home", ",", "'dawnscanner'", ",", "'results'", ",", "File", ".", "basename", "(", "@target", ")", ",", "\"#{Time.now.strftime('%Y%m%d')}_#{i}\"", ")", "i", "+=", "1", "end", "end", "@output_dir_name", "end" ]
Output stuff - START Creates the directory name where dawnscanner results will be saved Examples engine.create_output_dir # => /Users/thesp0nge/dawnscanner/results/railsgoat/20151123 # => /Users/thesp0nge/dawnscanner/results/railsgoat/20151123_1 (if previous directory name exists)
[ "Output", "stuff", "-", "START" ]
ac3eba58fa9adf563ecf01807d29066cb72cdeec
https://github.com/thesp0nge/dawnscanner/blob/ac3eba58fa9adf563ecf01807d29066cb72cdeec/lib/dawn/engine.rb#L231-L241
train
thesp0nge/dawnscanner
lib/dawn/engine.rb
Dawn.Engine.apply
def apply(name) # FIXME.20140325 # Now if no checks are loaded because knowledge base was not previously called, apply and apply_all proudly refuse to run. # Reason is simple, load_knowledge_base now needs enabled check array # and I don't want to pollute engine API to propagate this value. It's # a param to load_knowledge_base and then bin/dawn calls it # accordingly. # load_knowledge_base if @checks.nil? if @checks.nil? $logger.err "you must load knowledge base before trying to apply security checks" return false end return false if @checks.empty? @checks.each do |check| _do_apply(check) if check.name == name end false end
ruby
def apply(name) # FIXME.20140325 # Now if no checks are loaded because knowledge base was not previously called, apply and apply_all proudly refuse to run. # Reason is simple, load_knowledge_base now needs enabled check array # and I don't want to pollute engine API to propagate this value. It's # a param to load_knowledge_base and then bin/dawn calls it # accordingly. # load_knowledge_base if @checks.nil? if @checks.nil? $logger.err "you must load knowledge base before trying to apply security checks" return false end return false if @checks.empty? @checks.each do |check| _do_apply(check) if check.name == name end false end
[ "def", "apply", "(", "name", ")", "# FIXME.20140325", "# Now if no checks are loaded because knowledge base was not previously called, apply and apply_all proudly refuse to run.", "# Reason is simple, load_knowledge_base now needs enabled check array", "# and I don't want to pollute engine API to propagate this value. It's", "# a param to load_knowledge_base and then bin/dawn calls it", "# accordingly.", "# load_knowledge_base if @checks.nil?", "if", "@checks", ".", "nil?", "$logger", ".", "err", "\"you must load knowledge base before trying to apply security checks\"", "return", "false", "end", "return", "false", "if", "@checks", ".", "empty?", "@checks", ".", "each", "do", "|", "check", "|", "_do_apply", "(", "check", ")", "if", "check", ".", "name", "==", "name", "end", "false", "end" ]
Output stuff - END Security stuff applies here Public it applies a single security check given by its name name - the security check to be applied Examples engine.apply("CVE-2013-1800") # => boolean Returns a true value if the security check was successfully applied or false otherwise
[ "Output", "stuff", "-", "END" ]
ac3eba58fa9adf563ecf01807d29066cb72cdeec
https://github.com/thesp0nge/dawnscanner/blob/ac3eba58fa9adf563ecf01807d29066cb72cdeec/lib/dawn/engine.rb#L268-L289
train
neo4jrb/neo4j
lib/neo4j/active_rel/initialize.rb
Neo4j::ActiveRel.Initialize.init_on_load
def init_on_load(persisted_rel, from_node_id, to_node_id, type) @rel_type = type @_persisted_obj = persisted_rel changed_attributes_clear! @attributes = convert_and_assign_attributes(persisted_rel.props) load_nodes(from_node_id, to_node_id) end
ruby
def init_on_load(persisted_rel, from_node_id, to_node_id, type) @rel_type = type @_persisted_obj = persisted_rel changed_attributes_clear! @attributes = convert_and_assign_attributes(persisted_rel.props) load_nodes(from_node_id, to_node_id) end
[ "def", "init_on_load", "(", "persisted_rel", ",", "from_node_id", ",", "to_node_id", ",", "type", ")", "@rel_type", "=", "type", "@_persisted_obj", "=", "persisted_rel", "changed_attributes_clear!", "@attributes", "=", "convert_and_assign_attributes", "(", "persisted_rel", ".", "props", ")", "load_nodes", "(", "from_node_id", ",", "to_node_id", ")", "end" ]
called when loading the rel from the database @param [Neo4j::Embedded::EmbeddedRelationship, Neo4j::Server::CypherRelationship] persisted_rel properties of this relationship @param [Neo4j::Relationship] from_node_id The neo_id of the starting node of this rel @param [Neo4j::Relationship] to_node_id The neo_id of the ending node of this rel @param [String] type the relationship type
[ "called", "when", "loading", "the", "rel", "from", "the", "database" ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/active_rel/initialize.rb#L11-L17
train
neo4jrb/neo4j
lib/neo4j/shared/property.rb
Neo4j::Shared.Property.process_attributes
def process_attributes(attributes = nil) return attributes if attributes.blank? multi_parameter_attributes = {} new_attributes = {} attributes.each_pair do |key, value| if key.match(DATE_KEY_REGEX) match = key.to_s.match(DATE_KEY_REGEX) found_key = match[1] index = match[2].to_i (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else new_attributes[key] = value end end multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes) end
ruby
def process_attributes(attributes = nil) return attributes if attributes.blank? multi_parameter_attributes = {} new_attributes = {} attributes.each_pair do |key, value| if key.match(DATE_KEY_REGEX) match = key.to_s.match(DATE_KEY_REGEX) found_key = match[1] index = match[2].to_i (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else new_attributes[key] = value end end multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes) end
[ "def", "process_attributes", "(", "attributes", "=", "nil", ")", "return", "attributes", "if", "attributes", ".", "blank?", "multi_parameter_attributes", "=", "{", "}", "new_attributes", "=", "{", "}", "attributes", ".", "each_pair", "do", "|", "key", ",", "value", "|", "if", "key", ".", "match", "(", "DATE_KEY_REGEX", ")", "match", "=", "key", ".", "to_s", ".", "match", "(", "DATE_KEY_REGEX", ")", "found_key", "=", "match", "[", "1", "]", "index", "=", "match", "[", "2", "]", ".", "to_i", "(", "multi_parameter_attributes", "[", "found_key", "]", "||=", "{", "}", ")", "[", "index", "]", "=", "value", ".", "empty?", "?", "nil", ":", "value", ".", "send", "(", "\"to_#{$3}\"", ")", "else", "new_attributes", "[", "key", "]", "=", "value", "end", "end", "multi_parameter_attributes", ".", "empty?", "?", "new_attributes", ":", "process_multiparameter_attributes", "(", "multi_parameter_attributes", ",", "new_attributes", ")", "end" ]
Gives support for Rails date_select, datetime_select, time_select helpers.
[ "Gives", "support", "for", "Rails", "date_select", "datetime_select", "time_select", "helpers", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/property.rb#L82-L98
train
neo4jrb/neo4j
lib/neo4j/shared/declared_properties.rb
Neo4j::Shared.DeclaredProperties.attributes_nil_hash
def attributes_nil_hash @_attributes_nil_hash ||= {}.tap do |attr_hash| registered_properties.each_pair do |k, prop_obj| val = prop_obj.default_value attr_hash[k.to_s] = val end end.freeze end
ruby
def attributes_nil_hash @_attributes_nil_hash ||= {}.tap do |attr_hash| registered_properties.each_pair do |k, prop_obj| val = prop_obj.default_value attr_hash[k.to_s] = val end end.freeze end
[ "def", "attributes_nil_hash", "@_attributes_nil_hash", "||=", "{", "}", ".", "tap", "do", "|", "attr_hash", "|", "registered_properties", ".", "each_pair", "do", "|", "k", ",", "prop_obj", "|", "val", "=", "prop_obj", ".", "default_value", "attr_hash", "[", "k", ".", "to_s", "]", "=", "val", "end", "end", ".", "freeze", "end" ]
During object wrap, a hash is needed that contains each declared property with a nil value. The active_attr dependency is capable of providing this but it is expensive and calculated on the fly each time it is called. Rather than rely on that, we build this progressively as properties are registered. When the node or rel is loaded, this is used as a template.
[ "During", "object", "wrap", "a", "hash", "is", "needed", "that", "contains", "each", "declared", "property", "with", "a", "nil", "value", ".", "The", "active_attr", "dependency", "is", "capable", "of", "providing", "this", "but", "it", "is", "expensive", "and", "calculated", "on", "the", "fly", "each", "time", "it", "is", "called", ".", "Rather", "than", "rely", "on", "that", "we", "build", "this", "progressively", "as", "properties", "are", "registered", ".", "When", "the", "node", "or", "rel", "is", "loaded", "this", "is", "used", "as", "a", "template", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/declared_properties.rb#L69-L76
train
neo4jrb/neo4j
lib/neo4j/shared/declared_properties.rb
Neo4j::Shared.DeclaredProperties.attributes_string_map
def attributes_string_map @_attributes_string_map ||= {}.tap do |attr_hash| attributes_nil_hash.each_key { |k| attr_hash[k.to_sym] = k } end.freeze end
ruby
def attributes_string_map @_attributes_string_map ||= {}.tap do |attr_hash| attributes_nil_hash.each_key { |k| attr_hash[k.to_sym] = k } end.freeze end
[ "def", "attributes_string_map", "@_attributes_string_map", "||=", "{", "}", ".", "tap", "do", "|", "attr_hash", "|", "attributes_nil_hash", ".", "each_key", "{", "|", "k", "|", "attr_hash", "[", "k", ".", "to_sym", "]", "=", "k", "}", "end", ".", "freeze", "end" ]
During object wrapping, a props hash is built with string keys but Neo4j-core provides symbols. Rather than a `to_s` or `symbolize_keys` during every load, we build a map of symbol-to-string to speed up the process. This increases memory used by the gem but reduces object allocation and GC, so it is faster in practice.
[ "During", "object", "wrapping", "a", "props", "hash", "is", "built", "with", "string", "keys", "but", "Neo4j", "-", "core", "provides", "symbols", ".", "Rather", "than", "a", "to_s", "or", "symbolize_keys", "during", "every", "load", "we", "build", "a", "map", "of", "symbol", "-", "to", "-", "string", "to", "speed", "up", "the", "process", ".", "This", "increases", "memory", "used", "by", "the", "gem", "but", "reduces", "object", "allocation", "and", "GC", "so", "it", "is", "faster", "in", "practice", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/declared_properties.rb#L82-L86
train
neo4jrb/neo4j
lib/neo4j/active_rel/persistence/query_factory.rb
Neo4j::ActiveRel::Persistence.QueryFactory.node_before_callbacks!
def node_before_callbacks! validate_unpersisted_nodes! from_node.conditional_callback(:create, from_node.persisted?) do to_node.conditional_callback(:create, to_node.persisted?) do yield end end end
ruby
def node_before_callbacks! validate_unpersisted_nodes! from_node.conditional_callback(:create, from_node.persisted?) do to_node.conditional_callback(:create, to_node.persisted?) do yield end end end
[ "def", "node_before_callbacks!", "validate_unpersisted_nodes!", "from_node", ".", "conditional_callback", "(", ":create", ",", "from_node", ".", "persisted?", ")", "do", "to_node", ".", "conditional_callback", "(", ":create", ",", "to_node", ".", "persisted?", ")", "do", "yield", "end", "end", "end" ]
Node callbacks only need to be executed if the node is not persisted. We let the `conditional_callback` method do the work, we only have to give it the type of callback we expect to be run and the condition which, if true, will prevent it from executing.
[ "Node", "callbacks", "only", "need", "to", "be", "executed", "if", "the", "node", "is", "not", "persisted", ".", "We", "let", "the", "conditional_callback", "method", "do", "the", "work", "we", "only", "have", "to", "give", "it", "the", "type", "of", "callback", "we", "expect", "to", "be", "run", "and", "the", "condition", "which", "if", "true", "will", "prevent", "it", "from", "executing", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/active_rel/persistence/query_factory.rb#L37-L44
train
neo4jrb/neo4j
lib/neo4j/shared/persistence.rb
Neo4j::Shared.Persistence.update
def update(attributes) self.class.run_transaction do |tx| self.attributes = process_attributes(attributes) saved = save tx.mark_failed unless saved saved end end
ruby
def update(attributes) self.class.run_transaction do |tx| self.attributes = process_attributes(attributes) saved = save tx.mark_failed unless saved saved end end
[ "def", "update", "(", "attributes", ")", "self", ".", "class", ".", "run_transaction", "do", "|", "tx", "|", "self", ".", "attributes", "=", "process_attributes", "(", "attributes", ")", "saved", "=", "save", "tx", ".", "mark_failed", "unless", "saved", "saved", "end", "end" ]
Updates this resource with all the attributes from the passed-in Hash and requests that the record be saved. If saving fails because the resource is invalid then false will be returned.
[ "Updates", "this", "resource", "with", "all", "the", "attributes", "from", "the", "passed", "-", "in", "Hash", "and", "requests", "that", "the", "record", "be", "saved", ".", "If", "saving", "fails", "because", "the", "resource", "is", "invalid", "then", "false", "will", "be", "returned", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/persistence.rb#L182-L189
train
neo4jrb/neo4j
lib/neo4j/active_rel/related_node.rb
Neo4j::ActiveRel.RelatedNode.loaded
def loaded fail UnsetRelatedNodeError, 'Node not set, cannot load' if @node.nil? @node = if @node.respond_to?(:neo_id) @node else Neo4j::ActiveBase.new_query.match(:n).where(n: {neo_id: @node}).pluck(:n).first end end
ruby
def loaded fail UnsetRelatedNodeError, 'Node not set, cannot load' if @node.nil? @node = if @node.respond_to?(:neo_id) @node else Neo4j::ActiveBase.new_query.match(:n).where(n: {neo_id: @node}).pluck(:n).first end end
[ "def", "loaded", "fail", "UnsetRelatedNodeError", ",", "'Node not set, cannot load'", "if", "@node", ".", "nil?", "@node", "=", "if", "@node", ".", "respond_to?", "(", ":neo_id", ")", "@node", "else", "Neo4j", "::", "ActiveBase", ".", "new_query", ".", "match", "(", ":n", ")", ".", "where", "(", "n", ":", "{", "neo_id", ":", "@node", "}", ")", ".", "pluck", "(", ":n", ")", ".", "first", "end", "end" ]
Loads a node from the database or returns the node if already laoded
[ "Loads", "a", "node", "from", "the", "database", "or", "returns", "the", "node", "if", "already", "laoded" ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/active_rel/related_node.rb#L30-L37
train
neo4jrb/neo4j
lib/neo4j/shared/type_converters.rb
Neo4j::Shared.TypeConverters.convert_properties_to
def convert_properties_to(obj, medium, properties) direction = medium == :ruby ? :to_ruby : :to_db properties.each_pair do |key, value| next if skip_conversion?(obj, key, value) properties[key] = convert_property(key, value, direction) end end
ruby
def convert_properties_to(obj, medium, properties) direction = medium == :ruby ? :to_ruby : :to_db properties.each_pair do |key, value| next if skip_conversion?(obj, key, value) properties[key] = convert_property(key, value, direction) end end
[ "def", "convert_properties_to", "(", "obj", ",", "medium", ",", "properties", ")", "direction", "=", "medium", "==", ":ruby", "?", ":to_ruby", ":", ":to_db", "properties", ".", "each_pair", "do", "|", "key", ",", "value", "|", "next", "if", "skip_conversion?", "(", "obj", ",", "key", ",", "value", ")", "properties", "[", "key", "]", "=", "convert_property", "(", "key", ",", "value", ",", "direction", ")", "end", "end" ]
Modifies a hash's values to be of types acceptable to Neo4j or matching what the user defined using `type` in property definitions. @param [Neo4j::Shared::Property] obj A node or rel that mixes in the Property module @param [Symbol] medium Indicates the type of conversion to perform. @param [Hash] properties A hash of symbol-keyed properties for conversion.
[ "Modifies", "a", "hash", "s", "values", "to", "be", "of", "types", "acceptable", "to", "Neo4j", "or", "matching", "what", "the", "user", "defined", "using", "type", "in", "property", "definitions", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/type_converters.rb#L335-L341
train
neo4jrb/neo4j
lib/neo4j/shared/type_converters.rb
Neo4j::Shared.TypeConverters.convert_property
def convert_property(key, value, direction) converted_property(primitive_type(key.to_sym), value, direction) end
ruby
def convert_property(key, value, direction) converted_property(primitive_type(key.to_sym), value, direction) end
[ "def", "convert_property", "(", "key", ",", "value", ",", "direction", ")", "converted_property", "(", "primitive_type", "(", "key", ".", "to_sym", ")", ",", "value", ",", "direction", ")", "end" ]
Converts a single property from its current format to its db- or Ruby-expected output type. @param [Symbol] key A property declared on the model @param value The value intended for conversion @param [Symbol] direction Either :to_ruby or :to_db, indicates the type of conversion to perform
[ "Converts", "a", "single", "property", "from", "its", "current", "format", "to", "its", "db", "-", "or", "Ruby", "-", "expected", "output", "type", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/type_converters.rb#L347-L349
train
neo4jrb/neo4j
lib/neo4j/shared/type_converters.rb
Neo4j::Shared.TypeConverters.primitive_type
def primitive_type(attr) case when serialized_properties.include?(attr) serialized_properties[attr] when magic_typecast_properties.include?(attr) magic_typecast_properties[attr] else fetch_upstream_primitive(attr) end end
ruby
def primitive_type(attr) case when serialized_properties.include?(attr) serialized_properties[attr] when magic_typecast_properties.include?(attr) magic_typecast_properties[attr] else fetch_upstream_primitive(attr) end end
[ "def", "primitive_type", "(", "attr", ")", "case", "when", "serialized_properties", ".", "include?", "(", "attr", ")", "serialized_properties", "[", "attr", "]", "when", "magic_typecast_properties", ".", "include?", "(", "attr", ")", "magic_typecast_properties", "[", "attr", "]", "else", "fetch_upstream_primitive", "(", "attr", ")", "end", "end" ]
If the attribute is to be typecast using a custom converter, which converter should it use? If no, returns the type to find a native serializer.
[ "If", "the", "attribute", "is", "to", "be", "typecast", "using", "a", "custom", "converter", "which", "converter", "should", "it", "use?", "If", "no", "returns", "the", "type", "to", "find", "a", "native", "serializer", "." ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/type_converters.rb#L372-L381
train
neo4jrb/neo4j
lib/neo4j/shared/type_converters.rb
Neo4j::Shared.TypeConverters.skip_conversion?
def skip_conversion?(obj, attr, value) value.nil? || !obj.class.attributes.key?(attr) end
ruby
def skip_conversion?(obj, attr, value) value.nil? || !obj.class.attributes.key?(attr) end
[ "def", "skip_conversion?", "(", "obj", ",", "attr", ",", "value", ")", "value", ".", "nil?", "||", "!", "obj", ".", "class", ".", "attributes", ".", "key?", "(", "attr", ")", "end" ]
Returns true if the property isn't defined in the model or if it is nil
[ "Returns", "true", "if", "the", "property", "isn", "t", "defined", "in", "the", "model", "or", "if", "it", "is", "nil" ]
291c79a757e8bd5e84920a7bd44867a5f304aa8b
https://github.com/neo4jrb/neo4j/blob/291c79a757e8bd5e84920a7bd44867a5f304aa8b/lib/neo4j/shared/type_converters.rb#L384-L386
train
chefspec/chefspec
lib/chefspec/matchers/render_file_matcher.rb
ChefSpec::Matchers.RenderFileMatcher.matches_content?
def matches_content? return true if @expected_content.empty? @actual_content = ChefSpec::Renderer.new(@runner, resource).content return false if @actual_content.nil? # Knock out matches that pass. When we're done, we pass if the list is # empty. Otherwise, @expected_content is the list of matchers that # failed @expected_content.delete_if do |expected| if expected.is_a?(Regexp) @actual_content =~ expected elsif RSpec::Matchers.is_a_matcher?(expected) expected.matches?(@actual_content) elsif expected.is_a?(Proc) expected.call(@actual_content) # Weird RSpecish, but that block will return false for a negated check, # so we always return true. The block will raise an exception if the # assertion fails. true else @actual_content.include?(expected) end end @expected_content.empty? end
ruby
def matches_content? return true if @expected_content.empty? @actual_content = ChefSpec::Renderer.new(@runner, resource).content return false if @actual_content.nil? # Knock out matches that pass. When we're done, we pass if the list is # empty. Otherwise, @expected_content is the list of matchers that # failed @expected_content.delete_if do |expected| if expected.is_a?(Regexp) @actual_content =~ expected elsif RSpec::Matchers.is_a_matcher?(expected) expected.matches?(@actual_content) elsif expected.is_a?(Proc) expected.call(@actual_content) # Weird RSpecish, but that block will return false for a negated check, # so we always return true. The block will raise an exception if the # assertion fails. true else @actual_content.include?(expected) end end @expected_content.empty? end
[ "def", "matches_content?", "return", "true", "if", "@expected_content", ".", "empty?", "@actual_content", "=", "ChefSpec", "::", "Renderer", ".", "new", "(", "@runner", ",", "resource", ")", ".", "content", "return", "false", "if", "@actual_content", ".", "nil?", "# Knock out matches that pass. When we're done, we pass if the list is", "# empty. Otherwise, @expected_content is the list of matchers that", "# failed", "@expected_content", ".", "delete_if", "do", "|", "expected", "|", "if", "expected", ".", "is_a?", "(", "Regexp", ")", "@actual_content", "=~", "expected", "elsif", "RSpec", "::", "Matchers", ".", "is_a_matcher?", "(", "expected", ")", "expected", ".", "matches?", "(", "@actual_content", ")", "elsif", "expected", ".", "is_a?", "(", "Proc", ")", "expected", ".", "call", "(", "@actual_content", ")", "# Weird RSpecish, but that block will return false for a negated check,", "# so we always return true. The block will raise an exception if the", "# assertion fails.", "true", "else", "@actual_content", ".", "include?", "(", "expected", ")", "end", "end", "@expected_content", ".", "empty?", "end" ]
Determines if the resources content matches the expected content. @param [Chef::Resource] resource @return [true, false]
[ "Determines", "if", "the", "resources", "content", "matches", "the", "expected", "content", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/matchers/render_file_matcher.rb#L112-L138
train
chefspec/chefspec
lib/chefspec/server_methods.rb
ChefSpec.ServerMethods.load_data
def load_data(name, key, data = {}) ChefSpec::ZeroServer.load_data(name, key, data) end
ruby
def load_data(name, key, data = {}) ChefSpec::ZeroServer.load_data(name, key, data) end
[ "def", "load_data", "(", "name", ",", "key", ",", "data", "=", "{", "}", ")", "ChefSpec", "::", "ZeroServer", ".", "load_data", "(", "name", ",", "key", ",", "data", ")", "end" ]
Shortcut method for loading data into Chef Zero. @param [String] name the name or id of the item to load @param [String, Symbol] key the key to load @param [Hash] data the data for the object, which will be converted to JSON and uploaded to the server
[ "Shortcut", "method", "for", "loading", "data", "into", "Chef", "Zero", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/server_methods.rb#L156-L158
train
chefspec/chefspec
lib/chefspec/zero_server.rb
ChefSpec.ZeroServer.reset!
def reset! if RSpec.configuration.server_runner_clear_cookbooks @server.clear_data @cookbooks_uploaded = false else # If we don't want to do a full clear, iterate through each value that we # set and manually remove it. @data_loaded.each do |key, names| if key == "data" names.each { |n| @server.data_store.delete_dir(["organizations", "chef", key, n]) } else names.each { |n| @server.data_store.delete(["organizations", "chef", key, n]) } end end end @data_loaded = {} end
ruby
def reset! if RSpec.configuration.server_runner_clear_cookbooks @server.clear_data @cookbooks_uploaded = false else # If we don't want to do a full clear, iterate through each value that we # set and manually remove it. @data_loaded.each do |key, names| if key == "data" names.each { |n| @server.data_store.delete_dir(["organizations", "chef", key, n]) } else names.each { |n| @server.data_store.delete(["organizations", "chef", key, n]) } end end end @data_loaded = {} end
[ "def", "reset!", "if", "RSpec", ".", "configuration", ".", "server_runner_clear_cookbooks", "@server", ".", "clear_data", "@cookbooks_uploaded", "=", "false", "else", "# If we don't want to do a full clear, iterate through each value that we", "# set and manually remove it.", "@data_loaded", ".", "each", "do", "|", "key", ",", "names", "|", "if", "key", "==", "\"data\"", "names", ".", "each", "{", "|", "n", "|", "@server", ".", "data_store", ".", "delete_dir", "(", "[", "\"organizations\"", ",", "\"chef\"", ",", "key", ",", "n", "]", ")", "}", "else", "names", ".", "each", "{", "|", "n", "|", "@server", ".", "data_store", ".", "delete", "(", "[", "\"organizations\"", ",", "\"chef\"", ",", "key", ",", "n", "]", ")", "}", "end", "end", "end", "@data_loaded", "=", "{", "}", "end" ]
Remove all the data we just loaded from the ChefZero server
[ "Remove", "all", "the", "data", "we", "just", "loaded", "from", "the", "ChefZero", "server" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/zero_server.rb#L31-L47
train
chefspec/chefspec
lib/chefspec/zero_server.rb
ChefSpec.ZeroServer.nuke!
def nuke! @server = ChefZero::Server.new( # Set the log level from RSpec, defaulting to warn log_level: RSpec.configuration.log_level || :warn, port: RSpec.configuration.server_runner_port, # Set the data store data_store: data_store(RSpec.configuration.server_runner_data_store), ) @cookbooks_uploaded = false @data_loaded = {} end
ruby
def nuke! @server = ChefZero::Server.new( # Set the log level from RSpec, defaulting to warn log_level: RSpec.configuration.log_level || :warn, port: RSpec.configuration.server_runner_port, # Set the data store data_store: data_store(RSpec.configuration.server_runner_data_store), ) @cookbooks_uploaded = false @data_loaded = {} end
[ "def", "nuke!", "@server", "=", "ChefZero", "::", "Server", ".", "new", "(", "# Set the log level from RSpec, defaulting to warn", "log_level", ":", "RSpec", ".", "configuration", ".", "log_level", "||", ":warn", ",", "port", ":", "RSpec", ".", "configuration", ".", "server_runner_port", ",", "# Set the data store", "data_store", ":", "data_store", "(", "RSpec", ".", "configuration", ".", "server_runner_data_store", ")", ",", ")", "@cookbooks_uploaded", "=", "false", "@data_loaded", "=", "{", "}", "end" ]
Really reset everything and reload the configuration
[ "Really", "reset", "everything", "and", "reload", "the", "configuration" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/zero_server.rb#L52-L63
train
chefspec/chefspec
lib/chefspec/zero_server.rb
ChefSpec.ZeroServer.upload_cookbooks!
def upload_cookbooks! return if @cookbooks_uploaded loader = Chef::CookbookLoader.new(Chef::Config[:cookbook_path]) loader.load_cookbooks cookbook_uploader_for(loader).upload_cookbooks @cookbooks_uploaded = true end
ruby
def upload_cookbooks! return if @cookbooks_uploaded loader = Chef::CookbookLoader.new(Chef::Config[:cookbook_path]) loader.load_cookbooks cookbook_uploader_for(loader).upload_cookbooks @cookbooks_uploaded = true end
[ "def", "upload_cookbooks!", "return", "if", "@cookbooks_uploaded", "loader", "=", "Chef", "::", "CookbookLoader", ".", "new", "(", "Chef", "::", "Config", "[", ":cookbook_path", "]", ")", "loader", ".", "load_cookbooks", "cookbook_uploader_for", "(", "loader", ")", ".", "upload_cookbooks", "@cookbooks_uploaded", "=", "true", "end" ]
Upload the cookbooks to the Chef Server.
[ "Upload", "the", "cookbooks", "to", "the", "Chef", "Server", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/zero_server.rb#L75-L81
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.converge
def converge(*recipe_names) # Re-apply the Chef config before converging in case something else # called Config.reset too. apply_chef_config! @converging = false node.run_list.reset! recipe_names.each { |recipe_name| node.run_list.add(recipe_name) } return self if dry_run? # Expand the run_list expand_run_list! # Merge in provided node attributes. Default and override use the role_ # levels so they win over the relevant bits from cookbooks since otherwise # they would not and that would be confusing. node.attributes.role_default = Chef::Mixin::DeepMerge.merge(node.attributes.role_default, options[:default_attributes]) if options[:default_attributes] node.attributes.normal = Chef::Mixin::DeepMerge.merge(node.attributes.normal, options[:normal_attributes]) if options[:normal_attributes] node.attributes.role_override = Chef::Mixin::DeepMerge.merge(node.attributes.role_override, options[:override_attributes]) if options[:override_attributes] node.attributes.automatic = Chef::Mixin::DeepMerge.merge(node.attributes.automatic, options[:automatic_attributes]) if options[:automatic_attributes] # Setup the run_context, rescuing the exception that happens when a # resource is not defined on a particular platform begin @run_context = client.setup_run_context rescue Chef::Exceptions::NoSuchResourceType => e raise Error::MayNeedToSpecifyPlatform.new(original_error: e.message) end # Allow stubbing/mocking after the cookbook has been compiled but before the converge yield node if block_given? @converging = true converge_val = @client.converge(@run_context) if converge_val.is_a?(Exception) raise converge_val end self end
ruby
def converge(*recipe_names) # Re-apply the Chef config before converging in case something else # called Config.reset too. apply_chef_config! @converging = false node.run_list.reset! recipe_names.each { |recipe_name| node.run_list.add(recipe_name) } return self if dry_run? # Expand the run_list expand_run_list! # Merge in provided node attributes. Default and override use the role_ # levels so they win over the relevant bits from cookbooks since otherwise # they would not and that would be confusing. node.attributes.role_default = Chef::Mixin::DeepMerge.merge(node.attributes.role_default, options[:default_attributes]) if options[:default_attributes] node.attributes.normal = Chef::Mixin::DeepMerge.merge(node.attributes.normal, options[:normal_attributes]) if options[:normal_attributes] node.attributes.role_override = Chef::Mixin::DeepMerge.merge(node.attributes.role_override, options[:override_attributes]) if options[:override_attributes] node.attributes.automatic = Chef::Mixin::DeepMerge.merge(node.attributes.automatic, options[:automatic_attributes]) if options[:automatic_attributes] # Setup the run_context, rescuing the exception that happens when a # resource is not defined on a particular platform begin @run_context = client.setup_run_context rescue Chef::Exceptions::NoSuchResourceType => e raise Error::MayNeedToSpecifyPlatform.new(original_error: e.message) end # Allow stubbing/mocking after the cookbook has been compiled but before the converge yield node if block_given? @converging = true converge_val = @client.converge(@run_context) if converge_val.is_a?(Exception) raise converge_val end self end
[ "def", "converge", "(", "*", "recipe_names", ")", "# Re-apply the Chef config before converging in case something else", "# called Config.reset too.", "apply_chef_config!", "@converging", "=", "false", "node", ".", "run_list", ".", "reset!", "recipe_names", ".", "each", "{", "|", "recipe_name", "|", "node", ".", "run_list", ".", "add", "(", "recipe_name", ")", "}", "return", "self", "if", "dry_run?", "# Expand the run_list", "expand_run_list!", "# Merge in provided node attributes. Default and override use the role_", "# levels so they win over the relevant bits from cookbooks since otherwise", "# they would not and that would be confusing.", "node", ".", "attributes", ".", "role_default", "=", "Chef", "::", "Mixin", "::", "DeepMerge", ".", "merge", "(", "node", ".", "attributes", ".", "role_default", ",", "options", "[", ":default_attributes", "]", ")", "if", "options", "[", ":default_attributes", "]", "node", ".", "attributes", ".", "normal", "=", "Chef", "::", "Mixin", "::", "DeepMerge", ".", "merge", "(", "node", ".", "attributes", ".", "normal", ",", "options", "[", ":normal_attributes", "]", ")", "if", "options", "[", ":normal_attributes", "]", "node", ".", "attributes", ".", "role_override", "=", "Chef", "::", "Mixin", "::", "DeepMerge", ".", "merge", "(", "node", ".", "attributes", ".", "role_override", ",", "options", "[", ":override_attributes", "]", ")", "if", "options", "[", ":override_attributes", "]", "node", ".", "attributes", ".", "automatic", "=", "Chef", "::", "Mixin", "::", "DeepMerge", ".", "merge", "(", "node", ".", "attributes", ".", "automatic", ",", "options", "[", ":automatic_attributes", "]", ")", "if", "options", "[", ":automatic_attributes", "]", "# Setup the run_context, rescuing the exception that happens when a", "# resource is not defined on a particular platform", "begin", "@run_context", "=", "client", ".", "setup_run_context", "rescue", "Chef", "::", "Exceptions", "::", "NoSuchResourceType", "=>", "e", "raise", "Error", "::", "MayNeedToSpecifyPlatform", ".", "new", "(", "original_error", ":", "e", ".", "message", ")", "end", "# Allow stubbing/mocking after the cookbook has been compiled but before the converge", "yield", "node", "if", "block_given?", "@converging", "=", "true", "converge_val", "=", "@client", ".", "converge", "(", "@run_context", ")", "if", "converge_val", ".", "is_a?", "(", "Exception", ")", "raise", "converge_val", "end", "self", "end" ]
Instantiate a new SoloRunner to run examples with. @example Instantiate a new Runner ChefSpec::SoloRunner.new @example Specifying the platform and version ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '18.04') @example Specifying the cookbook path ChefSpec::SoloRunner.new(cookbook_path: ['/cookbooks']) @example Specifying the log level ChefSpec::SoloRunner.new(log_level: :info) @param [Hash] options The options for the new runner @option options [Symbol] :log_level The log level to use (default is :warn) @option options [String] :platform The platform to load Ohai attributes from (must be present in fauxhai) @option options [String] :version The version of the platform to load Ohai attributes from (must be present in fauxhai) @option options [String] :path Path of a json file that will be passed to fauxhai as :path option @option options [Array<String>] :step_into The list of LWRPs to evaluate @option options String] :file_cache_path File caching path, if absent ChefSpec will use a temporary directory generated on the fly @yield [node] Configuration block for Chef::Node Execute the given `run_list` on the node, without actually converging the node. Each time {#converge} is called, the `run_list` is reset to the new value (it is **not** additive). @example Converging a single recipe chef_run.converge('example::default') @example Converging multiple recipes chef_run.converge('example::default', 'example::secondary') @param [Array] recipe_names The names of the recipe or recipes to converge @return [ChefSpec::SoloRunner] A reference to the calling Runner (for chaining purposes)
[ "Instantiate", "a", "new", "SoloRunner", "to", "run", "examples", "with", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L89-L127
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.converge_block
def converge_block(&block) converge do recipe = Chef::Recipe.new(cookbook_name, '_test', run_context) recipe.instance_exec(&block) end end
ruby
def converge_block(&block) converge do recipe = Chef::Recipe.new(cookbook_name, '_test', run_context) recipe.instance_exec(&block) end end
[ "def", "converge_block", "(", "&", "block", ")", "converge", "do", "recipe", "=", "Chef", "::", "Recipe", ".", "new", "(", "cookbook_name", ",", "'_test'", ",", "run_context", ")", "recipe", ".", "instance_exec", "(", "block", ")", "end", "end" ]
Execute a block of recipe code. @param [Proc] block A block containing Chef recipe code @return [ChefSpec::SoloRunner]
[ "Execute", "a", "block", "of", "recipe", "code", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L137-L142
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.find_resource
def find_resource(type, name, action = nil) resource_collection.all_resources.reverse_each.find do |resource| resource.declared_type == type.to_sym && (name === resource.identity || name === resource.name) && (action.nil? || resource.performed_action?(action)) end end
ruby
def find_resource(type, name, action = nil) resource_collection.all_resources.reverse_each.find do |resource| resource.declared_type == type.to_sym && (name === resource.identity || name === resource.name) && (action.nil? || resource.performed_action?(action)) end end
[ "def", "find_resource", "(", "type", ",", "name", ",", "action", "=", "nil", ")", "resource_collection", ".", "all_resources", ".", "reverse_each", ".", "find", "do", "|", "resource", "|", "resource", ".", "declared_type", "==", "type", ".", "to_sym", "&&", "(", "name", "===", "resource", ".", "identity", "||", "name", "===", "resource", ".", "name", ")", "&&", "(", "action", ".", "nil?", "||", "resource", ".", "performed_action?", "(", "action", ")", ")", "end", "end" ]
Find the resource with the declared type and resource name, and optionally match a performed action. If multiples match it returns the last (which more or less matches the chef last-inserter-wins semantics) @example Find a template at `/etc/foo` chef_run.find_resource(:template, '/etc/foo') #=> #<Chef::Resource::Template> @param [Symbol] type The type of resource (sometimes called `resource_name`) such as `file` or `directory`. @param [String, Regexp] name The value of the name attribute or identity attribute for the resource. @param [Symbol] action (optional) match only resources that performed the action. @return [Chef::Resource, nil] The matching resource, or nil if one is not found
[ "Find", "the", "resource", "with", "the", "declared", "type", "and", "resource", "name", "and", "optionally", "match", "a", "performed", "action", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L207-L211
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.find_resources
def find_resources(type) resource_collection.all_resources.select do |resource| resource_name(resource) == type.to_sym end end
ruby
def find_resources(type) resource_collection.all_resources.select do |resource| resource_name(resource) == type.to_sym end end
[ "def", "find_resources", "(", "type", ")", "resource_collection", ".", "all_resources", ".", "select", "do", "|", "resource", "|", "resource_name", "(", "resource", ")", "==", "type", ".", "to_sym", "end", "end" ]
Find the resource with the declared type. @example Find all template resources chef_run.find_resources(:template) #=> [#<Chef::Resource::Template>, #...] @param [Symbol] type The type of resource such as `:file` or `:directory`. @return [Array<Chef::Resource>] The matching resources
[ "Find", "the", "resource", "with", "the", "declared", "type", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L226-L230
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.step_into?
def step_into?(resource) key = resource_name(resource) Array(options[:step_into]).map(&method(:resource_name)).include?(key) end
ruby
def step_into?(resource) key = resource_name(resource) Array(options[:step_into]).map(&method(:resource_name)).include?(key) end
[ "def", "step_into?", "(", "resource", ")", "key", "=", "resource_name", "(", "resource", ")", "Array", "(", "options", "[", ":step_into", "]", ")", ".", "map", "(", "method", "(", ":resource_name", ")", ")", ".", "include?", "(", "key", ")", "end" ]
Determines if the runner should step into the given resource. The +step_into+ option takes a string, but this method coerces everything to symbols for safety. This method also substitutes any dashes (+-+) with underscores (+_+), because that's what Chef does under the hood. (See GitHub issue #254 for more background) @param [Chef::Resource] resource the Chef resource to try and step in to @return [true, false]
[ "Determines", "if", "the", "runner", "should", "step", "into", "the", "given", "resource", ".", "The", "+", "step_into", "+", "option", "takes", "a", "string", "but", "this", "method", "coerces", "everything", "to", "symbols", "for", "safety", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L256-L259
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.method_missing
def method_missing(m, *args, &block) if block = ChefSpec.matchers[resource_name(m.to_sym)] instance_exec(args.first, &block) else super end end
ruby
def method_missing(m, *args, &block) if block = ChefSpec.matchers[resource_name(m.to_sym)] instance_exec(args.first, &block) else super end end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "block", ")", "if", "block", "=", "ChefSpec", ".", "matchers", "[", "resource_name", "(", "m", ".", "to_sym", ")", "]", "instance_exec", "(", "args", ".", "first", ",", "block", ")", "else", "super", "end", "end" ]
Respond to custom matchers defined by the user.
[ "Respond", "to", "custom", "matchers", "defined", "by", "the", "user", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L294-L300
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.with_default_options
def with_default_options(options) config = RSpec.configuration { cookbook_root: config.cookbook_root || calling_cookbook_root(options, caller), cookbook_path: config.cookbook_path || calling_cookbook_path(options, caller), role_path: config.role_path || default_role_path, environment_path: config.environment_path || default_environment_path, file_cache_path: config.file_cache_path, log_level: config.log_level, path: config.path, platform: config.platform, version: config.version, }.merge(options) end
ruby
def with_default_options(options) config = RSpec.configuration { cookbook_root: config.cookbook_root || calling_cookbook_root(options, caller), cookbook_path: config.cookbook_path || calling_cookbook_path(options, caller), role_path: config.role_path || default_role_path, environment_path: config.environment_path || default_environment_path, file_cache_path: config.file_cache_path, log_level: config.log_level, path: config.path, platform: config.platform, version: config.version, }.merge(options) end
[ "def", "with_default_options", "(", "options", ")", "config", "=", "RSpec", ".", "configuration", "{", "cookbook_root", ":", "config", ".", "cookbook_root", "||", "calling_cookbook_root", "(", "options", ",", "caller", ")", ",", "cookbook_path", ":", "config", ".", "cookbook_path", "||", "calling_cookbook_path", "(", "options", ",", "caller", ")", ",", "role_path", ":", "config", ".", "role_path", "||", "default_role_path", ",", "environment_path", ":", "config", ".", "environment_path", "||", "default_environment_path", ",", "file_cache_path", ":", "config", ".", "file_cache_path", ",", "log_level", ":", "config", ".", "log_level", ",", "path", ":", "config", ".", "path", ",", "platform", ":", "config", ".", "platform", ",", "version", ":", "config", ".", "version", ",", "}", ".", "merge", "(", "options", ")", "end" ]
Set the default options, with the given options taking precedence. @param [Hash] options the list of options to take precedence @return [Hash] options
[ "Set", "the", "default", "options", "with", "the", "given", "options", "taking", "precedence", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L334-L348
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.calling_cookbook_root
def calling_cookbook_root(options, kaller) calling_spec = options[:spec_declaration_locations] || kaller.find { |line| line =~ /\/spec/ } raise Error::CookbookPathNotFound if calling_spec.nil? bits = calling_spec.split(/:[0-9]/, 2).first.split(File::SEPARATOR) spec_dir = bits.index('spec') || 0 File.join(bits.slice(0, spec_dir)) end
ruby
def calling_cookbook_root(options, kaller) calling_spec = options[:spec_declaration_locations] || kaller.find { |line| line =~ /\/spec/ } raise Error::CookbookPathNotFound if calling_spec.nil? bits = calling_spec.split(/:[0-9]/, 2).first.split(File::SEPARATOR) spec_dir = bits.index('spec') || 0 File.join(bits.slice(0, spec_dir)) end
[ "def", "calling_cookbook_root", "(", "options", ",", "kaller", ")", "calling_spec", "=", "options", "[", ":spec_declaration_locations", "]", "||", "kaller", ".", "find", "{", "|", "line", "|", "line", "=~", "/", "\\/", "/", "}", "raise", "Error", "::", "CookbookPathNotFound", "if", "calling_spec", ".", "nil?", "bits", "=", "calling_spec", ".", "split", "(", "/", "/", ",", "2", ")", ".", "first", ".", "split", "(", "File", "::", "SEPARATOR", ")", "spec_dir", "=", "bits", ".", "index", "(", "'spec'", ")", "||", "0", "File", ".", "join", "(", "bits", ".", "slice", "(", "0", ",", "spec_dir", ")", ")", "end" ]
The inferred cookbook root from the calling spec. @param [Hash<Symbol, Object>] options initial runner options @param [Array<String>] kaller the calling trace @return [String]
[ "The", "inferred", "cookbook", "root", "from", "the", "calling", "spec", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L360-L368
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.calling_cookbook_path
def calling_cookbook_path(options, kaller) File.expand_path(File.join(calling_cookbook_root(options, kaller), '..')) end
ruby
def calling_cookbook_path(options, kaller) File.expand_path(File.join(calling_cookbook_root(options, kaller), '..')) end
[ "def", "calling_cookbook_path", "(", "options", ",", "kaller", ")", "File", ".", "expand_path", "(", "File", ".", "join", "(", "calling_cookbook_root", "(", "options", ",", "kaller", ")", ",", "'..'", ")", ")", "end" ]
The inferred path from the calling spec. @param [Hash<Symbol, Object>] options initial runner options @param [Array<String>] kaller the calling trace @return [String]
[ "The", "inferred", "path", "from", "the", "calling", "spec", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L380-L382
train
chefspec/chefspec
lib/chefspec/solo_runner.rb
ChefSpec.SoloRunner.default_role_path
def default_role_path Pathname.new(Dir.pwd).ascend do |path| possible = File.join(path, 'roles') return possible if File.exist?(possible) end nil end
ruby
def default_role_path Pathname.new(Dir.pwd).ascend do |path| possible = File.join(path, 'roles') return possible if File.exist?(possible) end nil end
[ "def", "default_role_path", "Pathname", ".", "new", "(", "Dir", ".", "pwd", ")", ".", "ascend", "do", "|", "path", "|", "possible", "=", "File", ".", "join", "(", "path", ",", "'roles'", ")", "return", "possible", "if", "File", ".", "exist?", "(", "possible", ")", "end", "nil", "end" ]
The inferred path to roles. @return [String, nil]
[ "The", "inferred", "path", "to", "roles", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/solo_runner.rb#L389-L396
train
chefspec/chefspec
lib/chefspec/coverage.rb
ChefSpec.Coverage.start!
def start!(&block) warn("ChefSpec's coverage reporting is deprecated and will be removed in a future version") instance_eval(&block) if block at_exit { ChefSpec::Coverage.report! } end
ruby
def start!(&block) warn("ChefSpec's coverage reporting is deprecated and will be removed in a future version") instance_eval(&block) if block at_exit { ChefSpec::Coverage.report! } end
[ "def", "start!", "(", "&", "block", ")", "warn", "(", "\"ChefSpec's coverage reporting is deprecated and will be removed in a future version\"", ")", "instance_eval", "(", "block", ")", "if", "block", "at_exit", "{", "ChefSpec", "::", "Coverage", ".", "report!", "}", "end" ]
Create a new coverage object singleton. Start the coverage reporting analysis. This method also adds the the +at_exit+ handler for printing the coverage report.
[ "Create", "a", "new", "coverage", "object", "singleton", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/coverage.rb#L47-L51
train
chefspec/chefspec
lib/chefspec/coverage.rb
ChefSpec.Coverage.add_filter
def add_filter(filter = nil, &block) id = "#{filter.inspect}/#{block.inspect}".hash @filters[id] = if filter.kind_of?(Filter) filter elsif filter.kind_of?(String) StringFilter.new(filter) elsif filter.kind_of?(Regexp) RegexpFilter.new(filter) elsif block BlockFilter.new(block) else raise ArgumentError, 'Please specify either a string, ' \ 'filter, or block to filter source files with!' end true end
ruby
def add_filter(filter = nil, &block) id = "#{filter.inspect}/#{block.inspect}".hash @filters[id] = if filter.kind_of?(Filter) filter elsif filter.kind_of?(String) StringFilter.new(filter) elsif filter.kind_of?(Regexp) RegexpFilter.new(filter) elsif block BlockFilter.new(block) else raise ArgumentError, 'Please specify either a string, ' \ 'filter, or block to filter source files with!' end true end
[ "def", "add_filter", "(", "filter", "=", "nil", ",", "&", "block", ")", "id", "=", "\"#{filter.inspect}/#{block.inspect}\"", ".", "hash", "@filters", "[", "id", "]", "=", "if", "filter", ".", "kind_of?", "(", "Filter", ")", "filter", "elsif", "filter", ".", "kind_of?", "(", "String", ")", "StringFilter", ".", "new", "(", "filter", ")", "elsif", "filter", ".", "kind_of?", "(", "Regexp", ")", "RegexpFilter", ".", "new", "(", "filter", ")", "elsif", "block", "BlockFilter", ".", "new", "(", "block", ")", "else", "raise", "ArgumentError", ",", "'Please specify either a string, '", "'filter, or block to filter source files with!'", "end", "true", "end" ]
Add a filter to the coverage analysis. @param [Filter, String, Regexp] filter the filter to add @param [Proc] block the block to use as a filter @return [true]
[ "Add", "a", "filter", "to", "the", "coverage", "analysis", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/coverage.rb#L63-L80
train
chefspec/chefspec
lib/chefspec/coverage.rb
ChefSpec.Coverage.set_template
def set_template(file = 'human.erb') [ ChefSpec.root.join('templates', 'coverage', file), File.expand_path(file, Dir.pwd) ].each do |temp| if File.exist?(temp) @template = temp return end end raise Error::TemplateNotFound.new(path: file) end
ruby
def set_template(file = 'human.erb') [ ChefSpec.root.join('templates', 'coverage', file), File.expand_path(file, Dir.pwd) ].each do |temp| if File.exist?(temp) @template = temp return end end raise Error::TemplateNotFound.new(path: file) end
[ "def", "set_template", "(", "file", "=", "'human.erb'", ")", "[", "ChefSpec", ".", "root", ".", "join", "(", "'templates'", ",", "'coverage'", ",", "file", ")", ",", "File", ".", "expand_path", "(", "file", ",", "Dir", ".", "pwd", ")", "]", ".", "each", "do", "|", "temp", "|", "if", "File", ".", "exist?", "(", "temp", ")", "@template", "=", "temp", "return", "end", "end", "raise", "Error", "::", "TemplateNotFound", ".", "new", "(", "path", ":", "file", ")", "end" ]
Change the template for reporting of converage analysis. @param [string] path The template file to use for the output of the report @return [true]
[ "Change", "the", "template", "for", "reporting", "of", "converage", "analysis", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/coverage.rb#L101-L112
train
chefspec/chefspec
lib/chefspec/librarian.rb
ChefSpec.Librarian.teardown!
def teardown! env = ::Librarian::Chef::Environment.new(project_path: Dir.pwd) env.config_db.local['path'] = @originalpath FileUtils.rm_rf(@tmpdir) if File.exist?(@tmpdir) end
ruby
def teardown! env = ::Librarian::Chef::Environment.new(project_path: Dir.pwd) env.config_db.local['path'] = @originalpath FileUtils.rm_rf(@tmpdir) if File.exist?(@tmpdir) end
[ "def", "teardown!", "env", "=", "::", "Librarian", "::", "Chef", "::", "Environment", ".", "new", "(", "project_path", ":", "Dir", ".", "pwd", ")", "env", ".", "config_db", ".", "local", "[", "'path'", "]", "=", "@originalpath", "FileUtils", ".", "rm_rf", "(", "@tmpdir", ")", "if", "File", ".", "exist?", "(", "@tmpdir", ")", "end" ]
Remove the temporary directory and restore the librarian-chef cookbook path.
[ "Remove", "the", "temporary", "directory", "and", "restore", "the", "librarian", "-", "chef", "cookbook", "path", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/librarian.rb#L38-L43
train
chefspec/chefspec
lib/chefspec/policyfile.rb
ChefSpec.Policyfile.setup!
def setup! policyfile_path = File.join(Dir.pwd, 'Policyfile.rb') installer = ChefDK::PolicyfileServices::Install.new( policyfile: policyfile_path, ui: ChefDK::UI.null ) installer.run exporter = ChefDK::PolicyfileServices::ExportRepo.new( policyfile: policyfile_path, export_dir: @tmpdir ) FileUtils.rm_rf(@tmpdir) exporter.run ::RSpec.configure do |config| config.cookbook_path = [ File.join(@tmpdir, 'cookbooks'), File.join(@tmpdir, 'cookbook_artifacts') ] end end
ruby
def setup! policyfile_path = File.join(Dir.pwd, 'Policyfile.rb') installer = ChefDK::PolicyfileServices::Install.new( policyfile: policyfile_path, ui: ChefDK::UI.null ) installer.run exporter = ChefDK::PolicyfileServices::ExportRepo.new( policyfile: policyfile_path, export_dir: @tmpdir ) FileUtils.rm_rf(@tmpdir) exporter.run ::RSpec.configure do |config| config.cookbook_path = [ File.join(@tmpdir, 'cookbooks'), File.join(@tmpdir, 'cookbook_artifacts') ] end end
[ "def", "setup!", "policyfile_path", "=", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "'Policyfile.rb'", ")", "installer", "=", "ChefDK", "::", "PolicyfileServices", "::", "Install", ".", "new", "(", "policyfile", ":", "policyfile_path", ",", "ui", ":", "ChefDK", "::", "UI", ".", "null", ")", "installer", ".", "run", "exporter", "=", "ChefDK", "::", "PolicyfileServices", "::", "ExportRepo", ".", "new", "(", "policyfile", ":", "policyfile_path", ",", "export_dir", ":", "@tmpdir", ")", "FileUtils", ".", "rm_rf", "(", "@tmpdir", ")", "exporter", ".", "run", "::", "RSpec", ".", "configure", "do", "|", "config", "|", "config", ".", "cookbook_path", "=", "[", "File", ".", "join", "(", "@tmpdir", ",", "'cookbooks'", ")", ",", "File", ".", "join", "(", "@tmpdir", ",", "'cookbook_artifacts'", ")", "]", "end", "end" ]
Setup and install the necessary dependencies in the temporary directory
[ "Setup", "and", "install", "the", "necessary", "dependencies", "in", "the", "temporary", "directory" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/policyfile.rb#L24-L48
train
chefspec/chefspec
lib/chefspec/mixins/normalize.rb
ChefSpec.Normalize.resource_name
def resource_name(thing) if thing.respond_to?(:declared_type) && thing.declared_type name = thing.declared_type elsif thing.respond_to?(:resource_name) name = thing.resource_name else name = thing end name.to_s.gsub('-', '_').to_sym end
ruby
def resource_name(thing) if thing.respond_to?(:declared_type) && thing.declared_type name = thing.declared_type elsif thing.respond_to?(:resource_name) name = thing.resource_name else name = thing end name.to_s.gsub('-', '_').to_sym end
[ "def", "resource_name", "(", "thing", ")", "if", "thing", ".", "respond_to?", "(", ":declared_type", ")", "&&", "thing", ".", "declared_type", "name", "=", "thing", ".", "declared_type", "elsif", "thing", ".", "respond_to?", "(", ":resource_name", ")", "name", "=", "thing", ".", "resource_name", "else", "name", "=", "thing", "end", "name", ".", "to_s", ".", "gsub", "(", "'-'", ",", "'_'", ")", ".", "to_sym", "end" ]
Calculate the name of a resource, replacing dashes with underscores and converting symbols to strings and back again. @param [String, Chef::Resource] thing @return [Symbol]
[ "Calculate", "the", "name", "of", "a", "resource", "replacing", "dashes", "with", "underscores", "and", "converting", "symbols", "to", "strings", "and", "back", "again", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/mixins/normalize.rb#L11-L20
train
chefspec/chefspec
lib/chefspec/formatter.rb
ChefSpec.ChefFormatter.node_load_failed
def node_load_failed(node_name, exception, config) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.node_load_failed(node_name, exception, config) display_error(description) end end
ruby
def node_load_failed(node_name, exception, config) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.node_load_failed(node_name, exception, config) display_error(description) end end
[ "def", "node_load_failed", "(", "node_name", ",", "exception", ",", "config", ")", "expecting_exception", "(", "exception", ")", "do", "description", "=", "Chef", "::", "Formatters", "::", "ErrorMapper", ".", "node_load_failed", "(", "node_name", ",", "exception", ",", "config", ")", "display_error", "(", "description", ")", "end", "end" ]
Failed to load node data from the server
[ "Failed", "to", "load", "node", "data", "from", "the", "server" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/formatter.rb#L42-L47
train
chefspec/chefspec
lib/chefspec/formatter.rb
ChefSpec.ChefFormatter.run_list_expand_failed
def run_list_expand_failed(node, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.run_list_expand_failed(node, exception) display_error(description) end end
ruby
def run_list_expand_failed(node, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.run_list_expand_failed(node, exception) display_error(description) end end
[ "def", "run_list_expand_failed", "(", "node", ",", "exception", ")", "expecting_exception", "(", "exception", ")", "do", "description", "=", "Chef", "::", "Formatters", "::", "ErrorMapper", ".", "run_list_expand_failed", "(", "node", ",", "exception", ")", "display_error", "(", "description", ")", "end", "end" ]
Error expanding the run list
[ "Error", "expanding", "the", "run", "list" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/formatter.rb#L50-L55
train
chefspec/chefspec
lib/chefspec/formatter.rb
ChefSpec.ChefFormatter.cookbook_resolution_failed
def cookbook_resolution_failed(expanded_run_list, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.cookbook_resolution_failed(expanded_run_list, exception) display_error(description) end end
ruby
def cookbook_resolution_failed(expanded_run_list, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.cookbook_resolution_failed(expanded_run_list, exception) display_error(description) end end
[ "def", "cookbook_resolution_failed", "(", "expanded_run_list", ",", "exception", ")", "expecting_exception", "(", "exception", ")", "do", "description", "=", "Chef", "::", "Formatters", "::", "ErrorMapper", ".", "cookbook_resolution_failed", "(", "expanded_run_list", ",", "exception", ")", "display_error", "(", "description", ")", "end", "end" ]
Called when there is an error getting the cookbook collection from the server.
[ "Called", "when", "there", "is", "an", "error", "getting", "the", "cookbook", "collection", "from", "the", "server", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/formatter.rb#L67-L72
train
chefspec/chefspec
lib/chefspec/formatter.rb
ChefSpec.ChefFormatter.cookbook_sync_failed
def cookbook_sync_failed(cookbooks, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.cookbook_sync_failed(cookbooks, exception) display_error(description) end end
ruby
def cookbook_sync_failed(cookbooks, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.cookbook_sync_failed(cookbooks, exception) display_error(description) end end
[ "def", "cookbook_sync_failed", "(", "cookbooks", ",", "exception", ")", "expecting_exception", "(", "exception", ")", "do", "description", "=", "Chef", "::", "Formatters", "::", "ErrorMapper", ".", "cookbook_sync_failed", "(", "cookbooks", ",", "exception", ")", "display_error", "(", "description", ")", "end", "end" ]
Called when an error occurs during cookbook sync
[ "Called", "when", "an", "error", "occurs", "during", "cookbook", "sync" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/formatter.rb#L98-L103
train
chefspec/chefspec
lib/chefspec/formatter.rb
ChefSpec.ChefFormatter.recipe_not_found
def recipe_not_found(exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.file_load_failed(nil, exception) display_error(description) end end
ruby
def recipe_not_found(exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.file_load_failed(nil, exception) display_error(description) end end
[ "def", "recipe_not_found", "(", "exception", ")", "expecting_exception", "(", "exception", ")", "do", "description", "=", "Chef", "::", "Formatters", "::", "ErrorMapper", ".", "file_load_failed", "(", "nil", ",", "exception", ")", "display_error", "(", "description", ")", "end", "end" ]
Called when a recipe cannot be resolved
[ "Called", "when", "a", "recipe", "cannot", "be", "resolved" ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/formatter.rb#L176-L181
train
chefspec/chefspec
lib/chefspec/formatter.rb
ChefSpec.ChefFormatter.resource_failed
def resource_failed(resource, action, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.resource_failed(resource, action, exception) display_error(description) end end
ruby
def resource_failed(resource, action, exception) expecting_exception(exception) do description = Chef::Formatters::ErrorMapper.resource_failed(resource, action, exception) display_error(description) end end
[ "def", "resource_failed", "(", "resource", ",", "action", ",", "exception", ")", "expecting_exception", "(", "exception", ")", "do", "description", "=", "Chef", "::", "Formatters", "::", "ErrorMapper", ".", "resource_failed", "(", "resource", ",", "action", ",", "exception", ")", "display_error", "(", "description", ")", "end", "end" ]
Called when a resource fails and will not be retried.
[ "Called", "when", "a", "resource", "fails", "and", "will", "not", "be", "retried", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/formatter.rb#L199-L204
train
chefspec/chefspec
lib/chefspec/renderer.rb
ChefSpec.Renderer.content
def content case resource_name(resource) when :template content_from_template(chef_run, resource) when :file content_from_file(chef_run, resource) when :cookbook_file content_from_cookbook_file(chef_run, resource) else nil end end
ruby
def content case resource_name(resource) when :template content_from_template(chef_run, resource) when :file content_from_file(chef_run, resource) when :cookbook_file content_from_cookbook_file(chef_run, resource) else nil end end
[ "def", "content", "case", "resource_name", "(", "resource", ")", "when", ":template", "content_from_template", "(", "chef_run", ",", "resource", ")", "when", ":file", "content_from_file", "(", "chef_run", ",", "resource", ")", "when", ":cookbook_file", "content_from_cookbook_file", "(", "chef_run", ",", "resource", ")", "else", "nil", "end", "end" ]
Create a new Renderer for the given Chef run and resource. @param [Chef::Runner] chef_run the Chef run containing the resources @param [Chef::Resource] resource the resource to render content from The content of the resource (this method delegates to the) various private rendering methods. @return [String, nil] the contents of the file as a string, or nil if the resource does not contain or respond to a content renderer.
[ "Create", "a", "new", "Renderer", "for", "the", "given", "Chef", "run", "and", "resource", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/renderer.rb#L38-L49
train
chefspec/chefspec
lib/chefspec/renderer.rb
ChefSpec.Renderer.content_from_template
def content_from_template(chef_run, template) cookbook_name = template.cookbook || template.cookbook_name template_location = cookbook_collection(chef_run.node)[cookbook_name].preferred_filename_on_disk_location(chef_run.node, :templates, template.source) if Chef::Mixin::Template.const_defined?(:TemplateContext) # Chef 11+ template_context = Chef::Mixin::Template::TemplateContext.new([]) template_context.update({ :node => chef_run.node, :template_finder => template_finder(chef_run, cookbook_name), }.merge(template.variables)) if template.respond_to?(:helper_modules) # Chef 11.4+ template_context._extend_modules(template.helper_modules) end template_context.render_template(template_location) else template.provider.new(template, chef_run.run_context).send(:render_with_context, template_location) do |file| File.read(file.path) end end end
ruby
def content_from_template(chef_run, template) cookbook_name = template.cookbook || template.cookbook_name template_location = cookbook_collection(chef_run.node)[cookbook_name].preferred_filename_on_disk_location(chef_run.node, :templates, template.source) if Chef::Mixin::Template.const_defined?(:TemplateContext) # Chef 11+ template_context = Chef::Mixin::Template::TemplateContext.new([]) template_context.update({ :node => chef_run.node, :template_finder => template_finder(chef_run, cookbook_name), }.merge(template.variables)) if template.respond_to?(:helper_modules) # Chef 11.4+ template_context._extend_modules(template.helper_modules) end template_context.render_template(template_location) else template.provider.new(template, chef_run.run_context).send(:render_with_context, template_location) do |file| File.read(file.path) end end end
[ "def", "content_from_template", "(", "chef_run", ",", "template", ")", "cookbook_name", "=", "template", ".", "cookbook", "||", "template", ".", "cookbook_name", "template_location", "=", "cookbook_collection", "(", "chef_run", ".", "node", ")", "[", "cookbook_name", "]", ".", "preferred_filename_on_disk_location", "(", "chef_run", ".", "node", ",", ":templates", ",", "template", ".", "source", ")", "if", "Chef", "::", "Mixin", "::", "Template", ".", "const_defined?", "(", ":TemplateContext", ")", "# Chef 11+", "template_context", "=", "Chef", "::", "Mixin", "::", "Template", "::", "TemplateContext", ".", "new", "(", "[", "]", ")", "template_context", ".", "update", "(", "{", ":node", "=>", "chef_run", ".", "node", ",", ":template_finder", "=>", "template_finder", "(", "chef_run", ",", "cookbook_name", ")", ",", "}", ".", "merge", "(", "template", ".", "variables", ")", ")", "if", "template", ".", "respond_to?", "(", ":helper_modules", ")", "# Chef 11.4+", "template_context", ".", "_extend_modules", "(", "template", ".", "helper_modules", ")", "end", "template_context", ".", "render_template", "(", "template_location", ")", "else", "template", ".", "provider", ".", "new", "(", "template", ",", "chef_run", ".", "run_context", ")", ".", "send", "(", ":render_with_context", ",", "template_location", ")", "do", "|", "file", "|", "File", ".", "read", "(", "file", ".", "path", ")", "end", "end", "end" ]
Compute the contents of a template using Chef's templating logic. @param [Chef::RunContext] chef_run the run context for the node @param [Chef::Provider::Template] template the template resource @return [String]
[ "Compute", "the", "contents", "of", "a", "template", "using", "Chef", "s", "templating", "logic", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/renderer.rb#L63-L82
train
chefspec/chefspec
lib/chefspec/renderer.rb
ChefSpec.Renderer.content_from_cookbook_file
def content_from_cookbook_file(chef_run, cookbook_file) cookbook_name = cookbook_file.cookbook || cookbook_file.cookbook_name cookbook = cookbook_collection(chef_run.node)[cookbook_name] File.read(cookbook.preferred_filename_on_disk_location(chef_run.node, :files, cookbook_file.source)) end
ruby
def content_from_cookbook_file(chef_run, cookbook_file) cookbook_name = cookbook_file.cookbook || cookbook_file.cookbook_name cookbook = cookbook_collection(chef_run.node)[cookbook_name] File.read(cookbook.preferred_filename_on_disk_location(chef_run.node, :files, cookbook_file.source)) end
[ "def", "content_from_cookbook_file", "(", "chef_run", ",", "cookbook_file", ")", "cookbook_name", "=", "cookbook_file", ".", "cookbook", "||", "cookbook_file", ".", "cookbook_name", "cookbook", "=", "cookbook_collection", "(", "chef_run", ".", "node", ")", "[", "cookbook_name", "]", "File", ".", "read", "(", "cookbook", ".", "preferred_filename_on_disk_location", "(", "chef_run", ".", "node", ",", ":files", ",", "cookbook_file", ".", "source", ")", ")", "end" ]
Get the contents of a cookbook file using Chef. @param [Chef::RunContext] chef_run the run context for the node @param [Chef::Provider::CookbookFile] cookbook_file the file resource
[ "Get", "the", "contents", "of", "a", "cookbook", "file", "using", "Chef", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/renderer.rb#L106-L110
train
chefspec/chefspec
lib/chefspec/renderer.rb
ChefSpec.Renderer.cookbook_collection
def cookbook_collection(node) if chef_run.respond_to?(:run_context) chef_run.run_context.cookbook_collection # Chef 11.8+ elsif node.respond_to?(:run_context) node.run_context.cookbook_collection # Chef 11+ else node.cookbook_collection # Chef 10 end end
ruby
def cookbook_collection(node) if chef_run.respond_to?(:run_context) chef_run.run_context.cookbook_collection # Chef 11.8+ elsif node.respond_to?(:run_context) node.run_context.cookbook_collection # Chef 11+ else node.cookbook_collection # Chef 10 end end
[ "def", "cookbook_collection", "(", "node", ")", "if", "chef_run", ".", "respond_to?", "(", ":run_context", ")", "chef_run", ".", "run_context", ".", "cookbook_collection", "# Chef 11.8+", "elsif", "node", ".", "respond_to?", "(", ":run_context", ")", "node", ".", "run_context", ".", "cookbook_collection", "# Chef 11+", "else", "node", ".", "cookbook_collection", "# Chef 10", "end", "end" ]
The cookbook collection for the current Chef run context. Handles the differing cases between Chef 10 and Chef 11. @param [Chef::Node] node the Chef node to get the cookbook collection from @return [Array<Chef::Cookbook>]
[ "The", "cookbook", "collection", "for", "the", "current", "Chef", "run", "context", ".", "Handles", "the", "differing", "cases", "between", "Chef", "10", "and", "Chef", "11", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/renderer.rb#L119-L127
train
chefspec/chefspec
lib/chefspec/renderer.rb
ChefSpec.Renderer.template_finder
def template_finder(chef_run, cookbook_name) if Chef::Provider.const_defined?(:TemplateFinder) # Chef 11+ Chef::Provider::TemplateFinder.new(chef_run.run_context, cookbook_name, chef_run.node) else nil end end
ruby
def template_finder(chef_run, cookbook_name) if Chef::Provider.const_defined?(:TemplateFinder) # Chef 11+ Chef::Provider::TemplateFinder.new(chef_run.run_context, cookbook_name, chef_run.node) else nil end end
[ "def", "template_finder", "(", "chef_run", ",", "cookbook_name", ")", "if", "Chef", "::", "Provider", ".", "const_defined?", "(", ":TemplateFinder", ")", "# Chef 11+", "Chef", "::", "Provider", "::", "TemplateFinder", ".", "new", "(", "chef_run", ".", "run_context", ",", "cookbook_name", ",", "chef_run", ".", "node", ")", "else", "nil", "end", "end" ]
Return a new instance of the TemplateFinder if we are running on Chef 11. @param [Chef::RunContext] chef_run the run context for the noe @param [String] cookbook_name the name of the cookbook @return [Chef::Provider::TemplateFinder, nil]
[ "Return", "a", "new", "instance", "of", "the", "TemplateFinder", "if", "we", "are", "running", "on", "Chef", "11", "." ]
b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e
https://github.com/chefspec/chefspec/blob/b7c260d480c3b71a0e61ce46148ec7b9d3f3c40e/lib/chefspec/renderer.rb#L137-L143
train