_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q11100 | Overcommit.GitRepo.all_files | train | def all_files
`git ls-files`.
split(/\n/).
map { |relative_file| File.expand_path(relative_file) }.
reject { |file| File.directory?(file) } # Exclude submodule directories
end | ruby | {
"resource": ""
} |
q11101 | Overcommit.GitRepo.restore_merge_state | train | def restore_merge_state
if @merge_head
FileUtils.touch(File.expand_path('MERGE_MODE', Overcommit::Utils.git_dir))
File.open(File.expand_path('MERGE_HEAD', Overcommit::Utils.git_dir), 'w') do |f|
f.write(@merge_head)
end
@merge_head = nil
end
if @merge_msg
File.open(File.expand_path('MERGE_MSG', Overcommit::Utils.git_dir), 'w') do |f|
f.write("#{@merge_msg}\n")
end
@merge_msg = nil
end
end | ruby | {
"resource": ""
} |
q11102 | Overcommit.GitRepo.restore_cherry_pick_state | train | def restore_cherry_pick_state
if @cherry_head
File.open(File.expand_path('CHERRY_PICK_HEAD',
Overcommit::Utils.git_dir), 'w') do |f|
f.write(@cherry_head)
end
@cherry_head = nil
end
end | ruby | {
"resource": ""
} |
q11103 | Overcommit.HookSigner.update_signature! | train | def update_signature!
result = Overcommit::Utils.execute(
%w[git config --local] + [signature_config_key, signature]
)
unless result.success?
raise Overcommit::Exceptions::GitConfigError,
"Unable to write to local repo git config: #{result.stderr}"
end
end | ruby | {
"resource": ""
} |
q11104 | Overcommit.HookSigner.signature | train | def signature
hook_config = @config.for_hook(@hook_name, @context.hook_class_name).
dup.
tap { |config| IGNORED_CONFIG_KEYS.each { |k| config.delete(k) } }
content_to_sign =
if signable_file?(hook_path) && Overcommit::GitRepo.tracked?(hook_path)
hook_contents
end
Digest::SHA256.hexdigest(content_to_sign.to_s + hook_config.to_s)
end | ruby | {
"resource": ""
} |
q11105 | Overcommit.Printer.end_hook | train | def end_hook(hook, status, output)
# Want to print the header for quiet hooks only if the result wasn't good
# so that the user knows what failed
print_header(hook) if (!hook.quiet? && !@config['quiet']) || status != :pass
print_result(hook, status, output)
end | ruby | {
"resource": ""
} |
q11106 | Rake.MakefileLoader.process_line | train | def process_line(line) # :nodoc:
file_tasks, args = line.split(":", 2)
return if args.nil?
dependents = args.split.map { |d| respace(d) }
file_tasks.scan(/\S+/) do |file_task|
file_task = respace(file_task)
file file_task => dependents
end
end | ruby | {
"resource": ""
} |
q11107 | Rake.Task.invoke | train | def invoke(*args)
task_args = TaskArguments.new(arg_names, args)
invoke_with_call_chain(task_args, InvocationChain::EMPTY)
end | ruby | {
"resource": ""
} |
q11108 | Rake.Task.transform_comments | train | def transform_comments(separator, &block)
if @comments.empty?
nil
else
block ||= lambda { |c| c }
@comments.map(&block).join(separator)
end
end | ruby | {
"resource": ""
} |
q11109 | Rake.FileUtilsExt.rake_merge_option | train | def rake_merge_option(args, defaults)
if Hash === args.last
defaults.update(args.last)
args.pop
end
args.push defaults
args
end | ruby | {
"resource": ""
} |
q11110 | Rake.FileUtilsExt.rake_check_options | train | def rake_check_options(options, *optdecl)
h = options.dup
optdecl.each do |name|
h.delete name
end
raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless
h.empty?
end | ruby | {
"resource": ""
} |
q11111 | Rake.Scope.trim | train | def trim(n)
result = self
while n > 0 && !result.empty?
result = result.tail
n -= 1
end
result
end | ruby | {
"resource": ""
} |
q11112 | Rake.Application.init | train | def init(app_name="rake", argv = ARGV)
standard_exception_handling do
@name = app_name
begin
args = handle_options argv
rescue ArgumentError
# Backward compatibility for capistrano
args = handle_options
end
collect_command_line_tasks(args)
end
end | ruby | {
"resource": ""
} |
q11113 | Rake.Application.have_rakefile | train | def have_rakefile # :nodoc:
@rakefiles.each do |fn|
if File.exist?(fn)
others = FileList.glob(fn, File::FNM_CASEFOLD)
return others.size == 1 ? others.first : fn
elsif fn == ""
return fn
end
end
return nil
end | ruby | {
"resource": ""
} |
q11114 | Rake.FileList.sub | train | def sub(pat, rep)
inject(self.class.new) { |res, fn| res << fn.sub(pat, rep) }
end | ruby | {
"resource": ""
} |
q11115 | Rake.FileList.gsub | train | def gsub(pat, rep)
inject(self.class.new) { |res, fn| res << fn.gsub(pat, rep) }
end | ruby | {
"resource": ""
} |
q11116 | Rake.FileList.sub! | train | def sub!(pat, rep)
each_with_index { |fn, i| self[i] = fn.sub(pat, rep) }
self
end | ruby | {
"resource": ""
} |
q11117 | Rake.FileList.gsub! | train | def gsub!(pat, rep)
each_with_index { |fn, i| self[i] = fn.gsub(pat, rep) }
self
end | ruby | {
"resource": ""
} |
q11118 | Rake.PackageTask.define | train | def define
fail "Version required (or :noversion)" if @version.nil?
@version = nil if :noversion == @version
desc "Build all the packages"
task :package
desc "Force a rebuild of the package files"
task repackage: [:clobber_package, :package]
desc "Remove package products"
task :clobber_package do
rm_r package_dir rescue nil
end
task clobber: [:clobber_package]
[
[need_tar, tgz_file, "z"],
[need_tar_gz, tar_gz_file, "z"],
[need_tar_bz2, tar_bz2_file, "j"],
[need_tar_xz, tar_xz_file, "J"]
].each do |need, file, flag|
if need
task package: ["#{package_dir}/#{file}"]
file "#{package_dir}/#{file}" =>
[package_dir_path] + package_files do
chdir(package_dir) { sh @tar_command, "#{flag}cvf", file, package_name }
end
end
end
if need_zip
task package: ["#{package_dir}/#{zip_file}"]
file "#{package_dir}/#{zip_file}" =>
[package_dir_path] + package_files do
chdir(package_dir) { sh @zip_command, "-r", zip_file, package_name }
end
end
directory package_dir_path => @package_files do
@package_files.each do |fn|
f = File.join(package_dir_path, fn)
fdir = File.dirname(f)
mkdir_p(fdir) unless File.exist?(fdir)
if File.directory?(fn)
mkdir_p(f)
else
rm_f f
safe_ln(fn, f)
end
end
end
self
end | ruby | {
"resource": ""
} |
q11119 | Rake.ThreadPool.join | train | def join
@threads_mon.synchronize do
begin
stat :joining
@join_cond.wait unless @threads.empty?
stat :joined
rescue Exception => e
stat :joined
$stderr.puts e
$stderr.print "Queue contains #{@queue.size} items. " +
"Thread pool contains #{@threads.count} threads\n"
$stderr.print "Current Thread #{Thread.current} status = " +
"#{Thread.current.status}\n"
$stderr.puts e.backtrace.join("\n")
@threads.each do |t|
$stderr.print "Thread #{t} status = #{t.status}\n"
$stderr.puts t.backtrace.join("\n")
end
raise e
end
end
end | ruby | {
"resource": ""
} |
q11120 | Rake.ThreadPool.process_queue_item | train | def process_queue_item #:nodoc:
return false if @queue.empty?
# Even though we just asked if the queue was empty, it
# still could have had an item which by this statement
# is now gone. For this reason we pass true to Queue#deq
# because we will sleep indefinitely if it is empty.
promise = @queue.deq(true)
stat :dequeued, item_id: promise.object_id
promise.work
return true
rescue ThreadError # this means the queue is empty
false
end | ruby | {
"resource": ""
} |
q11121 | Rake.TaskManager.resolve_args_without_dependencies | train | def resolve_args_without_dependencies(args)
task_name = args.shift
if args.size == 1 && args.first.respond_to?(:to_ary)
arg_names = args.first.to_ary
else
arg_names = args
end
[task_name, arg_names, []]
end | ruby | {
"resource": ""
} |
q11122 | Rake.TaskManager.enhance_with_matching_rule | train | def enhance_with_matching_rule(task_name, level=0)
fail Rake::RuleRecursionOverflowError,
"Rule Recursion Too Deep" if level >= 16
@rules.each do |pattern, args, extensions, block|
if pattern && pattern.match(task_name)
task = attempt_rule(task_name, pattern, args, extensions, block, level)
return task if task
end
end
nil
rescue Rake::RuleRecursionOverflowError => ex
ex.add_target(task_name)
fail ex
end | ruby | {
"resource": ""
} |
q11123 | Rake.TaskManager.find_location | train | def find_location
locations = caller
i = 0
while locations[i]
return locations[i + 1] if locations[i] =~ /rake\/dsl_definition.rb/
i += 1
end
nil
end | ruby | {
"resource": ""
} |
q11124 | Rake.TaskManager.attempt_rule | train | def attempt_rule(task_name, task_pattern, args, extensions, block, level)
sources = make_sources(task_name, task_pattern, extensions)
prereqs = sources.map { |source|
trace_rule level, "Attempting Rule #{task_name} => #{source}"
if File.exist?(source) || Rake::Task.task_defined?(source)
trace_rule level, "(#{task_name} => #{source} ... EXIST)"
source
elsif parent = enhance_with_matching_rule(source, level + 1)
trace_rule level, "(#{task_name} => #{source} ... ENHANCE)"
parent.name
else
trace_rule level, "(#{task_name} => #{source} ... FAIL)"
return nil
end
}
task = FileTask.define_task(task_name, { args => prereqs }, &block)
task.sources = prereqs
task
end | ruby | {
"resource": ""
} |
q11125 | Rake.FileTask.out_of_date? | train | def out_of_date?(stamp)
all_prerequisite_tasks.any? { |prereq|
prereq_task = application[prereq, @scope]
if prereq_task.instance_of?(Rake::FileTask)
prereq_task.timestamp > stamp || @application.options.build_all
else
prereq_task.timestamp > stamp
end
}
end | ruby | {
"resource": ""
} |
q11126 | Rake.TaskArguments.new_scope | train | def new_scope(names)
values = names.map { |n| self[n] }
self.class.new(names, values + extras, self)
end | ruby | {
"resource": ""
} |
q11127 | Rake.Promise.work | train | def work
stat :attempting_lock_on, item_id: object_id
if @mutex.try_lock
stat :has_lock_on, item_id: object_id
chore
stat :releasing_lock_on, item_id: object_id
@mutex.unlock
else
stat :bailed_on, item_id: object_id
end
end | ruby | {
"resource": ""
} |
q11128 | Bosh.Retryable.retryer | train | def retryer(&blk)
loop do
@try_count += 1
y = blk.call(@try_count, @retry_exception)
@retry_exception = nil # no exception was raised in the block
return y if y
raise Bosh::Common::RetryCountExceeded if @try_count >= @retry_limit
wait
end
rescue Exception => exception
raise unless @matchers.any? { |m| m.matches?(exception) }
raise unless exception.message =~ @matching
raise if @try_count >= @retry_limit
@retry_exception = exception
wait
retry
ensure
@ensure_callback.call(@try_count)
end | ruby | {
"resource": ""
} |
q11129 | Bosh::Director.PowerDnsManager.flush_dns_cache | train | def flush_dns_cache
if @flush_command && !@flush_command.empty?
stdout, stderr, status = Open3.capture3(@flush_command)
if status == 0
@logger.debug("Flushed #{stdout.chomp} records from DNS cache")
else
@logger.warn("Failed to flush DNS cache: #{stderr.chomp}")
end
end
end | ruby | {
"resource": ""
} |
q11130 | Bosh::Spec.Director.instance | train | def instance(instance_group_name, index_or_id, options = { deployment_name: Deployments::DEFAULT_DEPLOYMENT_NAME })
find_instance(instances(options), instance_group_name, index_or_id)
end | ruby | {
"resource": ""
} |
q11131 | Bosh::Monitor.Deployment.upsert_agent | train | def upsert_agent(instance)
@logger.info("Adding agent #{instance.agent_id} (#{instance.job}/#{instance.id}) to #{name}...")
agent_id = instance.agent_id
if agent_id.nil?
@logger.warn("No agent id for instance #{instance.job}/#{instance.id} in deployment #{name}")
#count agents for instances with deleted vm, which expect to have vm
if instance.expects_vm? && !instance.has_vm?
agent = Agent.new("agent_with_no_vm", deployment: name)
@instance_id_to_agent[instance.id] = agent
agent.update_instance(instance)
end
return false
end
# Idle VMs, we don't care about them, but we still want to track them
if instance.job.nil?
@logger.debug("VM with no job found: #{agent_id}")
end
agent = @agent_id_to_agent[agent_id]
if agent.nil?
@logger.debug("Discovered agent #{agent_id}")
agent = Agent.new(agent_id, deployment: name)
@agent_id_to_agent[agent_id] = agent
@instance_id_to_agent.delete(instance.id) if @instance_id_to_agent[instance.id]
end
agent.update_instance(instance)
true
end | ruby | {
"resource": ""
} |
q11132 | Bosh::Director.NatsRpc.subscribe_inbox | train | def subscribe_inbox
# double-check locking to reduce synchronization
if @subject_id.nil?
# nats lazy-load needs to be outside the synchronized block
client = nats
@lock.synchronize do
if @subject_id.nil?
@subject_id = client.subscribe("#{@inbox_name}.>") do |message, _, subject|
@handled_response = true
handle_response(message, subject)
end
end
end
end
end | ruby | {
"resource": ""
} |
q11133 | Bosh::Director.CompiledPackageRequirement.dependency_spec | train | def dependency_spec
spec = {}
@dependencies.each do |dependency|
unless dependency.compiled?
raise DirectorError,
'Cannot generate package dependency spec ' \
"for '#{@package.name}', " \
"'#{dependency.package.name}' hasn't been compiled yet"
end
compiled_package = dependency.compiled_package
spec[compiled_package.name] = {
'name' => compiled_package.name,
'version' => "#{compiled_package.version}.#{compiled_package.build}",
'sha1' => compiled_package.sha1,
'blobstore_id' => compiled_package.blobstore_id,
}
end
spec
end | ruby | {
"resource": ""
} |
q11134 | Bosh::Director.AgentClient.format_exception | train | def format_exception(exception)
return exception.to_s unless exception.is_a?(Hash)
msg = exception['message'].to_s
if exception['backtrace']
msg += "\n"
msg += Array(exception['backtrace']).join("\n")
end
if exception['blobstore_id']
blob = download_and_delete_blob(exception['blobstore_id'])
msg += "\n"
msg += blob.to_s
end
msg
end | ruby | {
"resource": ""
} |
q11135 | Bosh::Director.AgentClient.inject_compile_log | train | def inject_compile_log(response)
if response['value'] && response['value'].is_a?(Hash) &&
response['value']['result'].is_a?(Hash) &&
blob_id = response['value']['result']['compile_log_id']
compile_log = download_and_delete_blob(blob_id)
response['value']['result']['compile_log'] = compile_log
end
end | ruby | {
"resource": ""
} |
q11136 | Bosh::Director.DownloadHelper.download_remote_file | train | def download_remote_file(resource, remote_file, local_file, num_redirects = 0)
@logger.info("Downloading remote #{resource} from #{remote_file}") if @logger
uri = URI.parse(remote_file)
req = Net::HTTP::Get.new(uri)
if uri.user && uri.password
req.basic_auth uri.user, uri.password
end
Net::HTTP.start(uri.host, uri.port, :ENV,
:use_ssl => uri.scheme == 'https') do |http|
http.request req do |response|
case response
when Net::HTTPSuccess
File.open(local_file, 'wb') do |file|
response.read_body do |chunk|
file.write(chunk)
end
end
when Net::HTTPFound, Net::HTTPMovedPermanently
raise ResourceError, "Too many redirects at '#{remote_file}'." if num_redirects >= 9
location = response.header['location']
raise ResourceError, "No location header for redirect found at '#{remote_file}'." if location.nil?
location = URI.join(uri, location).to_s
download_remote_file(resource, location, local_file, num_redirects + 1)
when Net::HTTPNotFound
@logger.error("Downloading remote #{resource} from #{remote_file} failed: #{response.message}") if @logger
raise ResourceNotFound, "No #{resource} found at '#{remote_file}'."
else
@logger.error("Downloading remote #{resource} from #{remote_file} failed: #{response.message}") if @logger
raise ResourceError, "Downloading remote #{resource} failed. Check task debug log for details."
end
end
end
rescue URI::Error, SocketError, ::Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, EOFError,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
@logger.error("Downloading remote #{resource} from #{remote_file} failed: #{e.inspect}") if @logger
raise ResourceError, "Downloading remote #{resource} failed. Check task debug log for details."
end | ruby | {
"resource": ""
} |
q11137 | Bosh::Registry.InstanceManager.update_settings | train | def update_settings(instance_id, settings)
params = {
:instance_id => instance_id
}
instance = Models::RegistryInstance[params] || Models::RegistryInstance.new(params)
instance.settings = settings
instance.save
end | ruby | {
"resource": ""
} |
q11138 | Bosh::Registry.InstanceManager.read_settings | train | def read_settings(instance_id, remote_ip = nil)
check_instance_ips(remote_ip, instance_id) if remote_ip
get_instance(instance_id).settings
end | ruby | {
"resource": ""
} |
q11139 | Bosh::Director::Links.LinksManager.find_or_create_provider_intent | train | def find_or_create_provider_intent(link_provider:, link_original_name:, link_type:)
intent = Bosh::Director::Models::Links::LinkProviderIntent.find(
link_provider: link_provider,
original_name: link_original_name,
)
if intent.nil?
intent = Bosh::Director::Models::Links::LinkProviderIntent.create(
link_provider: link_provider,
original_name: link_original_name,
type: link_type,
)
else
intent.type = link_type
end
intent.serial_id = @serial_id if intent.serial_id != @serial_id
intent.save
end | ruby | {
"resource": ""
} |
q11140 | Bosh::Director::Links.LinksManager.consumer? | train | def consumer?(provider_intent, deployment_plan)
return true if provider_intent.shared
link_consumers = deployment_plan.model.link_consumers
link_consumers = link_consumers.select do |consumer|
consumer.serial_id == @serial_id
end
link_consumers.any? do |consumer|
consumer.intents.any? do |consumer_intent|
can_be_consumed?(consumer, provider_intent, consumer_intent, @serial_id)
end
end
end | ruby | {
"resource": ""
} |
q11141 | Bosh::Spec.Waiter.wait | train | def wait(retries_left, &blk)
blk.call
rescue Exception => e
retries_left -= 1
if retries_left > 0
sleep(0.5)
retry
else
raise
end
end | ruby | {
"resource": ""
} |
q11142 | Bosh::Director.Lock.lock | train | def lock
acquire
@refresh_thread = Thread.new do
renew_interval = [1.0, @expiration/2].max
begin
done_refreshing = false
until @unlock || done_refreshing
@refresh_mutex.synchronize do
@refresh_signal.wait(@refresh_mutex, renew_interval)
break if @unlock
@logger.debug("Renewing lock: #@name")
lock_expiration = Time.now.to_f + @expiration + 1
if Models::Lock.where(name: @name, uid: @uid).update(expired_at: Time.at(lock_expiration)) == 0
done_refreshing = true
end
end
end
ensure
if !@unlock
Models::Event.create(
user: Config.current_job.username,
action: 'lost',
object_type: 'lock',
object_name: @name,
task: @task_id,
deployment: @deployment_name,
error: 'Lock renewal thread exiting',
timestamp: Time.now,
)
Models::Task[@task_id].update(state: 'cancelling')
@logger.debug('Lock renewal thread exiting')
end
end
end
if block_given?
begin
yield
ensure
release
end
end
end | ruby | {
"resource": ""
} |
q11143 | Bosh::Director.Lock.release | train | def release
@refresh_mutex.synchronize {
@unlock = true
delete
@refresh_signal.signal
}
@refresh_thread.join if @refresh_thread
@event_manager.create_event(
{
user: Config.current_job.username,
action: 'release',
object_type: 'lock',
object_name: @name,
task: @task_id,
deployment: @deployment_name,
}
)
end | ruby | {
"resource": ""
} |
q11144 | Bosh::Director.OrphanNetworkManager.list_orphan_networks | train | def list_orphan_networks
Models::Network.where(orphaned: true).map do |network|
{
'name' => network.name,
'type' => network.type,
'created_at' => network.created_at.to_s,
'orphaned_at' => network.orphaned_at.to_s,
}
end
end | ruby | {
"resource": ""
} |
q11145 | Bosh::Director.JobRunner.perform_job | train | def perform_job(*args)
@task_logger.info('Creating job')
job = @job_class.new(*args)
Config.current_job = job
job.task_id = @task_id
job.task_checkpoint # cancelled in the queue?
run_checkpointing
@task_logger.info("Performing task: #{@task.inspect}")
@task.timestamp = Time.now
@task.started_at = Time.now
@task.checkpoint_time = Time.now
@task.save
result = job.perform
@task_logger.info('Done')
finish_task(:done, result)
rescue Bosh::Director::TaskCancelled => e
log_exception(e)
@task_logger.info("Task #{@task.id} cancelled")
finish_task(:cancelled, 'task cancelled')
rescue Exception => e
log_exception(e)
@task_logger.error("#{e}\n#{e.backtrace.join("\n")}")
finish_task(:error, e)
end | ruby | {
"resource": ""
} |
q11146 | Bosh::Director.JobRunner.run_checkpointing | train | def run_checkpointing
# task check pointer is scoped to separate class to avoid
# the secondary thread and main thread modifying the same @task
# variable (and accidentally clobbering it in the process)
task_checkpointer = TaskCheckPointer.new(@task.id)
Thread.new do
with_thread_name("task:#{@task.id}-checkpoint") do
while true
sleep(Config.task_checkpoint_interval)
task_checkpointer.checkpoint
end
end
end
end | ruby | {
"resource": ""
} |
q11147 | Bosh::Director.JobRunner.truncate | train | def truncate(string, len = 128)
stripped = string.strip[0..len]
if stripped.length > len
stripped.gsub(/\s+?(\S+)?$/, "") + "..."
else
stripped
end
end | ruby | {
"resource": ""
} |
q11148 | Bosh::Director.JobRunner.finish_task | train | def finish_task(state, result)
@task.refresh
@task.state = state
@task.result = truncate(result.to_s)
@task.timestamp = Time.now
@task.save
end | ruby | {
"resource": ""
} |
q11149 | Bosh::Director.JobRunner.log_exception | train | def log_exception(exception)
# Event log is being used here to propagate the error.
# It's up to event log renderer to find the error and
# signal it properly.
director_error = DirectorError.create_from_exception(exception)
Config.event_log.log_error(director_error)
end | ruby | {
"resource": ""
} |
q11150 | Bosh::Director.CompiledPackageRequirementGenerator.generate! | train | def generate!(requirements, instance_group, job, package, stemcell)
# Our assumption here is that package dependency graph
# has no cycles: this is being enforced on release upload.
# Other than that it's a vanilla Depth-First Search (DFS).
@logger.info("Checking whether package '#{package.desc}' needs to be compiled for stemcell '#{stemcell.desc}'")
requirement_key = [package.id, "#{stemcell.os}/#{stemcell.version}"]
requirement = requirements[requirement_key]
if requirement # We already visited this and its dependencies
requirement.add_instance_group(instance_group) # But we still need to register with this instance group
return requirement
end
package_dependency_manager = PackageDependenciesManager.new(job.release.model)
requirement = create_requirement(instance_group, job, package, stemcell, package_dependency_manager)
@logger.info("Processing package '#{package.desc}' dependencies")
dependencies = package_dependency_manager.dependencies(package)
dependencies.each do |dependency|
@logger.info("Package '#{package.desc}' depends on package '#{dependency.desc}'")
dependency_requirement = generate!(requirements, instance_group, job, dependency, stemcell)
requirement.add_dependency(dependency_requirement)
end
requirements[requirement_key] = requirement
requirement
end | ruby | {
"resource": ""
} |
q11151 | Bosh::Director.DeploymentPlan::Assembler.bind_jobs | train | def bind_jobs
@deployment_plan.releases.each do |release|
release.bind_jobs
end
@deployment_plan.instance_groups.each(&:validate_package_names_do_not_collide!)
@deployment_plan.instance_groups.each(&:validate_exported_from_matches_stemcell!)
end | ruby | {
"resource": ""
} |
q11152 | ActiveRecordExtended.Utilities.double_quote | train | def double_quote(value)
return if value.nil?
case value.to_s
# Ignore keys that contain double quotes or a Arel.star (*)[all columns]
# or if a table has already been explicitly declared (ex: users.id)
when "*", /((^".+"$)|(^[[:alpha:]]+\.[[:alnum:]]+))/
value
else
PG::Connection.quote_ident(value.to_s)
end
end | ruby | {
"resource": ""
} |
q11153 | ActiveRecordExtended.Utilities.literal_key | train | def literal_key(key)
case key
when TrueClass then "'t'"
when FalseClass then "'f'"
when Numeric then key
else
key = key.to_s
key.start_with?("'") && key.end_with?("'") ? key : "'#{key}'"
end
end | ruby | {
"resource": ""
} |
q11154 | ActiveRecordExtended.Utilities.to_arel_sql | train | def to_arel_sql(value)
case value
when Arel::Node, Arel::Nodes::SqlLiteral, nil
value
when ActiveRecord::Relation
Arel.sql(value.spawn.to_sql)
else
Arel.sql(value.respond_to?(:to_sql) ? value.to_sql : value.to_s)
end
end | ruby | {
"resource": ""
} |
q11155 | ActiveRecordExtended.WhereChain.contains | train | def contains(opts, *rest)
build_where_chain(opts, rest) do |arel|
case arel
when Arel::Nodes::In, Arel::Nodes::Equality
column = left_column(arel) || column_from_association(arel)
if [:hstore, :jsonb].include?(column.type)
Arel::Nodes::ContainsHStore.new(arel.left, arel.right)
elsif column.try(:array)
Arel::Nodes::ContainsArray.new(arel.left, arel.right)
else
raise ArgumentError, "Invalid argument for .where.contains(), got #{arel.class}"
end
else
raise ArgumentError, "Invalid argument for .where.contains(), got #{arel.class}"
end
end
end | ruby | {
"resource": ""
} |
q11156 | JekyllAdmin.URLable.api_url | train | def api_url
@api_url ||= Addressable::URI.new(
:scheme => scheme, :host => host, :port => port,
:path => path_with_base("/_api", resource_path)
).normalize.to_s
end | ruby | {
"resource": ""
} |
q11157 | JekyllAdmin.APIable.to_api | train | def to_api(include_content: false)
output = hash_for_api
output = output.merge(url_fields)
# Include content, if requested, otherwise remove it
if include_content
output = output.merge(content_fields)
else
CONTENT_FIELDS.each { |field| output.delete(field) }
end
# Documents have duplicate output and content fields, Pages do not
# Since it's an API, use `content` in both for consistency
output.delete("output")
# By default, calling to_liquid on a collection will return a docs
# array with each rendered document, which we don't want.
if is_a?(Jekyll::Collection)
output.delete("docs")
output["entries_url"] = entries_url
end
if is_a?(Jekyll::Document)
output["relative_path"] = relative_path.sub("_drafts/", "") if draft?
output["name"] = basename
end
if is_a?(Jekyll::StaticFile)
output["from_theme"] = from_theme_gem?
end
output
end | ruby | {
"resource": ""
} |
q11158 | JekyllAdmin.APIable.content_fields | train | def content_fields
output = {}
# Include file content-related fields
if is_a?(Jekyll::StaticFile)
output["encoded_content"] = encoded_content
elsif is_a?(JekyllAdmin::DataFile)
output["content"] = content
output["raw_content"] = raw_content
else
output["raw_content"] = raw_content
output["front_matter"] = front_matter
end
# Include next and previous documents non-recursively
if is_a?(Jekyll::Document)
%w(next previous).each do |direction|
method = "#{direction}_doc".to_sym
doc = public_send(method)
output[direction] = doc.to_api if doc
end
end
output
end | ruby | {
"resource": ""
} |
q11159 | JekyllAdmin.PathHelper.directory_path | train | def directory_path
sanitized_path(
case namespace
when "collections"
File.join(collection.relative_directory, params["splat"].first)
when "data"
File.join(DataFile.data_dir, params["splat"].first)
when "drafts"
File.join("_drafts", params["splat"].first)
else
params["splat"].first
end
)
end | ruby | {
"resource": ""
} |
q11160 | JekyllAdmin.FileHelper.write_file | train | def write_file(path, content)
Jekyll.logger.debug "WRITING:", path
path = sanitized_path(path)
FileUtils.mkdir_p File.dirname(path)
File.open(path, "wb") do |file|
file.write(content)
end
# we should fully process in dev mode for tests to pass
if ENV["RACK_ENV"] == "production"
site.read
else
site.process
end
end | ruby | {
"resource": ""
} |
q11161 | JekyllAdmin.FileHelper.delete_file | train | def delete_file(path)
Jekyll.logger.debug "DELETING:", path
FileUtils.rm_f sanitized_path(path)
site.process
end | ruby | {
"resource": ""
} |
q11162 | JekyllAdmin.Server.restored_front_matter | train | def restored_front_matter
front_matter.map do |key, value|
value = "null" if value.nil?
[key, value]
end.to_h
end | ruby | {
"resource": ""
} |
q11163 | SCSSLint.Linter::SingleLinePerProperty.single_line_rule_set? | train | def single_line_rule_set?(rule)
rule.children.all? { |child| child.line == rule.source_range.end_pos.line }
end | ruby | {
"resource": ""
} |
q11164 | SCSSLint.Linter::SingleLinePerProperty.check_adjacent_properties | train | def check_adjacent_properties(properties)
properties[0..-2].zip(properties[1..-1]).each do |first, second|
next unless first.line == second.line
add_lint(second, "Property '#{second.name.join}' should be placed on own line")
end
end | ruby | {
"resource": ""
} |
q11165 | SCSSLint.ControlCommentProcessor.before_node_visit | train | def before_node_visit(node)
return unless (commands = Array(extract_commands(node))).any?
commands.each do |command|
linters = command[:linters]
next unless linters.include?('all') || linters.include?(@linter.name)
process_command(command, node)
# Is the control comment the only thing on this line?
next if node.is_a?(Sass::Tree::RuleNode) ||
%r{^\s*(//|/\*)}.match(@linter.engine.lines[command[:line] - 1])
# Otherwise, pop since we only want comment to apply to the single line
pop_control_comment_stack(node)
end
end | ruby | {
"resource": ""
} |
q11166 | SCSSLint.ControlCommentProcessor.last_child | train | def last_child(node)
last = node.children.inject(node) do |lowest, child|
return lowest unless child.respond_to?(:line)
lowest.line < child.line ? child : lowest
end
# In this case, none of the children have associated line numbers or the
# node has no children at all, so return `nil`.
return if last == node
last
end | ruby | {
"resource": ""
} |
q11167 | SCSSLint.Linter::QualifyingElement.seq_contains_sel_class? | train | def seq_contains_sel_class?(seq, selector_class)
seq.members.any? do |simple|
simple.is_a?(selector_class)
end
end | ruby | {
"resource": ""
} |
q11168 | SCSSLint.Linter::SelectorDepth.max_sequence_depth | train | def max_sequence_depth(comma_sequence, current_depth)
# Sequence contains interpolation; assume a depth of 1
return current_depth + 1 unless comma_sequence
comma_sequence.members.map { |sequence| sequence_depth(sequence, current_depth) }.max
end | ruby | {
"resource": ""
} |
q11169 | SCSSLint.Linter::Indentation.check_root_ruleset_indent | train | def check_root_ruleset_indent(node, actual_indent)
# Whether node is a ruleset not nested within any other ruleset.
if @indent == 0 && node.is_a?(Sass::Tree::RuleNode)
unless actual_indent % @indent_width == 0
add_lint(node.line, lint_message("a multiple of #{@indent_width}", actual_indent))
return true
end
end
false
end | ruby | {
"resource": ""
} |
q11170 | SCSSLint.Linter::Indentation.one_shift_greater_than_parent? | train | def one_shift_greater_than_parent?(node, actual_indent)
parent_indent = node_indent(node_indent_parent(node)).length
expected_indent = parent_indent + @indent_width
expected_indent == actual_indent
end | ruby | {
"resource": ""
} |
q11171 | SCSSLint.Linter::SpaceBetweenParens.feel_for_enclosing_parens | train | def feel_for_enclosing_parens(node) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
range = node.source_range
original_source = source_from_range(range)
left_offset = -1
right_offset = 0
if original_source[-1] != ')'
right_offset += 1 while character_at(range.end_pos, right_offset) =~ /\s/
return original_source if character_at(range.end_pos, right_offset) != ')'
end
# At this point, we know that we're wrapped on the right by a ')'.
# Are we wrapped on the left by a '('?
left_offset -= 1 while character_at(range.start_pos, left_offset) =~ /\s/
return original_source if character_at(range.start_pos, left_offset) != '('
# At this point, we know we're wrapped on both sides by parens. However,
# those parens may be part of a parent function call. We don't care about
# such parens. This depends on whether the preceding character is part of
# a function name.
return original_source if character_at(range.start_pos, left_offset - 1).match?(/[A-Za-z0-9_]/)
range.start_pos.offset += left_offset
range.end_pos.offset += right_offset
source_from_range(range)
end | ruby | {
"resource": ""
} |
q11172 | SCSSLint.Linter::EmptyLineBetweenBlocks.check_preceding_node | train | def check_preceding_node(node, type)
case prev_node(node)
when
nil,
Sass::Tree::FunctionNode,
Sass::Tree::MixinNode,
Sass::Tree::MixinDefNode,
Sass::Tree::RuleNode,
Sass::Tree::CommentNode
# Ignore
nil
else
unless engine.lines[node.line - 2].strip.empty?
add_lint(node.line, MESSAGE_FORMAT % [type, 'preceded'])
end
end
end | ruby | {
"resource": ""
} |
q11173 | SCSSLint.Linter::SpaceAfterPropertyColon.value_offset | train | def value_offset(prop)
src_range = prop.name_source_range
src_range.start_pos.offset +
(src_range.end_pos.offset - src_range.start_pos.offset) +
whitespace_after_colon(prop).take_while { |w| w == ' ' }.size
end | ruby | {
"resource": ""
} |
q11174 | SCSSLint.RakeTask.default_description | train | def default_description
description = 'Run `scss-lint'
description += " --config #{config}" if config
description += " #{args}" if args
description += " #{files.join(' ')}" if files.any?
description += ' [files...]`'
description
end | ruby | {
"resource": ""
} |
q11175 | SCSSLint.CLI.run | train | def run(args)
options = SCSSLint::Options.new.parse(args)
act_on_options(options)
rescue StandardError => e
handle_runtime_exception(e, options)
end | ruby | {
"resource": ""
} |
q11176 | SCSSLint.CLI.relevant_configuration_file | train | def relevant_configuration_file(options)
if options[:config_file]
options[:config_file]
elsif File.exist?(Config::FILE_NAME)
Config::FILE_NAME
elsif File.exist?(Config.user_file)
Config.user_file
end
end | ruby | {
"resource": ""
} |
q11177 | Sass::Tree.Node.add_line_number | train | def add_line_number(node)
node.line ||= line if node.is_a?(::Sass::Script::Tree::Node)
node
end | ruby | {
"resource": ""
} |
q11178 | SCSSLint.Linter.run | train | def run(engine, config)
@lints = []
@config = config
@engine = engine
@comment_processor = ControlCommentProcessor.new(self)
visit(engine.tree)
@lints = @comment_processor.filter_lints(@lints)
end | ruby | {
"resource": ""
} |
q11179 | SCSSLint.Linter.add_lint | train | def add_lint(node_or_line_or_location, message)
@lints << Lint.new(self,
engine.filename,
extract_location(node_or_line_or_location),
message,
@config.fetch('severity', :warning).to_sym)
end | ruby | {
"resource": ""
} |
q11180 | SCSSLint.Linter.source_from_range | train | def source_from_range(source_range) # rubocop:disable Metrics/AbcSize
current_line = source_range.start_pos.line - 1
last_line = source_range.end_pos.line - 1
start_pos = source_range.start_pos.offset - 1
source =
if current_line == last_line
engine.lines[current_line][start_pos..(source_range.end_pos.offset - 1)]
else
engine.lines[current_line][start_pos..-1]
end
current_line += 1
while current_line < last_line
source += engine.lines[current_line].to_s
current_line += 1
end
if source_range.start_pos.line != source_range.end_pos.line
source += ((engine.lines[current_line] || '')[0...source_range.end_pos.offset]).to_s
end
source
end | ruby | {
"resource": ""
} |
q11181 | SCSSLint.Linter.node_on_single_line? | train | def node_on_single_line?(node)
return if node.source_range.start_pos.line != node.source_range.end_pos.line
# The Sass parser reports an incorrect source range if the trailing curly
# brace is on the next line, e.g.
#
# p {
# }
#
# Since we don't want to count this as a single line node, check if the
# last character on the first line is an opening curly brace.
engine.lines[node.line - 1].strip[-1] != '{'
end | ruby | {
"resource": ""
} |
q11182 | SCSSLint.Linter.visit | train | def visit(node)
# Visit the selector of a rule if parsed rules are available
if node.is_a?(Sass::Tree::RuleNode) && node.parsed_rules
visit_selector(node.parsed_rules)
end
@comment_processor.before_node_visit(node) if @engine.any_control_commands
super
@comment_processor.after_node_visit(node) if @engine.any_control_commands
end | ruby | {
"resource": ""
} |
q11183 | SCSSLint.Linter.visit_children | train | def visit_children(parent)
parent.children.each do |child|
child.node_parent = parent
visit(child)
end
end | ruby | {
"resource": ""
} |
q11184 | SCSSLint.Linter::SpaceAfterComma.sort_args_by_position | train | def sort_args_by_position(*args)
args.flatten.compact.sort_by do |arg|
pos = arg.source_range.end_pos
[pos.line, pos.offset]
end
end | ruby | {
"resource": ""
} |
q11185 | SCSSLint.Linter::SpaceAfterComma.find_comma_position | train | def find_comma_position(arg) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
offset = 0
pos = arg.source_range.end_pos
if character_at(pos, offset) != ','
loop do
offset += 1
break if (right_char = character_at(pos, offset)) == ','
offset = -offset
break if (left_char = character_at(pos, offset)) == ','
offset = -offset
next unless right_char.nil? && left_char.nil?
offset = 0
pos = Sass::Source::Position.new(pos.line + 1, 1)
break if character_at(pos, offset) == ','
end
end
Sass::Source::Position.new(pos.line, pos.offset + offset)
end | ruby | {
"resource": ""
} |
q11186 | SCSSLint.Runner.run_linter | train | def run_linter(linter, engine, file_path)
return if @config.excluded_file_for_linter?(file_path, linter)
@lints += linter.run(engine, @config.linter_options(linter))
end | ruby | {
"resource": ""
} |
q11187 | SCSSLint.Linter::DuplicateProperty.property_key | train | def property_key(prop)
prop_key = prop.name.join
prop_value = value_as_string(prop.value.first)
# Differentiate between values for different vendor prefixes
prop_value.to_s.scan(/^(-[^-]+-.+)/) do |vendor_keyword|
prop_key << vendor_keyword.first
end
prop_key
end | ruby | {
"resource": ""
} |
q11188 | SCSSLint.Linter::SpaceBeforeBrace.newline_before_nonwhitespace | train | def newline_before_nonwhitespace(string)
offset = -2
while /\S/.match(string[offset]).nil?
return true if string[offset] == "\n"
offset -= 1
end
false
end | ruby | {
"resource": ""
} |
q11189 | SCSSLint.Linter::SingleLinePerSelector.check_multiline_sequence | train | def check_multiline_sequence(node, sequence, index)
return unless sequence.members.size > 1
return unless sequence.members[2..-1].any? { |member| member == "\n" }
add_lint(node.line + index, MESSAGE)
end | ruby | {
"resource": ""
} |
q11190 | SCSSLint.Linter::PropertyUnits.check_units | train | def check_units(node, property, units)
allowed_units = allowed_units_for_property(property)
return if allowed_units.include?(units)
add_lint(node,
"#{units} units not allowed on `#{property}`; must be one of " \
"(#{allowed_units.to_a.sort.join(', ')})")
end | ruby | {
"resource": ""
} |
q11191 | SCSSLint.Linter::DeclarationOrder.check_children_order | train | def check_children_order(sorted_children, children)
sorted_children.each_with_index do |sorted_item, index|
next if sorted_item == children[index]
add_lint(sorted_item.first.line,
"Expected item on line #{sorted_item.first.line} to appear " \
"before line #{children[index].first.line}. #{MESSAGE}")
break
end
end | ruby | {
"resource": ""
} |
q11192 | SCSSLint.Utils.node_ancestor | train | def node_ancestor(node, levels)
while levels > 0
node = node.node_parent
return unless node
levels -= 1
end
node
end | ruby | {
"resource": ""
} |
q11193 | SCSSLint.Linter::PropertySortOrder.ignore_property? | train | def ignore_property?(prop_node)
return true if prop_node.name.any? { |part| !part.is_a?(String) }
config['ignore_unspecified'] &&
@preferred_order &&
!@preferred_order.include?(prop_node.name.join)
end | ruby | {
"resource": ""
} |
q11194 | CanCan.ConditionsMatcher.matches_conditions? | train | def matches_conditions?(action, subject, attribute = nil, *extra_args)
return call_block_with_all(action, subject, extra_args) if @match_all
return matches_block_conditions(subject, attribute, *extra_args) if @block
return matches_non_block_conditions(subject) unless conditions_empty?
true
end | ruby | {
"resource": ""
} |
q11195 | CanCan.Ability.can? | train | def can?(action, subject, attribute = nil, *extra_args)
match = extract_subjects(subject).lazy.map do |a_subject|
relevant_rules_for_match(action, a_subject).detect do |rule|
rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute)
end
end.reject(&:nil?).first
match ? match.base_behavior : false
end | ruby | {
"resource": ""
} |
q11196 | CanCan.Ability.can | train | def can(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block))
end | ruby | {
"resource": ""
} |
q11197 | CanCan.Ability.cannot | train | def cannot(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(false, action, subject, *attributes_and_conditions, &block))
end | ruby | {
"resource": ""
} |
q11198 | CanCan.Ability.validate_target | train | def validate_target(target)
error_message = "You can't specify target (#{target}) as alias because it is real action name"
raise Error, error_message if aliased_actions.values.flatten.include? target
end | ruby | {
"resource": ""
} |
q11199 | Backup.Archive.perform! | train | def perform!
Logger.info "Creating Archive '#{name}'..."
path = File.join(Config.tmp_path, @model.trigger, "archives")
FileUtils.mkdir_p(path)
pipeline = Pipeline.new
with_files_from(paths_to_package) do |files_from|
pipeline.add(
"#{tar_command} #{tar_options} -cPf -#{tar_root} " \
"#{paths_to_exclude} #{files_from}",
tar_success_codes
)
extension = "tar"
if @model.compressor
@model.compressor.compress_with do |command, ext|
pipeline << command
extension << ext
end
end
pipeline << "#{utility(:cat)} > " \
"'#{File.join(path, "#{name}.#{extension}")}'"
pipeline.run
end
if pipeline.success?
Logger.info "Archive '#{name}' Complete!"
else
raise Error, "Failed to Create Archive '#{name}'\n" +
pipeline.error_messages
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.