_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11200 | Backup.Model.database | train | def database(name, database_id = nil, &block)
@databases << get_class_from_scope(Database, name)
.new(self, database_id, &block)
end | ruby | {
"resource": ""
} |
q11201 | Backup.Model.store_with | train | def store_with(name, storage_id = nil, &block)
@storages << get_class_from_scope(Storage, name)
.new(self, storage_id, &block)
end | ruby | {
"resource": ""
} |
q11202 | Backup.Model.sync_with | train | def sync_with(name, syncer_id = nil, &block)
@syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
end | ruby | {
"resource": ""
} |
q11203 | Backup.Model.split_into_chunks_of | train | def split_into_chunks_of(chunk_size, suffix_length = 3)
if chunk_size.is_a?(Integer) && suffix_length.is_a?(Integer)
@splitter = Splitter.new(self, chunk_size, suffix_length)
else
raise Error, <<-EOS
Invalid arguments for #split_into_chunks_of()
+chunk_size+ (and optional... | ruby | {
"resource": ""
} |
q11204 | Backup.Model.perform! | train | def perform!
@started_at = Time.now.utc
@time = package.time = started_at.strftime("%Y.%m.%d.%H.%M.%S")
log!(:started)
before_hook
procedures.each do |procedure|
procedure.is_a?(Proc) ? procedure.call : procedure.each(&:perform!)
end
syncers.each(&:perform!)
resc... | ruby | {
"resource": ""
} |
q11205 | Backup.Model.procedures | train | def procedures
return [] unless databases.any? || archives.any?
[-> { prepare! }, databases, archives,
-> { package! }, -> { store! }, -> { clean! }]
end | ruby | {
"resource": ""
} |
q11206 | Backup.Model.store! | train | def store!
storage_results = storages.map do |storage|
begin
storage.perform!
rescue => ex
ex
end
end
first_exception, *other_exceptions = storage_results.select { |result| result.is_a? Exception }
if first_exception
other_exceptions.each do ... | ruby | {
"resource": ""
} |
q11207 | Backup.Model.log! | train | def log!(action)
case action
when :started
Logger.info "Performing Backup for '#{label} (#{trigger})'!\n" \
"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]"
when :finished
if exit_status > 1
ex = exit_status == 2 ? Error : FatalError
err = ex.wrap(exceptio... | ruby | {
"resource": ""
} |
q11208 | Backup.Splitter.after_packaging | train | def after_packaging
suffixes = chunk_suffixes
first_suffix = "a" * suffix_length
if suffixes == [first_suffix]
FileUtils.mv(
File.join(Config.tmp_path, "#{package.basename}-#{first_suffix}"),
File.join(Config.tmp_path, package.basename)
)
else
package.... | ruby | {
"resource": ""
} |
q11209 | Sorcery.Model.include_required_submodules! | train | def include_required_submodules!
class_eval do
@sorcery_config.submodules = ::Sorcery::Controller::Config.submodules
@sorcery_config.submodules.each do |mod|
# TODO: Is there a cleaner way to handle missing submodules?
# rubocop:disable Lint/HandleExceptions
begin
... | ruby | {
"resource": ""
} |
q11210 | Sorcery.Model.init_orm_hooks! | train | def init_orm_hooks!
sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
record.send(sorce... | ruby | {
"resource": ""
} |
q11211 | Chewy.Query.explain | train | def explain(value = nil)
chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end | ruby | {
"resource": ""
} |
q11212 | Chewy.Query.limit | train | def limit(value = nil, &block)
chain { criteria.update_request_options size: block || Integer(value) }
end | ruby | {
"resource": ""
} |
q11213 | Chewy.Query.offset | train | def offset(value = nil, &block)
chain { criteria.update_request_options from: block || Integer(value) }
end | ruby | {
"resource": ""
} |
q11214 | Chewy.Query.facets | train | def facets(params = nil)
raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
if params
chain { criteria.update_facets params }
else
_response['facets'] || {}
end
end | ruby | {
"resource": ""
} |
q11215 | Chewy.Query.script_score | train | def script_score(script, options = {})
scoring = {script_score: {script: script}.merge(options)}
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11216 | Chewy.Query.boost_factor | train | def boost_factor(factor, options = {})
scoring = options.merge(boost_factor: factor.to_i)
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11217 | Chewy.Query.random_score | train | def random_score(seed = Time.now, options = {})
scoring = options.merge(random_score: {seed: seed.to_i})
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11218 | Chewy.Query.field_value_factor | train | def field_value_factor(settings, options = {})
scoring = options.merge(field_value_factor: settings)
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11219 | Chewy.Query.decay | train | def decay(function, field, options = {})
field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
scoring = options.merge(function => {
field => field_options
})
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11220 | Chewy.Query.aggregations | train | def aggregations(params = nil)
@_named_aggs ||= _build_named_aggs
@_fully_qualified_named_aggs ||= _build_fqn_aggs
if params
params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =... | ruby | {
"resource": ""
} |
q11221 | Chewy.Query._build_named_aggs | train | def _build_named_aggs
named_aggs = {}
@_indexes.each do |index|
index.types.each do |type|
type._agg_defs.each do |agg_name, prc|
named_aggs[agg_name] = prc.call
end
end
end
named_aggs
end | ruby | {
"resource": ""
} |
q11222 | Chewy.Query.delete_all | train | def delete_all
if Runtime.version >= '2.0'
plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
end
request = chain... | ruby | {
"resource": ""
} |
q11223 | Chewy.Query.find | train | def find(*ids)
results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a
raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
ids.one? && !ids.first.is_a?(Array) ? results.first : results
end | ruby | {
"resource": ""
} |
q11224 | Acceptance.BoltCommandHelper.bolt_command_on | train | def bolt_command_on(host, command, flags = {}, opts = {})
bolt_command = command.dup
flags.each { |k, v| bolt_command << " #{k} #{v}" }
case host['platform']
when /windows/
execute_powershell_script_on(host, bolt_command, opts)
when /osx/
# Ensure Bolt runs with UTF-8 unde... | ruby | {
"resource": ""
} |
q11225 | Bolt.Applicator.count_statements | train | def count_statements(ast)
case ast
when Puppet::Pops::Model::Program
count_statements(ast.body)
when Puppet::Pops::Model::BlockExpression
ast.statements.count
else
1
end
end | ruby | {
"resource": ""
} |
q11226 | BoltServer.FileCache.create_cache_dir | train | def create_cache_dir(sha)
file_dir = File.join(@cache_dir, sha)
@cache_dir_mutex.with_read_lock do
# mkdir_p doesn't error if the file exists
FileUtils.mkdir_p(file_dir, mode: 0o750)
FileUtils.touch(file_dir)
end
file_dir
end | ruby | {
"resource": ""
} |
q11227 | BoltServer.FileCache.update_file | train | def update_file(file_data)
sha = file_data['sha256']
file_dir = create_cache_dir(file_data['sha256'])
file_path = File.join(file_dir, File.basename(file_data['filename']))
if check_file(file_path, sha)
@logger.debug("Using prexisting task file: #{file_path}")
return file_path
... | ruby | {
"resource": ""
} |
q11228 | PlanExecutor.Executor.as_resultset | train | def as_resultset(targets)
result_array = begin
yield
rescue StandardError => e
@logger.warn(e)
# CODEREVIEW how should we fail if there's an error?
Array(Bolt::Result.from_exception(targets[0], e))
... | ruby | {
"resource": ""
} |
q11229 | Bolt.Executor.queue_execute | train | def queue_execute(targets)
targets.group_by(&:transport).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
report_transport(transport, protocol_targets.count)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_ob... | ruby | {
"resource": ""
} |
q11230 | Bolt.PAL.parse_manifest | train | def parse_manifest(code, filename)
Puppet::Pops::Parser::EvaluatingParser.new.parse_string(code, filename)
rescue Puppet::Error => e
raise Bolt::PAL::PALError, "Failed to parse manifest: #{e}"
end | ruby | {
"resource": ""
} |
q11231 | Bolt.PAL.plan_hash | train | def plan_hash(plan_name, plan)
elements = plan.params_type.elements || []
parameters = elements.each_with_object({}) do |param, acc|
type = if param.value_type.is_a?(Puppet::Pops::Types::PTypeAliasType)
param.value_type.name
else
param.value_type.to_s... | ruby | {
"resource": ""
} |
q11232 | Bolt.PAL.list_modules | train | def list_modules
internal_module_groups = { BOLTLIB_PATH => 'Plan Language Modules',
MODULES_PATH => 'Packaged Modules' }
in_bolt_compiler do
# NOTE: Can replace map+to_h with transform_values when Ruby 2.4
# is the minimum supported version.
P... | ruby | {
"resource": ""
} |
q11233 | Bolt.Target.update_conf | train | def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can ea... | ruby | {
"resource": ""
} |
q11234 | BoltSpec.Plans.config | train | def config
@config ||= begin
conf = Bolt::Config.new(Bolt::Boltdir.new('.'), {})
conf.modulepath = [modulepath].flatten
conf
end
end | ruby | {
"resource": ""
} |
q11235 | Bolt.R10KLogProxy.to_bolt_level | train | def to_bolt_level(level_num)
level_str = Log4r::LNAMES[level_num]&.downcase || 'debug'
if level_str =~ /debug/
:debug
else
level_str.to_sym
end
end | ruby | {
"resource": ""
} |
q11236 | Bolt.Inventory.update_target | train | def update_target(target)
data = @groups.data_for(target.name)
data ||= {}
unless data['config']
@logger.debug("Did not find config for #{target.name} in inventory")
data['config'] = {}
end
data = self.class.localhost_defaults(data) if target.name == 'localhost'
# T... | ruby | {
"resource": ""
} |
q11237 | Byebug.Breakpoint.inspect | train | def inspect
meths = %w[id pos source expr hit_condition hit_count hit_value enabled?]
values = meths.map { |field| "#{field}: #{send(field)}" }.join(", ")
"#<Byebug::Breakpoint #{values}>"
end | ruby | {
"resource": ""
} |
q11238 | Byebug.CommandProcessor.repl | train | def repl
until @proceed
cmd = interface.read_command(prompt)
return if cmd.nil?
next if cmd == ""
run_cmd(cmd)
end
end | ruby | {
"resource": ""
} |
q11239 | Byebug.CommandProcessor.run_auto_cmds | train | def run_auto_cmds(run_level)
safely do
auto_cmds_for(run_level).each { |cmd| cmd.new(self).execute }
end
end | ruby | {
"resource": ""
} |
q11240 | Byebug.CommandProcessor.run_cmd | train | def run_cmd(input)
safely do
command = command_list.match(input)
return command.new(self, input).execute if command
puts safe_inspect(multiple_thread_eval(input))
end
end | ruby | {
"resource": ""
} |
q11241 | Byebug.History.restore | train | def restore
return unless File.exist?(Setting[:histfile])
File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
end | ruby | {
"resource": ""
} |
q11242 | Byebug.History.save | train | def save
n_cmds = Setting[:histsize] > size ? size : Setting[:histsize]
File.open(Setting[:histfile], "w") do |file|
n_cmds.times { file.puts(pop) }
end
clear
end | ruby | {
"resource": ""
} |
q11243 | Byebug.History.to_s | train | def to_s(n_cmds)
show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size
commands = buffer.last(show_size)
last_ids(show_size).zip(commands).map do |l|
format("%<position>5d %<command>s", position: l[0], command: l[1])
end.join("\n") + "\n"
end | ruby | {
"resource": ""
} |
q11244 | Byebug.History.ignore? | train | def ignore?(buf)
return true if /^\s*$/ =~ buf
return false if Readline::HISTORY.empty?
buffer[Readline::HISTORY.length - 1] == buf
end | ruby | {
"resource": ""
} |
q11245 | Byebug.Subcommands.execute | train | def execute
subcmd_name = @match[1]
return puts(help) unless subcmd_name
subcmd = subcommand_list.match(subcmd_name)
raise CommandNotFound.new(subcmd_name, self.class) unless subcmd
subcmd.new(processor, arguments).execute
end | ruby | {
"resource": ""
} |
q11246 | Byebug.Frame.locals | train | def locals
return [] unless _binding
_binding.local_variables.each_with_object({}) do |e, a|
a[e] = _binding.local_variable_get(e)
a
end
end | ruby | {
"resource": ""
} |
q11247 | Byebug.Frame.deco_args | train | def deco_args
return "" if args.empty?
my_args = args.map do |arg|
prefix, default = prefix_and_default(arg[0])
kls = use_short_style?(arg) ? "" : "##{locals[arg[1]].class}"
"#{prefix}#{arg[1] || default}#{kls}"
end
"(#{my_args.join(', ')})"
end | ruby | {
"resource": ""
} |
q11248 | Byebug.Context.stack_size | train | def stack_size
return 0 unless backtrace
backtrace.drop_while { |l| ignored_file?(l.first.path) }
.take_while { |l| !ignored_file?(l.first.path) }
.size
end | ruby | {
"resource": ""
} |
q11249 | Byebug.ListCommand.range | train | def range(input)
return auto_range(@match[1] || "+") unless input
b, e = parse_range(input)
raise("Invalid line range") unless valid_range?(b, e)
[b, e]
end | ruby | {
"resource": ""
} |
q11250 | Byebug.ListCommand.auto_range | train | def auto_range(direction)
prev_line = processor.prev_line
if direction == "=" || prev_line.nil?
source_file_formatter.range_around(frame.line)
else
source_file_formatter.range_from(move(prev_line, size, direction))
end
end | ruby | {
"resource": ""
} |
q11251 | Byebug.ListCommand.display_lines | train | def display_lines(min, max)
puts "\n[#{min}, #{max}] in #{frame.file}"
puts source_file_formatter.lines(min, max).join
end | ruby | {
"resource": ""
} |
q11252 | Byebug.Runner.run | train | def run
Byebug.mode = :standalone
option_parser.order!($ARGV)
return if non_script_option? || error_in_script?
$PROGRAM_NAME = program
Byebug.run_init_script if init_script
loop do
debug_program
break if quit
ControlProcessor.new(nil, interface).process_... | ruby | {
"resource": ""
} |
q11253 | Byebug.Runner.option_parser | train | def option_parser
@option_parser ||= OptionParser.new(banner, 25) do |opts|
opts.banner = banner
OptionSetter.new(self, opts).setup
end
end | ruby | {
"resource": ""
} |
q11254 | Byebug.Interface.read_input | train | def read_input(prompt, save_hist = true)
line = prepare_input(prompt)
return unless line
history.push(line) if save_hist
command_queue.concat(split_commands(line))
command_queue.shift
end | ruby | {
"resource": ""
} |
q11255 | Licensee.License.raw_content | train | def raw_content
return if pseudo_license?
unless File.exist?(path)
raise Licensee::InvalidLicense, "'#{key}' is not a valid license key"
end
@raw_content ||= File.read(path, encoding: 'utf-8')
end | ruby | {
"resource": ""
} |
q11256 | Licensee.ContentHelper.similarity | train | def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end | ruby | {
"resource": ""
} |
q11257 | Licensee.ContentHelper.content_without_title_and_version | train | def content_without_title_and_version
@content_without_title_and_version ||= begin
@_content = nil
ops = %i[html hrs comments markdown_headings title version]
ops.each { |op| strip(op) }
_content
end
end | ruby | {
"resource": ""
} |
q11258 | DeviseTokenAuth.PasswordsController.edit | train | def edit
# if a user is not found, return nil
@resource = resource_class.with_reset_password_token(resource_params[:reset_password_token])
if @resource && @resource.reset_password_period_valid?
client_id, token = @resource.create_token
# ensure that user is confirmed
@resourc... | ruby | {
"resource": ""
} |
q11259 | DeviseTokenAuth.UnlocksController.create | train | def create
return render_create_error_missing_email unless resource_params[:email]
@email = get_case_insensitive_field_from_resource_params(:email)
@resource = find_resource(:email, @email)
if @resource
yield @resource if block_given?
@resource.send_unlock_instructions(
... | ruby | {
"resource": ""
} |
q11260 | DeviseTokenAuth.OmniauthCallbacksController.redirect_callbacks | train | def redirect_callbacks
# derive target redirect route from 'resource_class' param, which was set
# before authentication.
devise_mapping = get_devise_mapping
redirect_route = get_redirect_route(devise_mapping)
# preserve omniauth info for success route. ignore 'extra' in twitter
# ... | ruby | {
"resource": ""
} |
q11261 | DeviseTokenAuth.OmniauthCallbacksController.omniauth_params | train | def omniauth_params
unless defined?(@_omniauth_params)
if request.env['omniauth.params'] && request.env['omniauth.params'].any?
@_omniauth_params = request.env['omniauth.params']
elsif session['dta.omniauth.params'] && session['dta.omniauth.params'].any?
@_omniauth_params ||= s... | ruby | {
"resource": ""
} |
q11262 | DeviseTokenAuth.OmniauthCallbacksController.assign_provider_attrs | train | def assign_provider_attrs(user, auth_hash)
attrs = auth_hash['info'].slice(*user.attribute_names)
user.assign_attributes(attrs)
end | ruby | {
"resource": ""
} |
q11263 | DeviseTokenAuth.OmniauthCallbacksController.whitelisted_params | train | def whitelisted_params
whitelist = params_for_resource(:sign_up)
whitelist.inject({}) do |coll, key|
param = omniauth_params[key.to_s]
coll[key] = param if param
coll
end
end | ruby | {
"resource": ""
} |
q11264 | Danger.TeamCity.bitbucket_pr_from_env | train | def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue
raise "Failed to find a pull request for branch \"#{bran... | ruby | {
"resource": ""
} |
q11265 | Danger.GemsResolver.paths | train | def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end | ruby | {
"resource": ""
} |
q11266 | Danger.Executor.validate_pr! | train | def validate_pr!(cork, fail_if_no_pr)
unless EnvironmentManager.pr?(system_env)
ci_name = EnvironmentManager.local_ci_source(system_env).name.split("::").last
msg = "Not a #{ci_name} Pull Request - skipping `danger` run. "
# circle won't run danger properly if the commit is pushed and bui... | ruby | {
"resource": ""
} |
q11267 | Danger.PluginLinter.print_summary | train | def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rule... | ruby | {
"resource": ""
} |
q11268 | Danger.PluginLinter.class_rules | train | def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not inclu... | ruby | {
"resource": ""
} |
q11269 | Danger.PluginLinter.method_rules | train | def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but i... | ruby | {
"resource": ""
} |
q11270 | Danger.PluginLinter.link | train | def link(ref)
if ref.kind_of?(Range)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue
elsif ref.kind_of?(Integer)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue
el... | ruby | {
"resource": ""
} |
q11271 | Danger.PluginFileResolver.resolve | train | def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs and refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*... | ruby | {
"resource": ""
} |
q11272 | Danger.CircleAPI.pull_request_url | train | def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_... | ruby | {
"resource": ""
} |
q11273 | Danger.CircleAPI.fetch_pull_request_url | train | def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests.first
pull_requests.first[:url]
end | ruby | {
"resource": ""
} |
q11274 | Danger.CircleAPI.fetch_build | train | def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
json = JSON.parse(response.body, symbolize_names: true)
json
end | ruby | {
"resource": ""
} |
q11275 | Danger.DangerfileDangerPlugin.validate_file_contains_plugin! | train | def validate_file_contains_plugin!(file)
plugin_count_was = Danger::Plugin.all_plugins.length
yield
if Danger::Plugin.all_plugins.length == plugin_count_was
raise("#{file} doesn't contain any valid danger plugins.")
end
end | ruby | {
"resource": ""
} |
q11276 | Danger.Dangerfile.print_known_info | train | def print_known_info
rows = []
rows += method_values_for_plugin_hashes(core_dsl_attributes)
rows << ["---", "---"]
rows += method_values_for_plugin_hashes(external_dsl_attributes)
rows << ["---", "---"]
rows << ["SCM", env.scm.class]
rows << ["Source", env.ci_source.class]
... | ruby | {
"resource": ""
} |
q11277 | Danger.DSLError.message | train | def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end | ruby | {
"resource": ""
} |
q11278 | Synapse.Synapse.run | train | def run
log.info "synapse: starting..."
statsd_increment('synapse.start')
# start all the watchers
statsd_time('synapse.watchers.start.time') do
@service_watchers.map do |watcher|
begin
watcher.start
statsd_increment("synapse.watcher.start", ['start_res... | ruby | {
"resource": ""
} |
q11279 | Ahoy.DatabaseStore.visit_or_create | train | def visit_or_create(started_at: nil)
ahoy.track_visit(started_at: started_at) if !visit && Ahoy.server_side_visits
visit
end | ruby | {
"resource": ""
} |
q11280 | Ahoy.Tracker.track | train | def track(name, properties = {}, options = {})
if exclude?
debug "Event excluded"
elsif missing_params?
debug "Missing required parameters"
else
data = {
visit_token: visit_token,
user_id: user.try(:id),
name: name.to_s,
properties: prope... | ruby | {
"resource": ""
} |
q11281 | Ransack.Constants.escape_wildcards | train | def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL and MySQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end | ruby | {
"resource": ""
} |
q11282 | AASM.Base.attribute_name | train | def attribute_name(column_name=nil)
if column_name
@state_machine.config.column = column_name.to_sym
else
@state_machine.config.column ||= :aasm_state
end
@state_machine.config.column
end | ruby | {
"resource": ""
} |
q11283 | AASM.Localizer.i18n_klass | train | def i18n_klass(klass)
klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore
end | ruby | {
"resource": ""
} |
q11284 | AASM.ClassMethods.aasm | train | def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
en... | ruby | {
"resource": ""
} |
q11285 | AASM::Core.Event.may_fire? | train | def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end | ruby | {
"resource": ""
} |
q11286 | SymmetricEncryption.Config.config | train | def config
@config ||= begin
raise(ConfigError, "Cannot find config file: #{file_name}") unless File.exist?(file_name)
env_config = YAML.load(ERB.new(File.new(file_name).read).result)[env]
raise(ConfigError, "Cannot find environment: #{env} in config file: #{file_name}") unless env_config... | ruby | {
"resource": ""
} |
q11287 | SymmetricEncryption.Writer.close | train | def close(close_child_stream = true)
return if closed?
if size.positive?
final = @stream_cipher.final
@ios.write(final) unless final.empty?
end
@ios.close if close_child_stream
@closed = true
end | ruby | {
"resource": ""
} |
q11288 | SymmetricEncryption.Cipher.encrypt | train | def encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
str = str.to_s
return str if str.empty?
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end | ruby | {
"resource": ""
} |
q11289 | SymmetricEncryption.Cipher.decrypt | train | def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING)... | ruby | {
"resource": ""
} |
q11290 | SymmetricEncryption.Cipher.binary_encrypt | train | def binary_encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: c... | ruby | {
"resource": ""
} |
q11291 | SymmetricEncryption.Header.read_string | train | def read_string(buffer, offset)
# TODO: Length check
# Exception when
# - offset exceeds length of buffer
# byteslice truncates when too long, but returns nil when start is beyond end of buffer
len = buffer.byteslice(offset, 2).unpack('v').first
offset += 2
out = ... | ruby | {
"resource": ""
} |
q11292 | SymmetricEncryption.Reader.gets | train | def gets(sep_string, length = nil)
return read(length) if sep_string.nil?
# Read more data until we get the sep_string
while (index = @read_buffer.index(sep_string)).nil? && !@ios.eof?
break if length && @read_buffer.length >= length
read_block
end
index ||= -1
data... | ruby | {
"resource": ""
} |
q11293 | SymmetricEncryption.Reader.read_header | train | def read_header
@pos = 0
# Read first block and check for the header
buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)
# Use cipher specified in header, or global cipher if it has no header
iv, key, cipher_name, cipher = nil
header = Header.new
if h... | ruby | {
"resource": ""
} |
q11294 | Braintree.ResourceCollection.each | train | def each(&block)
@ids.each_slice(@page_size) do |page_of_ids|
resources = @paging_block.call(page_of_ids)
resources.each(&block)
end
end | ruby | {
"resource": ""
} |
q11295 | Audited.Audit.revision | train | def revision
clazz = auditable_type.constantize
(clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
end
end | ruby | {
"resource": ""
} |
q11296 | Audited.Audit.new_attributes | train | def new_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = values.is_a?(Array) ? values.last : values
attrs
end
end | ruby | {
"resource": ""
} |
q11297 | Audited.Audit.old_attributes | train | def old_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = Array(values).first
attrs
end
end | ruby | {
"resource": ""
} |
q11298 | Audited.Audit.undo | train | def undo
case action
when 'create'
# destroys a newly created record
auditable.destroy!
when 'destroy'
# creates a new record with the destroyed record attributes
auditable_type.constantize.create!(audited_changes)
when 'update'
# changes back attributes
... | ruby | {
"resource": ""
} |
q11299 | Audited.Audit.user_as_string= | train | def user_as_string=(user)
# reset both either way
self.user_as_model = self.username = nil
user.is_a?(::ActiveRecord::Base) ?
self.user_as_model = user :
self.username = user
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.