_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3500
|
Dataflow.Port.send
|
train
|
def send value
LOCK.synchronize do
unify @end.head, value
unify @end.tail, Stream.new
@end = @end.tail
end
end
|
ruby
|
{
"resource": ""
}
|
q3501
|
Weibo.Request.make_mash_with_consistent_hash
|
train
|
def make_mash_with_consistent_hash(obj)
m = Hashie::Mash.new(obj)
def m.hash
inspect.hash
end
return m
end
|
ruby
|
{
"resource": ""
}
|
q3502
|
Ronin.Wordlist.each_word
|
train
|
def each_word(&block)
return enum_for(__method__) unless block
if @path
File.open(@path) do |file|
file.each_line do |line|
yield line.chomp
end
end
elsif @words
@words.each(&block)
end
end
|
ruby
|
{
"resource": ""
}
|
q3503
|
Ronin.Wordlist.each
|
train
|
def each(&block)
return enum_for(__method__) unless block
mutator = unless @mutations.empty?
Fuzzing::Mutator.new(@mutations)
end
each_word do |word|
yield word
if mutator
# perform additional mutations
mutator.each(word,&block)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3504
|
Ronin.Wordlist.save
|
train
|
def save(path)
File.open(path,'w') do |file|
each { |word| file.puts word }
end
return self
end
|
ruby
|
{
"resource": ""
}
|
q3505
|
StripeSaas.SubscriptionsController.load_owner
|
train
|
def load_owner
unless params[:owner_id].nil?
if current_owner.present?
# we need to try and look this owner up via the find method so that we're
# taking advantage of any override of the find method that would be provided
# by older versions of friendly_id. (support for newer versions default behavior
# below.)
searched_owner = current_owner.class.find(params[:owner_id]) rescue nil
# if we couldn't find them that way, check whether there is a new version of
# friendly_id in place that we can use to look them up by their slug.
# in christoph's words, "why?!" in my words, "warum?!!!"
# (we debugged this together on skype.)
if searched_owner.nil? && current_owner.class.respond_to?(:friendly)
searched_owner = current_owner.class.friendly.find(params[:owner_id]) rescue nil
end
if current_owner.try(:id) == searched_owner.try(:id)
@owner = current_owner
else
customer = Subscription.find_customer(searched_owner)
customer_2 = Subscription.find_customer(current_owner)
# susbscription we are looking for belongs to the same user but to a different
# subscription owner
# e.g. user -> account -> subscription
# same user but different accounts for example
if customer_2.try(:id) == customer.try(:id)
@owner = searched_owner
else
return unauthorized
end
end
else
return unauthorized
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3506
|
Librevox.Commands.originate
|
train
|
def originate url, args={}, &block
extension = args.delete(:extension)
dialplan = args.delete(:dialplan)
context = args.delete(:context)
vars = args.map {|k,v| "#{k}=#{v}"}.join(",")
arg_string = "{#{vars}}" +
[url, extension, dialplan, context].compact.join(" ")
command "originate", arg_string, &block
end
|
ruby
|
{
"resource": ""
}
|
q3507
|
CodeAnalyzer.Checker.add_warning
|
train
|
def add_warning(message, filename = @node.file, line_number = @node.line_number)
warnings << Warning.new(filename: filename, line_number: line_number, message: message)
end
|
ruby
|
{
"resource": ""
}
|
q3508
|
Morpher.TypeLookup.call
|
train
|
def call(object)
current = target = object.class
while current != Object
if registry.key?(current)
return registry.fetch(current)
end
current = current.superclass
end
fail TypeNotFoundError, target
end
|
ruby
|
{
"resource": ""
}
|
q3509
|
Hashie.Mash.rubyify_keys!
|
train
|
def rubyify_keys!
keys.each{|k|
v = delete(k)
new_key = k.to_s.underscore
self[new_key] = v
v.rubyify_keys! if v.is_a?(Hash)
v.each{|p| p.rubyify_keys! if p.is_a?(Hash)} if v.is_a?(Array)
}
self
end
|
ruby
|
{
"resource": ""
}
|
q3510
|
Bpl.CostModeling.get_annotation_value
|
train
|
def get_annotation_value annotationStmt
raise "annotation should have one argument" unless annotationStmt.arguments.length == 1
return annotationStmt.arguments.first.to_s
end
|
ruby
|
{
"resource": ""
}
|
q3511
|
Bpl.CostModeling.cost_of
|
train
|
def cost_of block
assumes = block.select{ |s| s.is_a?(AssumeStatement)}
cost = assumes.inject(0) do |acc, stmt|
if values = stmt.get_attribute(:'smack.InstTimingCost.Int64')
acc += values.first.show.to_i
end
acc
end
return cost
end
|
ruby
|
{
"resource": ""
}
|
q3512
|
Bpl.CostModeling.extract_branches
|
train
|
def extract_branches blocks
branches = []
blocks.each do |block|
block.each do |stmt|
case stmt
when GotoStatement
next if stmt.identifiers.length < 2
unless stmt.identifiers.length == 2
fail "Unexpected goto statement: #{stmt}"
end
if annotation = stmt.previous_sibling
fail "Expected :branchcond annotation" unless
annotation.has_attribute?(:branchcond)
end
branches.push(stmt)
end
end
end
return branches
end
|
ruby
|
{
"resource": ""
}
|
q3513
|
WLAPI.API.wordforms
|
train
|
def wordforms(word, limit = 10)
check_params(word, limit)
# note, it is the only service which requires 'Word', not 'Wort'
arg1 = ['Word', word]
arg2 = ['Limit', limit]
answer = query(@cl_Wordforms, arg1, arg2)
get_answer(answer)
end
|
ruby
|
{
"resource": ""
}
|
q3514
|
WLAPI.API.right_collocation_finder
|
train
|
def right_collocation_finder(word, pos, limit = 10)
check_params(word, pos, limit)
arg1 = ['Wort', word]
arg2 = ['Wortart', pos]
arg3 = ['Limit', limit]
answer = query(@cl_RightCollocationFinder, arg1, arg2, arg3)
get_answer(answer)
end
|
ruby
|
{
"resource": ""
}
|
q3515
|
WLAPI.API.cooccurrences
|
train
|
def cooccurrences(word, sign, limit = 10)
check_params(word, sign, limit)
arg1 = ['Wort', word]
arg2 = ['Mindestsignifikanz', sign]
arg3 = ['Limit', limit]
answer = query(@cl_Cooccurrences, arg1, arg2, arg3)
get_answer(answer)
end
|
ruby
|
{
"resource": ""
}
|
q3516
|
WLAPI.API.get_answer
|
train
|
def get_answer(doc, mod='')
result = []
# The path seems to be weird, because the namespaces change incrementally
# in the output, so I don't want to treat it here.
# A modifier needed because synonyms service provides duplicate values.
XPath.each(doc, "//result/*/*#{mod}") do |el|
warn(el.text) if $DEBUG
result << el.text
end
result.any? ? result : nil
end
|
ruby
|
{
"resource": ""
}
|
q3517
|
Ons.Producer.send_message
|
train
|
def send_message(topic, tag, body, key = '')
@producer.send_message(topic, tag, body, key)
end
|
ruby
|
{
"resource": ""
}
|
q3518
|
Ons.Producer.send_timer_message
|
train
|
def send_timer_message(topic, tag, body, timer, key = '')
@producer.send_timer_message(topic, tag, body, timer.to_i * 1000, key)
end
|
ruby
|
{
"resource": ""
}
|
q3519
|
MPV.Client.distribute_results!
|
train
|
def distribute_results!
response = JSON.parse(@socket.readline)
if response["event"]
@event_queue << response
else
@result_queue << response
end
rescue StandardError
@alive = false
Thread.exit
end
|
ruby
|
{
"resource": ""
}
|
q3520
|
MPV.Client.dispatch_events!
|
train
|
def dispatch_events!
loop do
event = @event_queue.pop
callbacks.each do |callback|
Thread.new do
callback.call event
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3521
|
Beaker.GoogleCompute.find_google_ssh_public_key
|
train
|
def find_google_ssh_public_key
keyfile = ENV.fetch('BEAKER_gce_ssh_public_key', File.join(ENV['HOME'], '.ssh', 'google_compute_engine.pub'))
if @options[:gce_ssh_public_key] && !File.exist?(keyfile)
keyfile = @options[:gce_ssh_public_key]
end
raise("Could not find GCE Public SSH Key at '#{keyfile}'") unless File.exist?(keyfile)
return keyfile
end
|
ruby
|
{
"resource": ""
}
|
q3522
|
Beaker.GoogleCompute.provision
|
train
|
def provision
attempts = @options[:timeout].to_i / SLEEPWAIT
start = Time.now
test_group_identifier = "beaker-#{start.to_i}-"
# get machineType resource, used by all instances
machineType = @gce_helper.get_machineType(start, attempts)
# set firewall to open pe ports
network = @gce_helper.get_network(start, attempts)
@firewall = test_group_identifier + generate_host_name
@gce_helper.create_firewall(@firewall, network, start, attempts)
@logger.debug("Created Google Compute firewall #{@firewall}")
@hosts.each do |host|
if host[:image]
gplatform = host[:image]
elsif host[:platform]
gplatform = Platform.new(host[:platform])
else
raise('You must specify either :image or :platform, or both as necessary')
end
img = @gce_helper.get_latest_image(gplatform, start, attempts)
unique_host_id = test_group_identifier + generate_host_name
host['diskname'] = unique_host_id
disk = @gce_helper.create_disk(host['diskname'], img, start, attempts)
@logger.debug("Created Google Compute disk for #{host.name}: #{host['diskname']}")
# create new host name
host['vmhostname'] = unique_host_id
#add a new instance of the image
instance = @gce_helper.create_instance(host['vmhostname'], img, machineType, disk, start, attempts)
@logger.debug("Created Google Compute instance for #{host.name}: #{host['vmhostname']}")
# add metadata to instance, if there is any to set
mdata = format_metadata
unless mdata.empty?
@gce_helper.setMetadata_on_instance(host['vmhostname'], instance['metadata']['fingerprint'],
mdata,
start, attempts)
@logger.debug("Added tags to Google Compute instance #{host.name}: #{host['vmhostname']}")
end
# get ip for this host
host['ip'] = instance['networkInterfaces'][0]['accessConfigs'][0]['natIP']
# configure ssh
default_user = host['user']
host['user'] = 'google_compute'
copy_ssh_to_root(host, @options)
enable_root_login(host, @options)
host['user'] = default_user
# shut down connection, will reconnect on next exec
host.close
@logger.debug("Instance ready: #{host['vmhostname']} for #{host.name}}")
end
end
|
ruby
|
{
"resource": ""
}
|
q3523
|
Beaker.GoogleCompute.cleanup
|
train
|
def cleanup()
attempts = @options[:timeout].to_i / SLEEPWAIT
start = Time.now
@gce_helper.delete_firewall(@firewall, start, attempts)
@hosts.each do |host|
@gce_helper.delete_instance(host['vmhostname'], start, attempts)
@logger.debug("Deleted Google Compute instance #{host['vmhostname']} for #{host.name}")
@gce_helper.delete_disk(host['diskname'], start, attempts)
@logger.debug("Deleted Google Compute disk #{host['diskname']} for #{host.name}")
end
end
|
ruby
|
{
"resource": ""
}
|
q3524
|
CountryCodeSelect.InstanceTag.country_code_select
|
train
|
def country_code_select(priority_countries, options)
selected = object.send(@method_name)
countries = ""
if priority_countries
countries += options_for_select(priority_countries, selected)
countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
elsif options[:include_blank]
countries += "<option value=\"\">" + options[:include_blank] + "</options>\n"
countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
end
countries = countries + options_for_select(COUNTRIES, selected)
content_tag(:select, countries, options.merge(id: "#{@object_name}_#{@method_name}", :name => "#{@object_name}[#{@method_name}]"), false)
end
|
ruby
|
{
"resource": ""
}
|
q3525
|
Unsakini.BoardsController.index
|
train
|
def index
admin = true
shared = false
admin = params[:is_admin] == 'true' if params[:admin]
shared = params[:shared] == 'true' if params[:shared]
result = @user.user_boards.shared(shared)
result = result.admin if admin
paginate json: result, per_page: 10
end
|
ruby
|
{
"resource": ""
}
|
q3526
|
Unsakini.BoardsController.create
|
train
|
def create
@user_board = UserBoard.new(
name: params[:board][:name],
user_id: @user.id,
encrypted_password: params[:encrypted_password],
is_admin: true
)
if @user_board.save
render json: @user_board, status: :created
else
render json: @user_board.errors.full_messages, status: 422
end
end
|
ruby
|
{
"resource": ""
}
|
q3527
|
Unsakini.BoardsController.update
|
train
|
def update
if @user_board.update(name: params[:board][:name], encrypted_password: params[:encrypted_password])
render json: @user_board
else
errors = @board.errors.full_messages.concat @user_board.errors.full_messages
render json: errors, status: 422
end
end
|
ruby
|
{
"resource": ""
}
|
q3528
|
Biffbot.Base.generate_url
|
train
|
def generate_url url, token, type, version
case type
when 'analyze'
url = "http://api.diffbot.com/v3/#{type}?token=#{token}&url=#{url}"
when 'custom'
url = "http://api.diffbot.com/v3/#{options[:api_name]}?token=#{token}&url=#{url}"
when 'article', 'image', 'product'
url = "http://api.diffbot.com/v2/#{type}?token=#{token}&url=#{url}"
url = "http://api.diffbot.com/#{version}/#{type}?token=#{token}&url=#{url}" if version == 'v2' || version == 'v3'
end
url
end
|
ruby
|
{
"resource": ""
}
|
q3529
|
Biffbot.Base.parse_options
|
train
|
def parse_options options = {}, request = ''
options.each do |opt, value|
case opt
when :timeout, :paging, :mode
request += "&#{opt}=#{value}"
when :callback, :stats
request += "&#{opt}"
when :fields
request += "&#{opt}=" + value.join(',') if value.is_a?(Array)
end
end
request
end
|
ruby
|
{
"resource": ""
}
|
q3530
|
Colorable.Color.info
|
train
|
def info
{
name: name,
rgb: rgb,
hsb: hsb,
hex: hex,
mode: mode,
dark: dark?
}
end
|
ruby
|
{
"resource": ""
}
|
q3531
|
Colorable.Color.next
|
train
|
def next(n=1)
@@colorset[mode] ||= Colorable::Colorset.new(order: mode)
idx = @@colorset[mode].find_index(self)
@@colorset[mode].at(idx+n).tap{|c| c.mode = mode } if idx
end
|
ruby
|
{
"resource": ""
}
|
q3532
|
CodeAnalyzer::CheckingVisitor.Plain.check
|
train
|
def check(filename, content)
@checkers.each do |checker|
checker.check(filename, content) if checker.parse_file?(filename)
end
end
|
ruby
|
{
"resource": ""
}
|
q3533
|
Unsakini.PostOwnerControllerConcern.ensure_post
|
train
|
def ensure_post
post_id = params[:post_id] || params[:id]
board_id = params[:board_id]
result = has_post_access(board_id, post_id)
status = result[:status]
@post = result[:post]
head status if status != :ok
end
|
ruby
|
{
"resource": ""
}
|
q3534
|
Unsakini.PostOwnerControllerConcern.has_post_access
|
train
|
def has_post_access(board_id, post_id)
post = Unsakini::Post.where(id: post_id, board_id: board_id)
.joins("LEFT JOIN #{UserBoard.table_name} ON #{UserBoard.table_name}.board_id = #{Post.table_name}.board_id")
.where("#{UserBoard.table_name}.user_id = ?", @user.id)
.first
if post.nil?
return {status: :forbidden}
else
return {status: :ok, post: post}
end
end
|
ruby
|
{
"resource": ""
}
|
q3535
|
Maximus.Stylestats.compile_scss
|
train
|
def compile_scss
puts "\nCompiling assets for stylestats...".color(:blue)
if is_rails?
# Get rake tasks
Rails.application.load_tasks unless @config.is_dev?
compile_scss_rails
else
load_compass
compile_scss
end
end
|
ruby
|
{
"resource": ""
}
|
q3536
|
Maximus.Stylestats.load_compass
|
train
|
def load_compass
if Gem::Specification::find_all_by_name('compass').any?
require 'compass'
Compass.sass_engine_options[:load_paths].each do |path|
Sass.load_paths << path
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3537
|
Maximus.Stylestats.load_scss_load_paths
|
train
|
def load_scss_load_paths
Dir.glob(@path).select { |d| File.directory? d}.each do |directory|
Sass.load_paths << directory
end
end
|
ruby
|
{
"resource": ""
}
|
q3538
|
Maximus.Stylestats.compile_scss_normal
|
train
|
def compile_scss_normal
Dir["#{@path}.scss"].select { |f| File.file? f }.each do |file|
next if File.basename(file).chr == '_'
scss_file = File.open(file, 'rb') { |f| f.read }
output_file = File.open( file.split('.').reverse.drop(1).reverse.join('.'), "w" )
output_file << Sass::Engine.new(scss_file, { syntax: :scss, quiet: true, style: :compressed }).render
output_file.close
end
end
|
ruby
|
{
"resource": ""
}
|
q3539
|
Maximus.Stylestats.find_css
|
train
|
def find_css(path = @path)
Dir.glob(path).select { |f| File.file? f }.map { |file| file }
end
|
ruby
|
{
"resource": ""
}
|
q3540
|
Unsakini.PostsController.create
|
train
|
def create
@post = Post.new(params.permit(:title, :content, :board_id))
@post.user = @user
if (@post.save)
render json: @post, status: :created
else
render json: @post.errors, status: 422
end
end
|
ruby
|
{
"resource": ""
}
|
q3541
|
Unsakini.EncryptableModelConcern.encrypt
|
train
|
def encrypt(value)
return value if is_empty_val(value)
c = cipher.encrypt
c.key = Digest::SHA256.digest(cipher_key)
c.iv = iv = c.random_iv
Base64.encode64(iv) + Base64.encode64(c.update(value.to_s) + c.final)
end
|
ruby
|
{
"resource": ""
}
|
q3542
|
Unsakini.EncryptableModelConcern.decrypt
|
train
|
def decrypt(value)
return value if is_empty_val(value)
c = cipher.decrypt
c.key = Digest::SHA256.digest(cipher_key)
c.iv = Base64.decode64 value.slice!(0,25)
c.update(Base64.decode64(value.to_s)) + c.final
end
|
ruby
|
{
"resource": ""
}
|
q3543
|
RipperPlus.Transformer.transform
|
train
|
def transform(root, opts={})
new_copy = opts[:in_place] ? root : clone_sexp(root)
scope_stack = ScopeStack.new
transform_tree(new_copy, scope_stack)
new_copy
end
|
ruby
|
{
"resource": ""
}
|
q3544
|
RipperPlus.Transformer.add_variables_from_node
|
train
|
def add_variables_from_node(lhs, scope_stack, allow_duplicates=true)
case lhs[0]
when :@ident
scope_stack.add_variable(lhs[1], allow_duplicates)
when :const_path_field, :@const, :top_const_field
if scope_stack.in_method?
raise DynamicConstantError.new
end
when Array
add_variable_list(lhs, scope_stack, allow_duplicates)
when :mlhs_paren, :var_field, :rest_param, :blockarg
add_variables_from_node(lhs[1], scope_stack, allow_duplicates)
when :mlhs_add_star
pre_star, star, post_star = lhs[1..3]
add_variable_list(pre_star, scope_stack, allow_duplicates)
if star
add_variables_from_node(star, scope_stack, allow_duplicates)
end
add_variable_list(post_star, scope_stack, allow_duplicates) if post_star
when :param_error
raise InvalidArgumentError.new
when :assign_error
raise LHSError.new
end
end
|
ruby
|
{
"resource": ""
}
|
q3545
|
RipperPlus.Transformer.transform_in_order
|
train
|
def transform_in_order(tree, scope_stack)
# some nodes have no type: include the first element in this case
range = Symbol === tree[0] ? 1..-1 : 0..-1
tree[range].each do |subtree|
# obviously don't transform literals or token locations
if Array === subtree && !(Fixnum === subtree[0])
transform_tree(subtree, scope_stack)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3546
|
RipperPlus.Transformer.transform_params
|
train
|
def transform_params(param_node, scope_stack)
param_node = param_node[1] if param_node[0] == :paren
if param_node
positional_1, optional, rest, positional_2, block = param_node[1..5]
add_variable_list(positional_1, scope_stack, false) if positional_1
if optional
optional.each do |var, value|
# MUST walk value first. (def foo(y=y); end) == (def foo(y=y()); end)
transform_tree(value, scope_stack)
add_variables_from_node(var, scope_stack, false)
end
end
if rest && rest[1]
add_variables_from_node(rest, scope_stack, false)
end
add_variable_list(positional_2, scope_stack, false) if positional_2
add_variables_from_node(block, scope_stack, false) if block
end
end
|
ruby
|
{
"resource": ""
}
|
q3547
|
Bumper.Version.bump_patch_tag
|
train
|
def bump_patch_tag tag
@v[:build] = '0' unless build.nil?
if patch_tag.nil?
@v[:patch] = patch.succ
return @v[:patch_tag] = tag
elsif patch_tag.start_with? tag
# ensure tag ends with number
if patch_tag !~ %r{\d+$}
@v[:patch_tag] = patch_tag + '1' # required for succ to work
end
# increment this tag
@v[:patch_tag] = patch_tag.succ
else
@v[:patch_tag] = tag # replace tag
end
end
|
ruby
|
{
"resource": ""
}
|
q3548
|
Morpher.Printer.visit
|
train
|
def visit(name)
child = object.public_send(name)
child_label(name)
visit_child(child)
end
|
ruby
|
{
"resource": ""
}
|
q3549
|
Morpher.Printer.visit_many
|
train
|
def visit_many(name)
children = object.public_send(name)
child_label(name)
children.each do |child|
visit_child(child)
end
end
|
ruby
|
{
"resource": ""
}
|
q3550
|
Morpher.Printer.indent
|
train
|
def indent(&block)
printer = new(object, output, indent_level.succ)
printer.instance_eval(&block)
end
|
ruby
|
{
"resource": ""
}
|
q3551
|
Ronin.Fuzzing.bad_strings
|
train
|
def bad_strings(&block)
yield ''
chars = [
'A', 'a', '1', '<', '>', '"', "'", '/', "\\", '?', '=', 'a=', '&',
'.', ',', '(', ')', ']', '[', '%', '*', '-', '+', '{', '}',
"\x14", "\xfe", "\xff"
]
chars.each do |c|
LONG_LENGTHS.each { |length| yield c * length }
end
yield '!@#$%%^#$%#$@#$%$$@#$%^^**(()'
yield '%01%02%03%04%0a%0d%0aADSF'
yield '%01%02%03@%04%0a%0d%0aADSF'
NULL_BYTES.each do |c|
SHORT_LENGTHS.each { |length| yield c * length }
end
yield "%\xfe\xf0%\x00\xff"
yield "%\xfe\xf0%\x00\xff" * 20
SHORT_LENGTHS.each do |length|
yield "\xde\xad\xbe\xef" * length
end
yield "\n\r" * 100
yield "<>" * 500
end
|
ruby
|
{
"resource": ""
}
|
q3552
|
Ronin.Fuzzing.bit_fields
|
train
|
def bit_fields(&block)
("\x00".."\xff").each do |c|
yield c
yield c << c # x2
yield c << c # x4
yield c << c # x8
end
end
|
ruby
|
{
"resource": ""
}
|
q3553
|
Ronin.Fuzzing.signed_bit_fields
|
train
|
def signed_bit_fields(&block)
("\x80".."\xff").each do |c|
yield c
yield c << c # x2
yield c << c # x4
yield c << c # x8
end
end
|
ruby
|
{
"resource": ""
}
|
q3554
|
Maximus.Phantomas.result
|
train
|
def result
return if @settings[:phantomas].blank?
node_module_exists('phantomjs', 'brew install')
node_module_exists('phantomas')
@path = @settings[:paths] if @path.blank?
@domain = @config.domain
# Phantomas doesn't actually skip the skip-modules defined in the config BUT here's to hoping for future support
phantomas_cli = "phantomas --config=#{@settings[:phantomas]} "
phantomas_cli += @config.is_dev? ? '--colors' : '--reporter=json:no-skip'
phantomas_cli << " --proxy=#{@domain}" if @domain.include?('localhost')
@path.is_a?(Hash) ? @path.each { |label, url| phantomas_by_url(url, phantomas_cli) } : phantomas_by_url(@path, phantomas_cli)
@output
end
|
ruby
|
{
"resource": ""
}
|
q3555
|
Snort.Rule.to_s
|
train
|
def to_s(options_only=false)
rule = ""
if @comments
rule += @comments
end
if not @enabled
rule += "#"
end
rule += [@action, @proto, @src, @sport, @dir, @dst, @dport].join(" ") unless options_only
if @options.any?
rule += " (" unless options_only
rule += @options.join(' ')
rule += ")" unless options_only
end
rule
end
|
ruby
|
{
"resource": ""
}
|
q3556
|
Maximus.Wraith.wraith_parse
|
train
|
def wraith_parse(browser)
Dir.glob("#{@config.working_dir}/maximus_wraith_#{browser}/**/*").select { |f| File.file? f }.each do |file|
extension = File.extname(file)
next unless extension == '.png' || extension == '.txt'
orig_label = File.dirname(file).split('/').last
path = @settings[:paths][orig_label].to_s
@output[:statistics][path] = {
browser: browser.to_s,
name: orig_label
} if @output[:statistics][path].blank?
browser_output = @output[:statistics][path]
if extension == '.txt'
browser_output = wraith_percentage(file, browser_output)
else
browser_output[:images] ||= []
browser_output[:images] << wraith_image(file)
end
end
@output
end
|
ruby
|
{
"resource": ""
}
|
q3557
|
Maximus.Wraith.wraith_percentage
|
train
|
def wraith_percentage(file, browser_output)
file_object = File.open(file, 'rb')
browser_output[:percent_changed] ||= {}
browser_output[:percent_changed][File.basename(file).split('_')[0].to_i] = file_object.read.to_f
file_object.close
browser_output
end
|
ruby
|
{
"resource": ""
}
|
q3558
|
Ons.Consumer.subscribe
|
train
|
def subscribe(topic, expression, handler = nil)
@consumer.subscribe(topic, expression, handler || Proc.new)
self
end
|
ruby
|
{
"resource": ""
}
|
q3559
|
WebkitRemote.Rpc.call
|
train
|
def call(method, params = nil)
request_id = @next_id
@next_id += 1
request = {
jsonrpc: '2.0',
id: request_id,
method: method,
}
request[:params] = params if params
request_json = JSON.dump request
@web_socket.send_frame request_json
loop do
result = receive_message request_id
return result if result
end
end
|
ruby
|
{
"resource": ""
}
|
q3560
|
WebkitRemote.Rpc.receive_message
|
train
|
def receive_message(expected_id)
json = @web_socket.recv_frame
begin
data = JSON.parse json
rescue JSONError
close
raise RuntimeError, 'Invalid JSON received'
end
if data['id']
# RPC result.
if data['id'] != expected_id
close
raise RuntimeError, 'Out of sequence RPC response id'
end
if data['error']
code = data['error']['code']
message = data['error']['message']
raise RuntimeError, "RPC Error #{code}: #{message}"
end
return data['result']
elsif data['method']
# RPC notice.
event = { name: data['method'], data: data['params'] }
@events << event
return nil
else
close
raise RuntimeError, "Unexpected / invalid RPC message #{data.inspect}"
end
end
|
ruby
|
{
"resource": ""
}
|
q3561
|
Impressbox.Command.selected_yaml_file
|
train
|
def selected_yaml_file
p = current_impressbox_provisioner
if p.nil? || p.config.nil? || p.config.file.nil? ||
!(p.config.file.is_a?(String) && p.config.file.chop.length > 0)
return 'config.yaml'
end
p.config.file
end
|
ruby
|
{
"resource": ""
}
|
q3562
|
Impressbox.Command.current_impressbox_provisioner
|
train
|
def current_impressbox_provisioner
@env.vagrantfile.config.vm.provisioners.each do |provisioner|
next unless provisioner.type == :impressbox
return provisioner
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q3563
|
Impressbox.Command.update_name
|
train
|
def update_name(options)
if options.key?(:name) && options[:name].is_a?(String) && options[:name].length > 0
return
end
hostname = if options.key?(:hostname) then
options[:hostname]
else
@args.default_values[:hostname]
end
hostname = hostname[0] if hostname.is_a?(Array)
options[:name] = hostname.gsub(/[^A-Za-z0-9_-]/, '-')
end
|
ruby
|
{
"resource": ""
}
|
q3564
|
Impressbox.Command.write_result_msg
|
train
|
def write_result_msg(result)
msg = if result then
I18n.t 'config.recreated'
else
I18n.t 'config.updated'
end
@env.ui.info msg
end
|
ruby
|
{
"resource": ""
}
|
q3565
|
Impressbox.Command.quick_make_file
|
train
|
def quick_make_file(local_file, tpl_file)
current_file = local_file(local_file)
template_file = @template.real_path(tpl_file)
@template.make_file(
template_file,
current_file,
@args.all.dup,
make_data_files_array(current_file),
method(:update_latest_options)
)
end
|
ruby
|
{
"resource": ""
}
|
q3566
|
Impressbox.Command.make_data_files_array
|
train
|
def make_data_files_array(current_file)
data_files = [
ConfigData.real_path('default.yml')
]
unless use_template_filename.nil?
data_files.push use_template_filename
end
unless must_recreate
data_files.push current_file
end
data_files
end
|
ruby
|
{
"resource": ""
}
|
q3567
|
PlaidRails.AccountsController.new
|
train
|
def new
client = Plaid::Client.new(env: PlaidRails.env,
client_id: PlaidRails.client_id,
secret: PlaidRails.secret,
public_key: PlaidRails.public_key)
response = client.accounts.get(account_params["access_token"])
@plaid_accounts = response.accounts
end
|
ruby
|
{
"resource": ""
}
|
q3568
|
DHCPParser.Conf.subnets
|
train
|
def subnets
subnet = []
index = 0
while index < @datas.count
index += 1
subnet << DHCPParser::Conf.get_subnet(@datas["net#{index}"])
end
return subnet
end
|
ruby
|
{
"resource": ""
}
|
q3569
|
DHCPParser.Conf.netmasks
|
train
|
def netmasks
netmask = []
index = 0
while index < @datas.count
index += 1
netmask << DHCPParser::Conf.get_netmask(@datas["net#{index}"])
end
return netmask
end
|
ruby
|
{
"resource": ""
}
|
q3570
|
DHCPParser.Conf.options
|
train
|
def options
option = []
index = 0
while index < @datas.count
index += 1
option << DHCPParser::Conf.get_list_option(@datas["net#{index}"])
end
return option
end
|
ruby
|
{
"resource": ""
}
|
q3571
|
DHCPParser.Conf.authoritative
|
train
|
def authoritative
authori = []
index = 0
while index < @datas.count
index += 1
authori << DHCPParser::Conf.get_authoritative(@datas["net#{index}"])
end
return authori
end
|
ruby
|
{
"resource": ""
}
|
q3572
|
DHCPParser.Conf.net
|
train
|
def net
i = 0
while i < @datas.count
i += 1
new_net = Net.new
new_net.subnet = DHCPParser::Conf.get_subnet(@datas["net#{i}"])
new_net.netmask = DHCPParser::Conf.get_netmask(@datas["net#{i}"])
list_option = DHCPParser::Conf.get_list_option(@datas["net#{i}"], true)
new_net.option = list_option[0]
new_net.differ = list_option[1]
pool = DHCPParser::Conf.get_pool(@datas["net#{i}"])
new_net.pool["range"] = pool["range"]
new_net.pool["allow"] = pool["allow"]
new_net.pool["denny"] = pool["denny"]
# set host
index = 0
while index < pool["hosts"].count
index += 1
host_name = pool["hosts"]["host#{index}"]["host"]
ethernet = pool["hosts"]["host#{index}"]["hardware_ethernet"]
address = pool["hosts"]["host#{index}"]["fixed-address"]
host = Host.new(host_name, ethernet, address)
new_net.pool["hosts"] << host
end
@array_net << new_net
end
return @array_net
end
|
ruby
|
{
"resource": ""
}
|
q3573
|
RailsStuff.ResourcesController.resources_controller
|
train
|
def resources_controller(**options)
ResourcesController.inject(self, **options)
self.after_save_action = options[:after_save_action] || after_save_action
resource_belongs_to(*options[:belongs_to]) if options[:belongs_to]
if options[:source_relation]
protected define_method(:source_relation, &options[:source_relation])
end
end
|
ruby
|
{
"resource": ""
}
|
q3574
|
StravaApi.Segments.segments
|
train
|
def segments(name)
result = call("segments", "segments", {:name => name})
result["segments"].collect {|item| Segment.new(self, item)}
end
|
ruby
|
{
"resource": ""
}
|
q3575
|
Rack.Robustness.call
|
train
|
def call(env)
dup.call!(env)
rescue => ex
catch_all ? last_resort(ex) : raise(ex)
end
|
ruby
|
{
"resource": ""
}
|
q3576
|
OSRM.Configuration.ensure_cache_version
|
train
|
def ensure_cache_version
return unless cache
cache_version = cache[cache_key('version')]
minimum_version = '0.4.0'
if cache_version &&
Gem::Version.new(cache_version) < Gem::Version.new(minimum_version)
@data[:cache] = nil
raise "OSRM API error: Incompatible cache version #{cache_version}, " +
"expected #{minimum_version} or higher"
end
end
|
ruby
|
{
"resource": ""
}
|
q3577
|
Jobbr.Job.cap_runs!
|
train
|
def cap_runs!
runs_count = self.runs.count
if runs_count > max_run_per_job
runs.sort_by(:started_at, order: 'ALPHA ASC', limit: [0, runs_count - max_run_per_job]).each do |run|
if run.status == :failed || run.status == :success
run.delete
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3578
|
WebkitRemote.Browser.tabs
|
train
|
def tabs
http_response = @http.request Net::HTTP::Get.new('/json')
tabs = JSON.parse(http_response.body).map do |json_tab|
title = json_tab['title']
url = json_tab['url']
debug_url = json_tab['webSocketDebuggerUrl']
Tab.new self, debug_url, title: title, url: url
end
# HACK(pwnall): work around the nasty Google Hangouts integration
tabs.select do |tab|
tab.url != 'chrome-extension://nkeimhogjdpnpccoofpliimaahmaaome/background.html'
end
end
|
ruby
|
{
"resource": ""
}
|
q3579
|
StravaApi.Clubs.clubs
|
train
|
def clubs(name)
raise StravaApi::CommandError if name.blank?
name = name.strip
raise StravaApi::CommandError if name.empty?
result = call("clubs", "clubs", {:name => name})
result["clubs"].collect {|item| Club.new(self, item)}
end
|
ruby
|
{
"resource": ""
}
|
q3580
|
StravaApi.Clubs.club_members
|
train
|
def club_members(id)
result = call("clubs/#{id}/members", "members", {})
result["members"].collect {|item| Member.new(self, item)}
end
|
ruby
|
{
"resource": ""
}
|
q3581
|
RailsStuff.ParamsParser.parse
|
train
|
def parse(val, *args, &block)
parse_not_blank(val, *args, &block)
rescue => e # rubocop:disable Lint/RescueWithoutErrorClass
raise Error.new(e.message, val), nil, e.backtrace
end
|
ruby
|
{
"resource": ""
}
|
q3582
|
RailsStuff.ParamsParser.parse_array
|
train
|
def parse_array(array, *args, &block)
return unless array.is_a?(Array)
parse(array) { array.map { |val| parse_not_blank(val, *args, &block) } }
end
|
ruby
|
{
"resource": ""
}
|
q3583
|
DT.Instance.rails_logger
|
train
|
def rails_logger
if instance_variable_defined?(k = :@rails_logger)
instance_variable_get(k)
else
instance_variable_set(k, conf.rails && conf.rails.logger)
end
end
|
ruby
|
{
"resource": ""
}
|
q3584
|
RailsStuff.RequireNested.require_nested
|
train
|
def require_nested(dir = 0)
dir = caller_locations(dir + 1, 1)[0].path.sub(/\.rb$/, '') if dir.is_a?(Integer)
Dir["#{dir}/*.rb"].each { |file| require_dependency file }
end
|
ruby
|
{
"resource": ""
}
|
q3585
|
StravaApi.Rides.ride_efforts
|
train
|
def ride_efforts(id)
result = call("rides/#{id}/efforts", "efforts", {})
result["efforts"].collect {|effort| Effort.new(self, effort)}
end
|
ruby
|
{
"resource": ""
}
|
q3586
|
WADL.XMLRepresentation.each_by_param
|
train
|
def each_by_param(param_name)
REXML::XPath.each(self, lookup_param(param_name).path) { |e| yield e }
end
|
ruby
|
{
"resource": ""
}
|
q3587
|
WADL.Param.format
|
train
|
def format(value, name = nil, style = nil)
name ||= self.name
style ||= self.style
value = fixed if fixed
value ||= default if default
unless value
if required?
raise ArgumentError, %Q{No value provided for required param "#{name}"!}
else
return '' # No value provided and none required.
end
end
if value.respond_to?(:each) && !value.respond_to?(:to_str)
if repeating?
values = value
else
raise ArgumentError, %Q{Multiple values provided for single-value param "#{name}"}
end
else
values = [value]
end
# If the param lists acceptable values in option tags, make sure that
# all values are found in those tags.
if options && !options.empty?
values.each { |_value|
unless find_option(_value)
acceptable = options.map { |o| o.value }.join('", "')
raise ArgumentError, %Q{"#{_value}" is not among the acceptable parameter values ("#{acceptable}")}
end
}
end
if style == 'query' || parent.is_a?(RequestFormat) || (
parent.respond_to?(:is_form_representation?) && parent.is_form_representation?
)
values.map { |v| "#{uri_escape(name)}=#{uri_escape(v.to_s)}" }.join('&')
elsif style == 'matrix'
if type == 'xsd:boolean'
values.map { |v| ";#{name}" if v =~ BOOLEAN_RE }.compact.join
else
values.map { |v| ";#{uri_escape(name)}=#{uri_escape(v.to_s)}" if v }.compact.join
end
elsif style == 'header'
values.join(',')
else
# All other cases: plain text representation.
values.map { |v| uri_escape(v.to_s) }.join(',')
end
end
|
ruby
|
{
"resource": ""
}
|
q3588
|
PlaidRails.Account.delete_updated_token
|
train
|
def delete_updated_token
# change all matching tokens on update
accounts = PlaidRails::Account.where(access_token: my_token)
if accounts.size > 0
delete_connect
end
end
|
ruby
|
{
"resource": ""
}
|
q3589
|
PlaidRails.Account.delete_connect
|
train
|
def delete_connect
begin
Rails.logger.info "Deleting Plaid User with token #{token_last_8}"
client = Plaid::Client.new(env: PlaidRails.env,
client_id: PlaidRails.client_id,
secret: PlaidRails.secret,
public_key: PlaidRails.public_key)
client.item.remove(access_token)
Rails.logger.info "Deleted Plaid User with token #{token_last_8}"
rescue => e
message = "Unable to delete user with token #{token_last_8}"
Rails.logger.error "#{message}: #{e.message}"
end
end
|
ruby
|
{
"resource": ""
}
|
q3590
|
RailsStuff.TypesTracker.register_type
|
train
|
def register_type(*args)
if types_list.respond_to?(:add)
types_list.add self, *args
else
types_list << self
end
if types_tracker_base.respond_to?(:scope) &&
!types_tracker_base.respond_to?(model_name.element)
type_name = name
types_tracker_base.scope model_name.element, -> { where(type: type_name) }
end
end
|
ruby
|
{
"resource": ""
}
|
q3591
|
RailsStuff.RedisStorage.get
|
train
|
def get(id)
return unless id
with_redis { |redis| redis.get(redis_key_for(id)).try { |data| load(data) } }
end
|
ruby
|
{
"resource": ""
}
|
q3592
|
RailsStuff.RedisStorage.delete
|
train
|
def delete(id)
return true unless id
with_redis { |redis| redis.del(redis_key_for(id)) }
true
end
|
ruby
|
{
"resource": ""
}
|
q3593
|
Keepassx.Database.add_group
|
train
|
def add_group(opts)
raise ArgumentError, "Expected Hash or Keepassx::Group, got #{opts.class}" unless valid_group?(opts)
if opts.is_a?(Keepassx::Group)
# Assign parent group
parent = opts.parent
index = last_sibling_index(parent) + 1
@groups.insert(index, opts)
# Increment counter
header.groups_count += 1
# Return group
opts
elsif opts.is_a?(Hash)
opts = deep_copy(opts)
opts = build_group_options(opts)
# Create group
group = create_group(opts)
# Increment counter
header.groups_count += 1
# Return group
group
end
end
|
ruby
|
{
"resource": ""
}
|
q3594
|
Keepassx.Database.next_group_id
|
train
|
def next_group_id
if @groups.empty?
# Start each time from 1 to make sure groups get the same id's for the
# same input data
1
else
id = @groups.last.id
loop do
id += 1
break id if @groups.find { |g| g.id == id }.nil?
end
end
end
|
ruby
|
{
"resource": ""
}
|
q3595
|
Keepassx.Database.last_sibling_index
|
train
|
def last_sibling_index(parent)
return -1 if groups.empty?
if parent.nil?
parent_index = 0
sibling_level = 1
else
parent_index = groups.find_index(parent)
sibling_level = parent.level + 1
end
raise "Could not find group #{parent.name}" if parent_index.nil?
(parent_index..(header.groups_count - 1)).each do |i|
break i unless groups[i].level == sibling_level
end
end
|
ruby
|
{
"resource": ""
}
|
q3596
|
WADL.Resource.address
|
train
|
def address(working_address = nil)
working_address &&= working_address.deep_copy
working_address ||= if parent.respond_to?(:base)
address = Address.new
address.path_fragments << parent.base
address
else
parent.address.deep_copy
end
working_address.path_fragments << path.dup
# Install path, query, and header parameters in the Address. These
# may override existing parameters with the same names, but if
# you've got a WADL application that works that way, you should
# have bound parameters to values earlier.
new_path_fragments = []
embedded_param_names = Set.new(Address.embedded_param_names(path))
params.each { |param|
name = param.name
if embedded_param_names.include?(name)
working_address.path_params[name] = param
else
if param.style == 'query'
working_address.query_params[name] = param
elsif param.style == 'header'
working_address.header_params[name] = param
else
new_path_fragments << param
working_address.path_params[name] = param
end
end
}
working_address.path_fragments << new_path_fragments unless new_path_fragments.empty?
working_address
end
|
ruby
|
{
"resource": ""
}
|
q3597
|
WADL.RepresentationFormat.%
|
train
|
def %(values)
unless is_form_representation?
raise "wadl can't instantiate a representation of type #{mediaType}"
end
representation = []
params.each { |param|
name = param.name
if param.fixed
p_values = [param.fixed]
elsif p_values = values[name] || values[name.to_sym]
p_values = [p_values] if !param.repeating? || !p_values.respond_to?(:each) || p_values.respond_to?(:to_str)
else
raise ArgumentError, "Your proposed representation is missing a value for #{param.name}" if param.required?
end
p_values.each { |v| representation << "#{CGI.escape(name)}=#{CGI.escape(v.to_s)}" } if p_values
}
representation.join('&')
end
|
ruby
|
{
"resource": ""
}
|
q3598
|
RETS4R.Client.login
|
train
|
def login(username, password) #:yields: login_results
@request_struct.username = username
@request_struct.password = password
# We are required to set the Accept header to this by the RETS 1.5 specification.
set_header('Accept', '*/*')
response = request(@urls.login)
# Parse response to get other URLS
results = @response_parser.parse_key_value(response.body)
# TODO: fix test to like this
# results = ResponseDocument.safe_parse(response.body).validate!.parse_key_value
if (results.success?)
CAPABILITY_LIST.each do |capability|
next unless results.response[capability]
uri = URI.parse(results.response[capability])
if uri.absolute?
@urls[capability] = uri
else
base = @urls.login.clone
base.path = results.response[capability]
@urls[capability] = base
end
end
logger.debug("Capability URL List: #{@urls.inspect}") if logger
else
raise LoginError.new(response.message + "(#{results.reply_code}: #{results.reply_text})")
end
# Perform the mandatory get request on the action URL.
results.secondary_response = perform_action_url
# We only yield
if block_given?
begin
yield results
ensure
self.logout
end
else
results
end
end
|
ruby
|
{
"resource": ""
}
|
q3599
|
RETS4R.Client.get_metadata
|
train
|
def get_metadata(type = 'METADATA-SYSTEM', id = '*')
xml = download_metadata(type, id)
result = @response_parser.parse_metadata(xml, @format)
# TODO: fix test to like this
# result = ResponseDocument.safe_parse(xml).validate!.to_rexml
if block_given?
yield result
else
result
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.