_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q14500 | Grape.Entity.serializable_hash | train | def serializable_hash(runtime_options = {})
return nil if object.nil?
opts = options.merge(runtime_options || {})
root_exposure.serializable_value(self, opts)
end | ruby | {
"resource": ""
} |
q14501 | CryptKeeper.LoggedQueries.logged_queries | train | 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 | {
"resource": ""
} |
q14502 | ClassifierReborn.Hasher.word_hash | train | 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 | {
"resource": ""
} |
q14503 | ClassifierReborn.Bayes.classify | train | def classify(text)
result, score = classify_with_score(text)
result = nil if threshold_enabled? && (score < @threshold || score == Float::INFINITY)
result
end | ruby | {
"resource": ""
} |
q14504 | ClassifierReborn.Bayes.custom_stopwords | train | 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 | {
"resource": ""
} |
q14505 | ClassifierReborn.LSI.build_index | train | 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 | {
"resource": ""
} |
q14506 | ClassifierReborn.LSI.highest_relative_content | train | 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 | {
"resource": ""
} |
q14507 | ClassifierReborn.LSI.proximity_array_for_content | train | 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 | {
"resource": ""
} |
q14508 | ClassifierReborn.LSI.proximity_norms_for_content | train | 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 | {
"resource": ""
} |
q14509 | ClassifierReborn.LSI.search | train | 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 | {
"resource": ""
} |
q14510 | ClassifierReborn.LSI.find_related | train | 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 | {
"resource": ""
} |
q14511 | ClassifierReborn.LSI.classify | train | def classify(doc, cutoff = 0.30, &block)
scored_categories(doc, cutoff, &block).last.first
end | ruby | {
"resource": ""
} |
q14512 | ClassifierReborn.LSI.scored_categories | train | 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 | {
"resource": ""
} |
q14513 | ClassifierReborn.LSI.highest_ranked_stems | train | 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 | {
"resource": ""
} |
q14514 | ClassifierReborn.ContentNode.raw_vector_with | train | 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 | {
"resource": ""
} |
q14515 | TTY.Table.rotate_horizontal | train | 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 | {
"resource": ""
} |
q14516 | TTY.Table.row | train | def row(index, &block)
if block_given?
rows.fetch(index) { return self }.each(&block)
self
else
rows.fetch(index) { return nil }
end
end | ruby | {
"resource": ""
} |
q14517 | TTY.Table.column | train | 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 | {
"resource": ""
} |
q14518 | TTY.Table.<< | train | 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 | {
"resource": ""
} |
q14519 | TTY.Table.render_with | train | 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 | {
"resource": ""
} |
q14520 | TTY.Table.coerce | train | 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 | {
"resource": ""
} |
q14521 | StatsD.Instrument.statsd_measure | train | 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 | {
"resource": ""
} |
q14522 | StatsD.Instrument.statsd_distribution | train | 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 | {
"resource": ""
} |
q14523 | StatsD.Instrument.statsd_count | train | 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 | {
"resource": ""
} |
q14524 | Mixlib.ShellOut.format_for_exception | train | 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 | {
"resource": ""
} |
q14525 | Kss.CommentParser.normalize | train | 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 | {
"resource": ""
} |
q14526 | Fluent.ExceptionDetector.transition | train | 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 | {
"resource": ""
} |
q14527 | ServerEngine.DaemonLogger.add | train | 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 | {
"resource": ""
} |
q14528 | Dawn.KnowledgeBaseExperimental.__packed? | train | 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 | {
"resource": ""
} |
q14529 | Dawn.Engine.output_dir | train | 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 | {
"resource": ""
} |
q14530 | Dawn.Engine.apply | train | 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 | {
"resource": ""
} |
q14531 | Neo4j::ActiveRel.Initialize.init_on_load | train | 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 | {
"resource": ""
} |
q14532 | Neo4j::Shared.Property.process_attributes | train | 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 | {
"resource": ""
} |
q14533 | Neo4j::Shared.DeclaredProperties.attributes_nil_hash | train | 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 | {
"resource": ""
} |
q14534 | Neo4j::Shared.DeclaredProperties.attributes_string_map | train | 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 | {
"resource": ""
} |
q14535 | Neo4j::ActiveRel::Persistence.QueryFactory.node_before_callbacks! | train | 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 | {
"resource": ""
} |
q14536 | Neo4j::Shared.Persistence.update | train | 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 | {
"resource": ""
} |
q14537 | Neo4j::ActiveRel.RelatedNode.loaded | train | 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 | {
"resource": ""
} |
q14538 | Neo4j::Shared.TypeConverters.convert_properties_to | train | 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 | {
"resource": ""
} |
q14539 | Neo4j::Shared.TypeConverters.convert_property | train | def convert_property(key, value, direction)
converted_property(primitive_type(key.to_sym), value, direction)
end | ruby | {
"resource": ""
} |
q14540 | Neo4j::Shared.TypeConverters.primitive_type | train | 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 | {
"resource": ""
} |
q14541 | Neo4j::Shared.TypeConverters.skip_conversion? | train | def skip_conversion?(obj, attr, value)
value.nil? || !obj.class.attributes.key?(attr)
end | ruby | {
"resource": ""
} |
q14542 | ChefSpec::Matchers.RenderFileMatcher.matches_content? | train | 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 | {
"resource": ""
} |
q14543 | ChefSpec.ServerMethods.load_data | train | def load_data(name, key, data = {})
ChefSpec::ZeroServer.load_data(name, key, data)
end | ruby | {
"resource": ""
} |
q14544 | ChefSpec.ZeroServer.reset! | train | 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 | {
"resource": ""
} |
q14545 | ChefSpec.ZeroServer.nuke! | train | 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 | {
"resource": ""
} |
q14546 | ChefSpec.ZeroServer.upload_cookbooks! | train | 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 | {
"resource": ""
} |
q14547 | ChefSpec.SoloRunner.converge | train | 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 | {
"resource": ""
} |
q14548 | ChefSpec.SoloRunner.converge_block | train | def converge_block(&block)
converge do
recipe = Chef::Recipe.new(cookbook_name, '_test', run_context)
recipe.instance_exec(&block)
end
end | ruby | {
"resource": ""
} |
q14549 | ChefSpec.SoloRunner.find_resource | train | 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 | {
"resource": ""
} |
q14550 | ChefSpec.SoloRunner.find_resources | train | def find_resources(type)
resource_collection.all_resources.select do |resource|
resource_name(resource) == type.to_sym
end
end | ruby | {
"resource": ""
} |
q14551 | ChefSpec.SoloRunner.step_into? | train | def step_into?(resource)
key = resource_name(resource)
Array(options[:step_into]).map(&method(:resource_name)).include?(key)
end | ruby | {
"resource": ""
} |
q14552 | ChefSpec.SoloRunner.method_missing | train | 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 | {
"resource": ""
} |
q14553 | ChefSpec.SoloRunner.with_default_options | train | 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 | {
"resource": ""
} |
q14554 | ChefSpec.SoloRunner.calling_cookbook_root | train | 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 | {
"resource": ""
} |
q14555 | ChefSpec.SoloRunner.calling_cookbook_path | train | def calling_cookbook_path(options, kaller)
File.expand_path(File.join(calling_cookbook_root(options, kaller), '..'))
end | ruby | {
"resource": ""
} |
q14556 | ChefSpec.SoloRunner.default_role_path | train | 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 | {
"resource": ""
} |
q14557 | ChefSpec.Coverage.start! | train | 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 | {
"resource": ""
} |
q14558 | ChefSpec.Coverage.add_filter | train | 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 | {
"resource": ""
} |
q14559 | ChefSpec.Coverage.set_template | train | 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 | {
"resource": ""
} |
q14560 | ChefSpec.Librarian.teardown! | train | 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 | {
"resource": ""
} |
q14561 | ChefSpec.Policyfile.setup! | train | 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 | {
"resource": ""
} |
q14562 | ChefSpec.Normalize.resource_name | train | 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 | {
"resource": ""
} |
q14563 | ChefSpec.ChefFormatter.node_load_failed | train | 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 | {
"resource": ""
} |
q14564 | ChefSpec.ChefFormatter.run_list_expand_failed | train | 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 | {
"resource": ""
} |
q14565 | ChefSpec.ChefFormatter.cookbook_resolution_failed | train | 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 | {
"resource": ""
} |
q14566 | ChefSpec.ChefFormatter.cookbook_sync_failed | train | 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 | {
"resource": ""
} |
q14567 | ChefSpec.ChefFormatter.recipe_not_found | train | def recipe_not_found(exception)
expecting_exception(exception) do
description = Chef::Formatters::ErrorMapper.file_load_failed(nil, exception)
display_error(description)
end
end | ruby | {
"resource": ""
} |
q14568 | ChefSpec.ChefFormatter.resource_failed | train | 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 | {
"resource": ""
} |
q14569 | ChefSpec.Renderer.content | train | 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 | {
"resource": ""
} |
q14570 | ChefSpec.Renderer.content_from_template | train | 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 | {
"resource": ""
} |
q14571 | ChefSpec.Renderer.content_from_cookbook_file | train | 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 | {
"resource": ""
} |
q14572 | ChefSpec.Renderer.cookbook_collection | train | 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 | {
"resource": ""
} |
q14573 | ChefSpec.Renderer.template_finder | train | 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 | {
"resource": ""
} |
q14574 | ActivityNotification.NotificationApi.send_notification_email | train | def send_notification_email(options = {})
if target.notification_email_allowed?(notifiable, key) &&
notifiable.notification_email_allowed?(target, key) &&
email_subscribed?
send_later = options.has_key?(:send_later) ? options[:send_later] : true
send_later ?
@@notification_mailer.send_notification_email(self, options).deliver_later :
@@notification_mailer.send_notification_email(self, options).deliver_now
end
end | ruby | {
"resource": ""
} |
q14575 | ActivityNotification.NotificationApi.publish_to_optional_targets | train | def publish_to_optional_targets(options = {})
notifiable.optional_targets(target.to_resources_name, key).map { |optional_target|
optional_target_name = optional_target.to_optional_target_name
if optional_target_subscribed?(optional_target_name)
optional_target.notify(self, options[optional_target_name] || {})
[optional_target_name, true]
else
[optional_target_name, false]
end
}.to_h
end | ruby | {
"resource": ""
} |
q14576 | ActivityNotification.NotificationApi.open! | train | def open!(options = {})
opened? and return 0
opened_at = options[:opened_at] || Time.current
with_members = options.has_key?(:with_members) ? options[:with_members] : true
unopened_member_count = with_members ? group_members.unopened_only.count : 0
group_members.update_all(opened_at: opened_at) if with_members
update(opened_at: opened_at)
unopened_member_count + 1
end | ruby | {
"resource": ""
} |
q14577 | ActivityNotification.NotificationApi.group_notifier_count | train | def group_notifier_count(limit = ActivityNotification.config.opened_index_limit)
notification = group_member? && group_owner.present? ? group_owner : self
notification.notifier.present? ? group_member_notifier_count(limit) + 1 : 0
end | ruby | {
"resource": ""
} |
q14578 | ActivityNotification.NotificationApi.remove_from_group | train | def remove_from_group
new_group_owner = group_members.earliest
if new_group_owner.present?
new_group_owner.update(group_owner_id: nil)
group_members.update_all(group_owner_id: new_group_owner.id)
end
new_group_owner
end | ruby | {
"resource": ""
} |
q14579 | ActivityNotification.NotificationApi.notifiable_path | train | def notifiable_path
notifiable.present? or raise ActiveRecord::RecordNotFound.new("Couldn't find notifiable #{notifiable_type}")
notifiable.notifiable_path(target_type, key)
end | ruby | {
"resource": ""
} |
q14580 | ActivityNotification.ViewHelpers.notifications_path_for | train | def notifications_path_for(target, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}notifications_path", options) :
send("#{routing_scope(options)}#{target.to_resource_name}_notifications_path", target, options)
end | ruby | {
"resource": ""
} |
q14581 | ActivityNotification.ViewHelpers.notification_path_for | train | def notification_path_for(notification, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}notification_path", notification, options) :
send("#{routing_scope(options)}#{notification.target.to_resource_name}_notification_path", notification.target, notification, options)
end | ruby | {
"resource": ""
} |
q14582 | ActivityNotification.ViewHelpers.move_notification_path_for | train | def move_notification_path_for(notification, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("move_#{routing_scope(options)}notification_path", notification, options) :
send("move_#{routing_scope(options)}#{notification.target.to_resource_name}_notification_path", notification.target, notification, options)
end | ruby | {
"resource": ""
} |
q14583 | ActivityNotification.ViewHelpers.open_notification_path_for | train | def open_notification_path_for(notification, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("open_#{routing_scope(options)}notification_path", notification, options) :
send("open_#{routing_scope(options)}#{notification.target.to_resource_name}_notification_path", notification.target, notification, options)
end | ruby | {
"resource": ""
} |
q14584 | ActivityNotification.ViewHelpers.open_all_notifications_path_for | train | def open_all_notifications_path_for(target, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("open_all_#{routing_scope(options)}notifications_path", options) :
send("open_all_#{routing_scope(options)}#{target.to_resource_name}_notifications_path", target, options)
end | ruby | {
"resource": ""
} |
q14585 | ActivityNotification.ViewHelpers.notifications_url_for | train | def notifications_url_for(target, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}notifications_url", options) :
send("#{routing_scope(options)}#{target.to_resource_name}_notifications_url", target, options)
end | ruby | {
"resource": ""
} |
q14586 | ActivityNotification.ViewHelpers.notification_url_for | train | def notification_url_for(notification, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}notification_url", notification, options) :
send("#{routing_scope(options)}#{notification.target.to_resource_name}_notification_url", notification.target, notification, options)
end | ruby | {
"resource": ""
} |
q14587 | ActivityNotification.ViewHelpers.move_notification_url_for | train | def move_notification_url_for(notification, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("move_#{routing_scope(options)}notification_url", notification, options) :
send("move_#{routing_scope(options)}#{notification.target.to_resource_name}_notification_url", notification.target, notification, options)
end | ruby | {
"resource": ""
} |
q14588 | ActivityNotification.ViewHelpers.open_notification_url_for | train | def open_notification_url_for(notification, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("open_#{routing_scope(options)}notification_url", notification, options) :
send("open_#{routing_scope(options)}#{notification.target.to_resource_name}_notification_url", notification.target, notification, options)
end | ruby | {
"resource": ""
} |
q14589 | ActivityNotification.ViewHelpers.open_all_notifications_url_for | train | def open_all_notifications_url_for(target, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("open_all_#{routing_scope(options)}notifications_url", options) :
send("open_all_#{routing_scope(options)}#{target.to_resource_name}_notifications_url", target, options)
end | ruby | {
"resource": ""
} |
q14590 | ActivityNotification.ViewHelpers.subscriptions_path_for | train | def subscriptions_path_for(target, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}subscriptions_path", options) :
send("#{routing_scope(options)}#{target.to_resource_name}_subscriptions_path", target, options)
end | ruby | {
"resource": ""
} |
q14591 | ActivityNotification.ViewHelpers.subscription_path_for | train | def subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}subscription_path", subscription, options) :
send("#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14592 | ActivityNotification.ViewHelpers.subscribe_subscription_path_for | train | def subscribe_subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("subscribe_#{routing_scope(options)}subscription_path", subscription, options) :
send("subscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14593 | ActivityNotification.ViewHelpers.unsubscribe_subscription_path_for | train | def unsubscribe_subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("unsubscribe_#{routing_scope(options)}subscription_path", subscription, options) :
send("unsubscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14594 | ActivityNotification.ViewHelpers.subscribe_to_email_subscription_path_for | train | def subscribe_to_email_subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("subscribe_to_email_#{routing_scope(options)}subscription_path", subscription, options) :
send("subscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14595 | ActivityNotification.ViewHelpers.unsubscribe_to_email_subscription_path_for | train | def unsubscribe_to_email_subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("unsubscribe_to_email_#{routing_scope(options)}subscription_path", subscription, options) :
send("unsubscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14596 | ActivityNotification.ViewHelpers.subscribe_to_optional_target_subscription_path_for | train | def subscribe_to_optional_target_subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("subscribe_to_optional_target_#{routing_scope(options)}subscription_path", subscription, options) :
send("subscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14597 | ActivityNotification.ViewHelpers.unsubscribe_to_optional_target_subscription_path_for | train | def unsubscribe_to_optional_target_subscription_path_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("unsubscribe_to_optional_target_#{routing_scope(options)}subscription_path", subscription, options) :
send("unsubscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_path", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
q14598 | ActivityNotification.ViewHelpers.subscriptions_url_for | train | def subscriptions_url_for(target, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}subscriptions_url", options) :
send("#{routing_scope(options)}#{target.to_resource_name}_subscriptions_url", target, options)
end | ruby | {
"resource": ""
} |
q14599 | ActivityNotification.ViewHelpers.subscription_url_for | train | def subscription_url_for(subscription, params = {})
options = params.dup
options.delete(:devise_default_routes) ?
send("#{routing_scope(options)}subscription_url", subscription, options) :
send("#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.