_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q10700 | Fluent::Plugin.ForwardOutput.read_ack_from_sock | train | def read_ack_from_sock(sock, unpacker)
begin
raw_data = sock.instance_of?(Fluent::PluginHelper::Socket::WrappedSocket::TLS) ? sock.readpartial(@read_length) : sock.recv(@read_length)
rescue Errno::ECONNRESET, EOFError # ECONNRESET for #recv, #EOFError for #readpartial
raw_data = ""
end
info = @sock_ack_waiting_mutex.synchronize{ @sock_ack_waiting.find{|i| i.sock == sock } }
# When connection is closed by remote host, socket is ready to read and #recv returns an empty string that means EOF.
# If this happens we assume the data wasn't delivered and retry it.
if raw_data.empty?
log.warn "destination node closed the connection. regard it as unavailable.", host: info.node.host, port: info.node.port
info.node.disable!
rollback_write(info.chunk_id, update_retry: false)
return nil
else
unpacker.feed(raw_data)
res = unpacker.read
log.trace "getting response from destination", host: info.node.host, port: info.node.port, chunk_id: dump_unique_id_hex(info.chunk_id), response: res
if res['ack'] != info.chunk_id_base64
# Some errors may have occurred when ack and chunk id is different, so send the chunk again.
log.warn "ack in response and chunk id in sent data are different", chunk_id: dump_unique_id_hex(info.chunk_id), ack: res['ack']
rollback_write(info.chunk_id, update_retry: false)
return nil
else
log.trace "got a correct ack response", chunk_id: dump_unique_id_hex(info.chunk_id)
end
return info.chunk_id
end
rescue => e
log.error "unexpected error while receiving ack message", error: e
log.error_backtrace
ensure
info.sock.close_write rescue nil
info.sock.close rescue nil
@sock_ack_waiting_mutex.synchronize do
@sock_ack_waiting.delete(info)
end
end | ruby | {
"resource": ""
} |
q10701 | Fluent.NumericTimeParser.parse_unixtime | train | def parse_unixtime(value)
unless value.is_a?(String) || value.is_a?(Numeric)
raise TimeParseError, "value must be a string or a number: #{value}(value.class)"
end
if @cache1_key == value
return @cache1_time
elsif @cache2_key == value
return @cache2_time
end
begin
time = Fluent::EventTime.new(value.to_i)
rescue => e
raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
end
@cache1_key = @cache2_key
@cache1_time = @cache2_time
@cache2_key = value
@cache2_time = time
time
end | ruby | {
"resource": ""
} |
q10702 | Fluent::Plugin.MonitorAgentInput.plugin_info_by_id | train | def plugin_info_by_id(plugin_id, opts={})
found = all_plugins.find {|pe|
pe.respond_to?(:plugin_id) && pe.plugin_id.to_s == plugin_id
}
if found
get_monitor_info(found, opts)
else
nil
end
end | ruby | {
"resource": ""
} |
q10703 | Fluent::Plugin.MonitorAgentInput.plugins_info_by_type | train | def plugins_info_by_type(type, opts={})
array = all_plugins.select {|pe|
(pe.config['@type'] == type) rescue nil
}
array.map {|pe|
get_monitor_info(pe, opts)
}
end | ruby | {
"resource": ""
} |
q10704 | Fluent::Plugin.MonitorAgentInput.get_monitor_info | train | def get_monitor_info(pe, opts={})
obj = {}
# Common plugin information
obj['plugin_id'] = pe.plugin_id
obj['plugin_category'] = plugin_category(pe)
obj['type'] = pe.config['@type']
obj['config'] = pe.config if opts[:with_config]
# run MONITOR_INFO in plugins' instance context and store the info to obj
MONITOR_INFO.each_pair {|key,code|
begin
catch(:skip) do
obj[key] = pe.instance_exec(&code)
end
rescue NoMethodError => e
unless @first_warn
log.error "NoMethodError in monitoring plugins", key: key, plugin: pe.class, error: e
log.error_backtrace
@first_warn = true
end
rescue => e
log.warn "unexpected error in monitoring plugins", key: key, plugin: pe.class, error: e
end
}
obj['retry'] = get_retry_info(pe.retry) if opts[:with_retry] and pe.instance_variable_defined?(:@retry)
# include all instance variables if :with_debug_info is set
if opts[:with_debug_info]
iv = {}
pe.instance_eval do
instance_variables.each {|sym|
next if IGNORE_ATTRIBUTES.include?(sym)
key = sym.to_s[1..-1] # removes first '@'
iv[key] = instance_variable_get(sym)
}
end
obj['instance_variables'] = iv
elsif ivars = opts[:ivars]
iv = {}
ivars.each {|name|
iname = "@#{name}"
iv[name] = pe.instance_variable_get(iname) if pe.instance_variable_defined?(iname)
}
obj['instance_variables'] = iv
end
obj
end | ruby | {
"resource": ""
} |
q10705 | Devise.ParameterSanitizer.sanitize | train | def sanitize(action)
permissions = @permitted[action]
if permissions.respond_to?(:call)
cast_to_hash permissions.call(default_params)
elsif permissions.present?
cast_to_hash permit_keys(default_params, permissions)
else
unknown_action!(action)
end
end | ruby | {
"resource": ""
} |
q10706 | Devise.ParameterSanitizer.permit | train | def permit(action, keys: nil, except: nil, &block)
if block_given?
@permitted[action] = block
end
if keys.present?
@permitted[action] ||= @auth_keys.dup
@permitted[action].concat(keys)
end
if except.present?
@permitted[action] ||= @auth_keys.dup
@permitted[action] = @permitted[action] - except
end
end | ruby | {
"resource": ""
} |
q10707 | Devise.ParameterFilter.stringify_params | train | def stringify_params(conditions)
return conditions unless conditions.is_a?(Hash)
conditions.each do |k, v|
conditions[k] = v.to_s if param_requires_string_conversion?(v)
end
end | ruby | {
"resource": ""
} |
q10708 | Liquid.Template.parse | train | def parse(source, options = {})
@options = options
@profiling = options[:profile]
@line_numbers = options[:line_numbers] || @profiling
parse_context = options.is_a?(ParseContext) ? options : ParseContext.new(options)
@root = Document.parse(tokenize(source), parse_context)
@warnings = parse_context.warnings
self
end | ruby | {
"resource": ""
} |
q10709 | Liquid.Template.render | train | def render(*args)
return ''.freeze if @root.nil?
context = case args.first
when Liquid::Context
c = args.shift
if @rethrow_errors
c.exception_renderer = ->(e) { raise }
end
c
when Liquid::Drop
drop = args.shift
drop.context = Context.new([drop, assigns], instance_assigns, registers, @rethrow_errors, @resource_limits)
when Hash
Context.new([args.shift, assigns], instance_assigns, registers, @rethrow_errors, @resource_limits)
when nil
Context.new(assigns, instance_assigns, registers, @rethrow_errors, @resource_limits)
else
raise ArgumentError, "Expected Hash or Liquid::Context as parameter"
end
case args.last
when Hash
options = args.pop
registers.merge!(options[:registers]) if options[:registers].is_a?(Hash)
apply_options_to_context(context, options)
when Module, Array
context.add_filters(args.pop)
end
# Retrying a render resets resource usage
context.resource_limits.reset
begin
# render the nodelist.
# for performance reasons we get an array back here. join will make a string out of it.
result = with_profiling(context) do
@root.render(context)
end
result.respond_to?(:join) ? result.join : result
rescue Liquid::MemoryError => e
context.handle_error(e)
ensure
@errors = context.errors
end
end | ruby | {
"resource": ""
} |
q10710 | Liquid.StandardFilters.truncate | train | def truncate(input, length = 50, truncate_string = "...".freeze)
return if input.nil?
input_str = input.to_s
length = Utils.to_integer(length)
truncate_string_str = truncate_string.to_s
l = length - truncate_string_str.length
l = 0 if l < 0
input_str.length > length ? input_str[0...l] + truncate_string_str : input_str
end | ruby | {
"resource": ""
} |
q10711 | Liquid.StandardFilters.sort | train | def sort(input, property = nil)
ary = InputIterator.new(input)
return [] if ary.empty?
if property.nil?
ary.sort do |a, b|
nil_safe_compare(a, b)
end
elsif ary.all? { |el| el.respond_to?(:[]) }
begin
ary.sort { |a, b| nil_safe_compare(a[property], b[property]) }
rescue TypeError
raise_property_error(property)
end
end
end | ruby | {
"resource": ""
} |
q10712 | Liquid.StandardFilters.where | train | def where(input, property, target_value = nil)
ary = InputIterator.new(input)
if ary.empty?
[]
elsif ary.first.respond_to?(:[]) && target_value.nil?
begin
ary.select { |item| item[property] }
rescue TypeError
raise_property_error(property)
end
elsif ary.first.respond_to?(:[])
begin
ary.select { |item| item[property] == target_value }
rescue TypeError
raise_property_error(property)
end
end
end | ruby | {
"resource": ""
} |
q10713 | Liquid.StandardFilters.uniq | train | def uniq(input, property = nil)
ary = InputIterator.new(input)
if property.nil?
ary.uniq
elsif ary.empty? # The next two cases assume a non-empty array.
[]
elsif ary.first.respond_to?(:[])
begin
ary.uniq { |a| a[property] }
rescue TypeError
raise_property_error(property)
end
end
end | ruby | {
"resource": ""
} |
q10714 | Liquid.StandardFilters.replace | train | def replace(input, string, replacement = ''.freeze)
input.to_s.gsub(string.to_s, replacement.to_s)
end | ruby | {
"resource": ""
} |
q10715 | Liquid.StandardFilters.replace_first | train | def replace_first(input, string, replacement = ''.freeze)
input.to_s.sub(string.to_s, replacement.to_s)
end | ruby | {
"resource": ""
} |
q10716 | Liquid.Context.stack | train | def stack(new_scope = nil)
old_stack_used = @this_stack_used
if new_scope
push(new_scope)
@this_stack_used = true
else
@this_stack_used = false
end
yield
ensure
pop if @this_stack_used
@this_stack_used = old_stack_used
end | ruby | {
"resource": ""
} |
q10717 | Liquid.Context.find_variable | train | def find_variable(key, raise_on_not_found: true)
# This was changed from find() to find_index() because this is a very hot
# path and find_index() is optimized in MRI to reduce object allocation
index = @scopes.find_index { |s| s.key?(key) }
scope = @scopes[index] if index
variable = nil
if scope.nil?
@environments.each do |e|
variable = lookup_and_evaluate(e, key, raise_on_not_found: raise_on_not_found)
# When lookup returned a value OR there is no value but the lookup also did not raise
# then it is the value we are looking for.
if !variable.nil? || @strict_variables && raise_on_not_found
scope = e
break
end
end
end
scope ||= @environments.last || @scopes.last
variable ||= lookup_and_evaluate(scope, key, raise_on_not_found: raise_on_not_found)
variable = variable.to_liquid
variable.context = self if variable.respond_to?(:context=)
variable
end | ruby | {
"resource": ""
} |
q10718 | RuboCop.CachedData.deserialize_offenses | train | def deserialize_offenses(offenses)
source_buffer = Parser::Source::Buffer.new(@filename)
source_buffer.source = File.read(@filename, encoding: Encoding::UTF_8)
offenses.map! do |o|
location = Parser::Source::Range.new(source_buffer,
o['location']['begin_pos'],
o['location']['end_pos'])
Cop::Offense.new(o['severity'], location,
o['message'],
o['cop_name'], o['status'].to_sym)
end
end | ruby | {
"resource": ""
} |
q10719 | RuboCop.Token.space_before? | train | def space_before?
position = begin_pos.zero? ? begin_pos : begin_pos - 1
pos.source_buffer.source.match(/\G\s/, position)
end | ruby | {
"resource": ""
} |
q10720 | RuboCop.Options.option | train | def option(opts, *args)
long_opt_symbol = long_opt_symbol(args)
args += Array(OptionsHelp::TEXT[long_opt_symbol])
opts.on(*args) do |arg|
@options[long_opt_symbol] = arg
yield arg if block_given?
end
end | ruby | {
"resource": ""
} |
q10721 | RuboCop.Config.possibly_include_hidden? | train | def possibly_include_hidden?
return @possibly_include_hidden if defined?(@possibly_include_hidden)
@possibly_include_hidden = patterns_to_include.any? do |s|
s.is_a?(Regexp) || s.start_with?('.') || s.include?('/.')
end
end | ruby | {
"resource": ""
} |
q10722 | RuboCop.Runner.check_for_infinite_loop | train | def check_for_infinite_loop(processed_source, offenses)
checksum = processed_source.checksum
if @processed_sources.include?(checksum)
raise InfiniteCorrectionLoop.new(processed_source.path, offenses)
end
@processed_sources << checksum
end | ruby | {
"resource": ""
} |
q10723 | RuboCop.TargetFinder.target_files_in_dir | train | def target_files_in_dir(base_dir = Dir.pwd)
# Support Windows: Backslashes from command-line -> forward slashes
if File::ALT_SEPARATOR
base_dir = base_dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
end
all_files = find_files(base_dir, File::FNM_DOTMATCH)
hidden_files = Set.new(all_files - find_files(base_dir, 0))
base_dir_config = @config_store.for(base_dir)
target_files = all_files.select do |file|
to_inspect?(file, hidden_files, base_dir_config)
end
# Most recently modified file first.
target_files.sort_by! { |path| -Integer(File.mtime(path)) } if fail_fast?
target_files
end | ruby | {
"resource": ""
} |
q10724 | RuboCop.ResultCache.rubocop_checksum | train | def rubocop_checksum
ResultCache.source_checksum ||=
begin
lib_root = File.join(File.dirname(__FILE__), '..')
exe_root = File.join(lib_root, '..', 'exe')
# These are all the files we have `require`d plus everything in the
# exe directory. A change to any of them could affect the cop output
# so we include them in the cache hash.
source_files = $LOADED_FEATURES + Find.find(exe_root).to_a
sources = source_files
.select { |path| File.file?(path) }
.sort
.map { |path| IO.read(path, encoding: Encoding::UTF_8) }
Digest::SHA1.hexdigest(sources.join)
end
end | ruby | {
"resource": ""
} |
q10725 | RuboCop.ResultCache.relevant_options_digest | train | def relevant_options_digest(options)
options = options.reject { |key, _| NON_CHANGING.include?(key) }
options = options.to_s.gsub(/[^a-z]+/i, '_')
# We must avoid making file names too long for some filesystems to handle
# If they are short, we can leave them human-readable
options.length <= 32 ? options : Digest::SHA1.hexdigest(options)
end | ruby | {
"resource": ""
} |
q10726 | RuboCop.ConfigLoaderResolver.merge | train | def merge(base_hash, derived_hash, **opts)
result = base_hash.merge(derived_hash)
keys_appearing_in_both = base_hash.keys & derived_hash.keys
keys_appearing_in_both.each do |key|
if opts[:unset_nil] && derived_hash[key].nil?
result.delete(key)
elsif base_hash[key].is_a?(Hash)
result[key] = merge(base_hash[key], derived_hash[key], **opts)
elsif should_union?(base_hash, key, opts[:inherit_mode])
result[key] = base_hash[key] | derived_hash[key]
elsif opts[:debug]
warn_on_duplicate_setting(base_hash, derived_hash, key, opts)
end
end
result
end | ruby | {
"resource": ""
} |
q10727 | Shell.DoppelGangerClient.build_node | train | def build_node
Chef::Log.trace("Building node object for #{@node_name}")
@node = Chef::Node.find_or_create(node_name)
ohai_data = @ohai.data.merge(@node.automatic_attrs)
@node.consume_external_attrs(ohai_data, nil)
@run_list_expansion = @node.expand!("server")
@expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings
Chef::Log.info("Run List is [#{@node.run_list}]")
Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]")
@node
end | ruby | {
"resource": ""
} |
q10728 | Shell.ModelWrapper.list_objects | train | def list_objects
objects = @model_class.method(:list).arity == 0 ? @model_class.list : @model_class.list(true)
objects.map { |obj| Array(obj).find { |o| o.kind_of?(@model_class) } }
end | ruby | {
"resource": ""
} |
q10729 | ChefConfig.WorkstationConfigLoader.apply_defaults | train | def apply_defaults
# If we don't have a better guess use the username.
Config[:node_name] ||= Etc.getlogin
# If we don't have a key (path or inline) check user.pem and $node_name.pem.
unless Config.key?(:client_key) || Config.key?(:client_key_contents)
key_path = find_default_key(["#{Config[:node_name]}.pem", "user.pem"])
Config[:client_key] = key_path if key_path
end
# Similarly look for a validation key file, though this should be less
# common these days.
unless Config.key?(:validation_key) || Config.key?(:validation_key_contents)
key_path = find_default_key(["#{Config[:validation_client_name]}.pem", "validator.pem", "validation.pem"])
Config[:validation_key] = key_path if key_path
end
end | ruby | {
"resource": ""
} |
q10730 | ChefConfig.WorkstationConfigLoader.find_default_key | train | def find_default_key(key_names)
key_names.each do |filename|
path = Pathname.new(filename)
# If we have a config location (like ./.chef/), look there first.
if config_location
local_path = path.expand_path(File.dirname(config_location))
return local_path.to_s if local_path.exist?
end
# Then check ~/.chef.
home_path = path.expand_path(home_chef_dir)
return home_path.to_s if home_path.exist?
end
nil
end | ruby | {
"resource": ""
} |
q10731 | Sinatra.Helpers.status | train | def status(value = nil)
response.status = Rack::Utils.status_code(value) if value
response.status
end | ruby | {
"resource": ""
} |
q10732 | Sinatra.ConfigFile.config_file | train | def config_file(*paths)
Dir.chdir(root || '.') do
paths.each do |pattern|
Dir.glob(pattern) do |file|
raise UnsupportedConfigType unless ['.yml', '.erb'].include?(File.extname(file))
logger.info "loading config file '#{file}'" if logging? && respond_to?(:logger)
document = ERB.new(IO.read(file)).result
yaml = YAML.load(document)
config = config_for_env(yaml)
config.each_pair { |key, value| set(key, value) }
end
end
end
end | ruby | {
"resource": ""
} |
q10733 | Sinatra.ConfigFile.environment_keys? | train | def environment_keys?(hash)
hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) }
end | ruby | {
"resource": ""
} |
q10734 | Sinatra.LinkHeader.stylesheet | train | def stylesheet(*urls)
urls << {} unless urls.last.respond_to? :to_hash
urls.last[:type] ||= mime_type(:css)
link(:stylesheet, *urls)
end | ruby | {
"resource": ""
} |
q10735 | Sinatra.LinkHeader.link | train | def link(*urls)
opts = urls.last.respond_to?(:to_hash) ? urls.pop : {}
opts[:rel] = urls.shift unless urls.first.respond_to? :to_str
options = opts.map { |k, v| " #{k}=#{v.to_s.inspect}" }
html_pattern = "<link href=\"%s\"#{options.join} />"
http_pattern = ["<%s>", *options].join ";"
link = (response["Link"] ||= "")
urls.map do |url|
link << ",\n" unless link.empty?
link << (http_pattern % url)
html_pattern % url
end.join "\n"
end | ruby | {
"resource": ""
} |
q10736 | Elasticsearch.Benchmarking.each_run | train | def each_run(file)
if file
file = File.new(file)
matrix = YAML.load(ERB.new(file.read).result)
file.close
matrix.each_with_index do |run, i|
DEFAULT_RUN.merge(run)
yield(run, i)
end
else
yield(DEFAULT_RUN)
end
end | ruby | {
"resource": ""
} |
q10737 | FactoryBot.DefinitionProxy.add_attribute | train | def add_attribute(name, &block)
declaration = Declaration::Dynamic.new(name, @ignore, block)
@definition.declare_attribute(declaration)
end | ruby | {
"resource": ""
} |
q10738 | FactoryBot.DefinitionProxy.sequence | train | def sequence(name, *args, &block)
sequence = Sequence.new(name, *args, &block)
FactoryBot::Internal.register_inline_sequence(sequence)
add_attribute(name) { increment_sequence(sequence) }
end | ruby | {
"resource": ""
} |
q10739 | FactoryBot.DefinitionProxy.association | train | def association(name, *options)
if block_given?
raise AssociationDefinitionError.new(
"Unexpected block passed to '#{name}' association "\
"in '#{@definition.name}' factory",
)
else
declaration = Declaration::Association.new(name, *options)
@definition.declare_attribute(declaration)
end
end | ruby | {
"resource": ""
} |
q10740 | GraphQL.Query.lookahead | train | def lookahead
@lookahead ||= begin
ast_node = selected_operation
root_type = warden.root_type_for_operation(ast_node.operation_type || "query")
root_type = root_type.metadata[:type_class] || raise("Invariant: `lookahead` only works with class-based types")
GraphQL::Execution::Lookahead.new(query: self, root_type: root_type, ast_nodes: [ast_node])
end
end | ruby | {
"resource": ""
} |
q10741 | GraphQL.Query.result | train | def result
if !@executed
with_prepared_ast {
Execution::Multiplex.run_queries(@schema, [self], context: @context)
}
end
@result ||= Query::Result.new(query: self, values: @result_values)
end | ruby | {
"resource": ""
} |
q10742 | GraphQL.ObjectType.implements | train | def implements(interfaces, inherit: false)
if !interfaces.is_a?(Array)
raise ArgumentError, "`implements(interfaces)` must be an array, not #{interfaces.class} (#{interfaces})"
end
@clean_interfaces = nil
@clean_inherited_fields = nil
dirty_ifaces = inherit ? @dirty_inherited_interfaces : @dirty_interfaces
dirty_ifaces.concat(interfaces)
end | ruby | {
"resource": ""
} |
q10743 | GraphQL.BackwardsCompatibility.wrap_arity | train | def wrap_arity(callable, from:, to:, name:, last: false)
arity = get_arity(callable)
if arity == to || arity < 0
# It already matches, return it as is
callable
elsif arity == from
# It has the old arity, so wrap it with an arity converter
message ="#{name} with #{from} arguments is deprecated, it now accepts #{to} arguments, see:"
backtrace = caller(0, 20)
# Find the first line in the trace that isn't library internals:
user_line = backtrace.find {|l| l !~ /lib\/graphql/ }
warn(message + "\n" + user_line + "\n")
wrapper = last ? LastArgumentsWrapper : FirstArgumentsWrapper
wrapper.new(callable, from)
else
raise "Can't wrap #{callable} (arity: #{arity}) to have arity #{to}"
end
end | ruby | {
"resource": ""
} |
q10744 | GraphQL.Subscriptions.execute | train | def execute(subscription_id, event, object)
# Lookup the saved data for this subscription
query_data = read_subscription(subscription_id)
# Fetch the required keys from the saved data
query_string = query_data.fetch(:query_string)
variables = query_data.fetch(:variables)
context = query_data.fetch(:context)
operation_name = query_data.fetch(:operation_name)
# Re-evaluate the saved query
result = @schema.execute(
{
query: query_string,
context: context,
subscription_topic: event.topic,
operation_name: operation_name,
variables: variables,
root_value: object,
}
)
deliver(subscription_id, result)
rescue GraphQL::Schema::Subscription::NoUpdateError
# This update was skipped in user code; do nothing.
rescue GraphQL::Schema::Subscription::UnsubscribedError
# `unsubscribe` was called, clean up on our side
# TODO also send `{more: false}` to client?
delete_subscription(subscription_id)
end | ruby | {
"resource": ""
} |
q10745 | GraphQL.Subscriptions.execute_all | train | def execute_all(event, object)
each_subscription_id(event) do |subscription_id|
execute(subscription_id, event, object)
end
end | ruby | {
"resource": ""
} |
q10746 | GraphQL.BaseType.to_definition | train | def to_definition(schema, printer: nil, **args)
printer ||= GraphQL::Schema::Printer.new(schema, **args)
printer.print_type(self)
end | ruby | {
"resource": ""
} |
q10747 | GraphQL.RakeTask.write_outfile | train | def write_outfile(method_name, file)
schema = @load_schema.call(self)
context = @load_context.call(self)
result = schema.public_send(method_name, only: @only, except: @except, context: context)
dir = File.dirname(file)
FileUtils.mkdir_p(dir)
File.write(file, result)
end | ruby | {
"resource": ""
} |
q10748 | GraphQL.RakeTask.define_task | train | def define_task
namespace(@namespace) do
namespace("schema") do
desc("Dump the schema to IDL in #{idl_path}")
task :idl => @dependencies do
write_outfile(:to_definition, idl_path)
puts "Schema IDL dumped into #{idl_path}"
end
desc("Dump the schema to JSON in #{json_path}")
task :json => @dependencies do
write_outfile(:to_json, json_path)
puts "Schema JSON dumped into #{json_path}"
end
desc("Dump the schema to JSON and IDL")
task :dump => [:idl, :json]
end
end
end | ruby | {
"resource": ""
} |
q10749 | GraphQL.Field.prepare_lazy | train | def prepare_lazy(obj, args, ctx)
GraphQL::Execution::Lazy.new {
lazy_resolve(obj, args, ctx)
}
end | ruby | {
"resource": ""
} |
q10750 | GraphQL.Filter.call | train | def call(member, ctx)
(@only ? @only.call(member, ctx) : true) &&
(@except ? !@except.call(member, ctx) : true)
end | ruby | {
"resource": ""
} |
q10751 | GraphQL.Analysis.analyze_query | train | def analyze_query(query, analyzers, multiplex_states: [])
query.trace("analyze_query", { query: query }) do
analyzers_to_run = analyzers.select do |analyzer|
if analyzer.respond_to?(:analyze?)
analyzer.analyze?(query)
else
true
end
end
reducer_states = analyzers_to_run.map { |r| ReducerState.new(r, query) } + multiplex_states
irep = query.internal_representation
irep.operation_definitions.each do |name, op_node|
reduce_node(op_node, reducer_states)
end
reducer_states.map(&:finalize_reducer)
end
end | ruby | {
"resource": ""
} |
q10752 | GraphQL.Analysis.reduce_node | train | def reduce_node(irep_node, reducer_states)
visit_analyzers(:enter, irep_node, reducer_states)
irep_node.typed_children.each do |type_defn, children|
children.each do |name, child_irep_node|
reduce_node(child_irep_node, reducer_states)
end
end
visit_analyzers(:leave, irep_node, reducer_states)
end | ruby | {
"resource": ""
} |
q10753 | GraphQL.Schema.validate | train | def validate(string_or_document, rules: nil, context: nil)
doc = if string_or_document.is_a?(String)
GraphQL.parse(string_or_document)
else
string_or_document
end
query = GraphQL::Query.new(self, document: doc, context: context)
validator_opts = { schema: self }
rules && (validator_opts[:rules] = rules)
validator = GraphQL::StaticValidation::Validator.new(validator_opts)
res = validator.validate(query)
res[:errors]
end | ruby | {
"resource": ""
} |
q10754 | GraphQL.Schema.execute | train | def execute(query_str = nil, **kwargs)
if query_str
kwargs[:query] = query_str
end
# Some of the query context _should_ be passed to the multiplex, too
multiplex_context = if (ctx = kwargs[:context])
{
backtrace: ctx[:backtrace],
tracers: ctx[:tracers],
}
else
{}
end
# Since we're running one query, don't run a multiplex-level complexity analyzer
all_results = multiplex([kwargs], max_complexity: nil, context: multiplex_context)
all_results[0]
end | ruby | {
"resource": ""
} |
q10755 | GraphQL.Schema.check_resolved_type | train | def check_resolved_type(type, object, ctx = :__undefined__)
if ctx == :__undefined__
# Old method signature
ctx = object
object = type
type = nil
end
if object.is_a?(GraphQL::Schema::Object)
object = object.object
end
if type.respond_to?(:graphql_definition)
type = type.graphql_definition
end
# Prefer a type-local function; fall back to the schema-level function
type_proc = type && type.resolve_type_proc
type_result = if type_proc
type_proc.call(object, ctx)
else
yield(type, object, ctx)
end
if type_result.nil?
nil
else
after_lazy(type_result) do |resolved_type_result|
if resolved_type_result.respond_to?(:graphql_definition)
resolved_type_result = resolved_type_result.graphql_definition
end
if !resolved_type_result.is_a?(GraphQL::BaseType)
type_str = "#{resolved_type_result} (#{resolved_type_result.class.name})"
raise "resolve_type(#{object}) returned #{type_str}, but it should return a GraphQL type"
else
resolved_type_result
end
end
end
end | ruby | {
"resource": ""
} |
q10756 | GraphQL.Schema.id_from_object | train | def id_from_object(object, type, ctx)
if @id_from_object_proc.nil?
raise(NotImplementedError, "Can't generate an ID for #{object.inspect} of type #{type}, schema's `id_from_object` must be defined")
else
@id_from_object_proc.call(object, type, ctx)
end
end | ruby | {
"resource": ""
} |
q10757 | GraphQL.Schema.to_definition | train | def to_definition(only: nil, except: nil, context: {})
GraphQL::Schema::Printer.print_schema(self, only: only, except: except, context: context)
end | ruby | {
"resource": ""
} |
q10758 | GraphQL.EnumType.coerce_non_null_input | train | def coerce_non_null_input(value_name, ctx)
if @values_by_name.key?(value_name)
@values_by_name.fetch(value_name).value
elsif match_by_value = @values_by_name.find { |k, v| v.value == value_name }
# this is for matching default values, which are "inputs", but they're
# the Ruby value, not the GraphQL string.
match_by_value[1].value
else
nil
end
end | ruby | {
"resource": ""
} |
q10759 | Jazz.Query.inspect_input | train | def inspect_input(input:)
[
input.class.name,
input.helper_method,
# Access by method
input.string_value,
# Access by key:
input[:string_value],
input.key?(:string_value).to_s,
# ~~Access by legacy key~~ # not anymore
input[:string_value],
input.ensemble,
input.key?(:ensemble).to_s,
]
end | ruby | {
"resource": ""
} |
q10760 | Searchable.Indexing.as_indexed_json | train | def as_indexed_json(options={})
self.as_json(
include: { categories: { only: :title},
authors: { methods: [:full_name, :department], only: [:full_name, :department] },
comments: { only: :text }
})
end | ruby | {
"resource": ""
} |
q10761 | Octokit.Client.inspect | train | def inspect
inspected = super
# mask password
inspected.gsub! @password, '*******' if @password
inspected.gsub! @management_console_password, '*******' if @management_console_password
inspected.gsub! @bearer_token, '********' if @bearer_token
# Only show last 4 of token, secret
inspected.gsub! @access_token, "#{'*'*36}#{@access_token[36..-1]}" if @access_token
inspected.gsub! @client_secret, "#{'*'*36}#{@client_secret[36..-1]}" if @client_secret
inspected
end | ruby | {
"resource": ""
} |
q10762 | Octokit.Connection.agent | train | def agent
@agent ||= Sawyer::Agent.new(endpoint, sawyer_options) do |http|
http.headers[:accept] = default_media_type
http.headers[:content_type] = "application/json"
http.headers[:user_agent] = user_agent
if basic_authenticated?
http.basic_auth(@login, @password)
elsif token_authenticated?
http.authorization 'token', @access_token
elsif bearer_authenticated?
http.authorization 'Bearer', @bearer_token
elsif application_authenticated?
http.params = http.params.merge application_authentication
end
end
end | ruby | {
"resource": ""
} |
q10763 | Octokit.Connection.boolean_from_response | train | def boolean_from_response(method, path, options = {})
request(method, path, options)
@last_response.status == 204
rescue Octokit::NotFound
false
end | ruby | {
"resource": ""
} |
q10764 | Decidim.AriaSelectedLinkToHelper.aria_selected_link_to | train | def aria_selected_link_to(text, link, options = {})
link_to(
text,
link,
options.merge(
"aria-selected": is_active_link?(link, options[:aria_link_type] || :inclusive)
)
)
end | ruby | {
"resource": ""
} |
q10765 | Decidim.AuthorizationFormBuilder.all_fields | train | def all_fields
fields = public_attributes.map do |name, type|
@template.content_tag(:div, input_field(name, type), class: "field")
end
safe_join(fields)
end | ruby | {
"resource": ""
} |
q10766 | Decidim.AuthorizationFormBuilder.input | train | def input(name, options = {})
if options[:as]
send(options[:as].to_s, name, options[:input] || {})
else
type = find_input_type(name.to_s)
input_field(name, type)
end
end | ruby | {
"resource": ""
} |
q10767 | Decidim.HomeActivitySearch.resource_types | train | def resource_types
@resource_types ||= %w(
Decidim::Accountability::Result
Decidim::Blogs::Post
Decidim::Comments::Comment
Decidim::Consultations::Question
Decidim::Debates::Debate
Decidim::Meetings::Meeting
Decidim::Proposals::Proposal
Decidim::Surveys::Survey
Decidim::Assembly
Decidim::Consultation
Decidim::Initiative
Decidim::ParticipatoryProcess
).select do |klass|
klass.safe_constantize.present?
end
end | ruby | {
"resource": ""
} |
q10768 | Decidim.AuthorizationFormHelper.authorization_form_for | train | def authorization_form_for(record, options = {}, &block)
default_options = {
builder: AuthorizationFormBuilder,
as: "authorization_handler",
url: decidim_verifications.authorizations_path
}
options = default_options.merge(options)
decidim_form_for(record, options, &block)
end | ruby | {
"resource": ""
} |
q10769 | Decidim.ApplicationController.store_current_location | train | def store_current_location
return if (devise_controller? && params[:redirect_url].blank?) || !request.format.html?
value = params[:redirect_url] || request.url
store_location_for(:user, value)
end | ruby | {
"resource": ""
} |
q10770 | Decidim.ScopesHelper.has_visible_scopes? | train | def has_visible_scopes?(resource)
resource.participatory_space.scopes_enabled? &&
resource.scope.present? &&
resource.participatory_space.scope != resource.scope
end | ruby | {
"resource": ""
} |
q10771 | Decidim.ScopesHelper.scopes_picker_tag | train | def scopes_picker_tag(name, value, options = {})
root = try(:current_participatory_space)&.scope
field = options[:field] || name
scopes_picker_field_tag name, value, id: options[:id] do |scope|
{ url: decidim.scopes_picker_path(root: root, current: scope&.id, field: field),
text: scope_name_for_picker(scope, I18n.t("decidim.scopes.global")) }
end
end | ruby | {
"resource": ""
} |
q10772 | Decidim.AmendmentsHelper.amendments_for | train | def amendments_for(amendable)
return unless amendable.amendable? && amendable.emendations.count.positive?
content = content_tag(:h2, class: "section-heading", id: "amendments") do
t("section_heading", scope: "decidim.amendments.amendable", count: amendable.emendations.count)
end
content << cell("decidim/collapsible_list",
amendable.emendations,
cell_options: { context: { current_user: current_user } },
list_class: "row small-up-1 medium-up-2 card-grid",
size: 4).to_s
content_tag :div, content.html_safe, class: "section"
end | ruby | {
"resource": ""
} |
q10773 | Decidim.AmendmentsHelper.allowed_to_accept_and_reject? | train | def allowed_to_accept_and_reject?(emendation)
return unless emendation.amendment.evaluating?
emendation.amendable.created_by?(current_user) || current_user.admin?
end | ruby | {
"resource": ""
} |
q10774 | Decidim.AmendmentsHelper.allowed_to_promote? | train | def allowed_to_promote?(emendation)
return unless emendation.amendment.rejected? && emendation.created_by?(current_user)
return if promoted?(emendation)
true
end | ruby | {
"resource": ""
} |
q10775 | Decidim.AmendmentsHelper.promoted? | train | def promoted?(emendation)
logs = Decidim::ActionLog.where(decidim_component_id: emendation.component)
.where(decidim_user_id: emendation.creator_author)
.where(action: "promote")
logs.select { |log| log.extra["promoted_from"] == emendation.id }.present?
end | ruby | {
"resource": ""
} |
q10776 | Decidim.AmendmentsHelper.user_group_select_field | train | def user_group_select_field(form, name)
form.select(name,
current_user.user_groups.verified.map { |g| [g.name, g.id] },
selected: form.object.user_group_id.presence,
include_blank: current_user.name,
label: t("new.amendment_author", scope: "decidim.amendments"))
end | ruby | {
"resource": ""
} |
q10777 | Decidim.AmendmentsHelper.emendation_field_value | train | def emendation_field_value(form, original, key)
return params[:amendment][:emendation_params][key] if params[:amendment].present?
present(form.object.send(original)).send(key)
end | ruby | {
"resource": ""
} |
q10778 | Decidim.MapHelper.static_map_link | train | def static_map_link(resource, options = {})
return unless resource.geocoded?
zoom = options[:zoom] || 17
latitude = resource.latitude
longitude = resource.longitude
map_url = "https://www.openstreetmap.org/?mlat=#{latitude}&mlon=#{longitude}#map=#{zoom}/#{latitude}/#{longitude}"
link_to map_url, target: "_blank" do
image_tag decidim.static_map_path(sgid: resource.to_sgid.to_s)
end
end | ruby | {
"resource": ""
} |
q10779 | Decidim.AttachmentsHelper.attachment_title | train | def attachment_title(attachment)
attachment.title.is_a?(Hash) ? translated_attribute(attachment.title) : attachment.title
end | ruby | {
"resource": ""
} |
q10780 | Decidim.ReplaceButtonsHelper.submit_tag | train | def submit_tag(text = "Save changes", options = {})
options = options.stringify_keys
content_tag :button, text, { "type" => "submit", "name" => "commit" }.update(options)
end | ruby | {
"resource": ""
} |
q10781 | Decidim.Traceability.create | train | def create(klass, author, params, extra_log_info = {})
perform_action!(:create, klass, author, extra_log_info) do
klass.create(params)
end
end | ruby | {
"resource": ""
} |
q10782 | Decidim.Traceability.create! | train | def create!(klass, author, params, extra_log_info = {})
perform_action!(:create, klass, author, extra_log_info) do
klass.create!(params)
end
end | ruby | {
"resource": ""
} |
q10783 | Decidim.Traceability.perform_action! | train | def perform_action!(action, resource, author, extra_log_info = {})
PaperTrail.request(whodunnit: gid(author)) do
Decidim::ApplicationRecord.transaction do
result = block_given? ? yield : nil
loggable_resource = resource.is_a?(Class) ? result : resource
log(action, author, loggable_resource, extra_log_info)
return result
end
end
end | ruby | {
"resource": ""
} |
q10784 | Decidim.Traceability.update! | train | def update!(resource, author, params, extra_log_info = {})
perform_action!(:update, resource, author, extra_log_info) do
resource.update!(params)
resource
end
end | ruby | {
"resource": ""
} |
q10785 | Decidim.ApplicationHelper.html_truncate | train | def html_truncate(text, options = {})
options[:max_length] = options.delete(:length) || options[:max_length]
options[:tail] = options.delete(:separator) || options[:tail] || "..."
options[:count_tags] ||= false
options[:count_tail] ||= false
options[:tail_before_final_tag] ||= true
Truncato.truncate(text, options)
end | ruby | {
"resource": ""
} |
q10786 | Decidim.ApplicationHelper.edit_link | train | def edit_link(link, action, subject, extra_context = {})
return unless current_user
return unless admin_allowed_to?(action, subject, extra_context)
return if content_for?(:edit_link)
content_for(:edit_link, link)
end | ruby | {
"resource": ""
} |
q10787 | Decidim.ParticipatorySpaceManifest.context | train | def context(name = :public, &block)
name = name.to_sym
@contexts ||= {}
if block
context = ParticipatorySpaceContextManifest.new
context.instance_eval(&block)
@contexts[name] = context
end
@contexts.fetch(name)
end | ruby | {
"resource": ""
} |
q10788 | Decidim.FriendlyDates.friendly_created_at | train | def friendly_created_at
current_datetime = Time.current
if created_at > current_datetime.beginning_of_day
I18n.l(created_at, format: :time_of_day)
elsif created_at > current_datetime.beginning_of_week
I18n.l(created_at, format: :day_of_week)
elsif created_at > current_datetime.beginning_of_year
I18n.l(created_at, format: :day_of_month)
else
I18n.l(created_at, format: :day_of_year)
end
end | ruby | {
"resource": ""
} |
q10789 | Decidim.MetricManage.retrieve_participatory_spaces | train | def retrieve_participatory_spaces
Decidim.participatory_space_manifests.map do |space_manifest|
next unless space_manifest.name == :participatory_processes # Temporal limitation
space_manifest.participatory_spaces.call(@organization)
end.flatten.compact
end | ruby | {
"resource": ""
} |
q10790 | Decidim.LocalizedLocalesHelper.localized_locales | train | def localized_locales(collection = Decidim.available_locales)
klass = Class.new do
def initialize(locale)
@locale = locale
end
def id
@locale.to_s
end
def name
I18n.with_locale(@locale) { I18n.t("name", scope: "locale") }
end
end
collection.map { |locale| klass.new(locale) }
end | ruby | {
"resource": ""
} |
q10791 | Decidim.CurrentOrganization.call | train | def call(env)
organization = detect_current_organization(env)
if organization
env["decidim.current_organization"] = organization
@app.call(env)
else
organization = find_secondary_host_org(env)
return @app.call(env) unless organization
location = new_location_for(env, organization.host)
[301, { "Location" => location, "Content-Type" => "text/html", "Content-Length" => "0" }, []]
end
end | ruby | {
"resource": ""
} |
q10792 | Decidim.DestroyAccount.call | train | def call
return broadcast(:invalid) unless @form.valid?
Decidim::User.transaction do
destroy_user_account!
destroy_user_identities
destroy_user_group_memberships
destroy_follows
end
broadcast(:ok)
end | ruby | {
"resource": ""
} |
q10793 | Decidim.ActionAuthorizer.authorize | train | def authorize
raise AuthorizationError, "Missing data" unless component && action
AuthorizationStatusCollection.new(authorization_handlers, user, component, resource)
end | ruby | {
"resource": ""
} |
q10794 | Decidim.UpdateAccount.call | train | def call
return broadcast(:invalid) unless @form.valid?
update_personal_data
update_avatar
update_password
if @user.valid?
@user.save!
notify_followers
broadcast(:ok, @user.unconfirmed_email.present?)
else
@form.errors.add :avatar, @user.errors[:avatar] if @user.errors.has_key? :avatar
broadcast(:invalid)
end
end | ruby | {
"resource": ""
} |
q10795 | Decidim.ResourceHelper.linked_resources_for | train | def linked_resources_for(resource, type, link_name)
linked_resources = resource.linked_resources(type, link_name).group_by { |linked_resource| linked_resource.class.name }
safe_join(linked_resources.map do |klass, resources|
resource_manifest = klass.constantize.resource_manifest
content_tag(:div, class: "section") do
i18n_name = "#{resource.class.name.demodulize.underscore}_#{resource_manifest.name}"
content_tag(:h3, I18n.t(i18n_name, scope: "decidim.resource_links.#{link_name}"), class: "section-heading") +
render(partial: resource_manifest.template, locals: { resources: resources })
end
end)
end | ruby | {
"resource": ""
} |
q10796 | Decidim.ResourceHelper.resource_title | train | def resource_title(resource)
title = resource.try(:title) || resource.try(:name) || resource.try(:subject) || "#{resource.model_name.human} ##{resource.id}"
title = translated_attribute(title) if title.is_a?(Hash)
title
end | ruby | {
"resource": ""
} |
q10797 | Decidim.PaginateHelper.decidim_paginate | train | def decidim_paginate(collection, paginate_params = {})
# Kaminari uses url_for to generate the url, but this doesn't play nice with our engine system
# and unless we remove these params they are added again as query string :(
default_params = {
participatory_process_id: nil,
component_id: nil
}
paginate collection, theme: "decidim", params: paginate_params.merge(default_params)
end | ruby | {
"resource": ""
} |
q10798 | Decidim.ActionLog.participatory_space_lazy | train | def participatory_space_lazy(cache: true)
return if participatory_space_id.blank? || participatory_space_type.blank?
return resouce_lazy if participatory_space_id == resource_id && participatory_space_type == resource_type
self.class.lazy_relation(participatory_space_id, participatory_space_type, cache)
end | ruby | {
"resource": ""
} |
q10799 | Decidim.ResourceSearch.search_scope_id | train | def search_scope_id
clean_scope_ids = if scope_id.is_a?(Hash)
scope_id.values
else
[scope_id].flatten
end
conditions = []
conditions << "decidim_scope_id IS NULL" if clean_scope_ids.delete("global")
conditions.concat(["? = ANY(decidim_scopes.part_of)"] * clean_scope_ids.count) if clean_scope_ids.any?
query.includes(:scope).references(:decidim_scopes).where(conditions.join(" OR "), *clean_scope_ids.map(&:to_i))
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.