_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2500
|
Pandata.Parser.get_webnames_from_search
|
train
|
def get_webnames_from_search(html)
user_links = Nokogiri::HTML(html).css('.user_name a')
webnames = []
user_links.each
|
ruby
|
{
"resource": ""
}
|
q2501
|
Pandata.Parser.get_next_data_indices
|
train
|
def get_next_data_indices(html)
# .js-more-link is found on mobile pages.
show_more = Nokogiri::HTML(html).css('.show_more, .js-more-link')[0]
if show_more
next_indices = {}
data_attributes = ['nextStartIndex', 'nextLikeStartIndex', 'nextThumbStartIndex']
data_attributes.each do |attr_name|
|
ruby
|
{
"resource": ""
}
|
q2502
|
Pandata.Parser.infobox_each_link
|
train
|
def infobox_each_link(html)
Nokogiri::HTML(html).css('.infobox').each do |infobox|
infobox_body = infobox.css('.infobox-body')
title_link = infobox_body.css('h3 a').text.strip
subtitle_link = infobox_body.css('p a').first
|
ruby
|
{
"resource": ""
}
|
q2503
|
Pandata.Parser.doublelink_each_link
|
train
|
def doublelink_each_link(html)
Nokogiri::HTML(html).css('.double-link').each do |doublelink|
title_link = doublelink.css('.media__bd__header').text.strip
subtitle_link
|
ruby
|
{
"resource": ""
}
|
q2504
|
Pandata.Parser.get_followx_users
|
train
|
def get_followx_users(html)
users = []
Nokogiri::HTML(html).css('.follow_section').each do |section|
listener_name = section.css('.listener_name').first
webname = listener_name['webname']
# Remove any 'spans with a space' that sometimes appear with special characters.
listener_name.css('span').each(&:remove)
|
ruby
|
{
"resource": ""
}
|
q2505
|
TTY.Platform.detect_system_properties
|
train
|
def detect_system_properties(arch)
parts = (arch || architecture).split('-', 2)
if parts.length == 1
|
ruby
|
{
"resource": ""
}
|
q2506
|
Masq.ServerController.decide
|
train
|
def decide
@site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root)
@site.persona = current_account.personas.find(params[:persona_id]
|
ruby
|
{
"resource": ""
}
|
q2507
|
Masq.ServerController.complete
|
train
|
def complete
if params[:cancel]
cancel
else
resp = checkid_request.answer(true, nil, identifier(current_account))
if params[:always]
@site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url])
@site.update_attributes(params[:site])
elsif sreg_request || ax_fetch_request
@site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url])
@site.attributes = params[:site]
elsif ax_store_request
@site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url])
not_supported, not_accepted, accepted = [], [], []
ax_store_request.data.each do |type_uri, values|
if property = Persona.attribute_name_for_type_uri(type_uri)
store_attribute = params[:site][:ax_store][property.to_sym]
if store_attribute && !store_attribute[:value].blank?
@site.persona.update_attribute(property, values.first)
accepted << type_uri
else
not_accepted << type_uri
|
ruby
|
{
"resource": ""
}
|
q2508
|
Masq.ServerController.handle_checkid_request
|
train
|
def handle_checkid_request
if allow_verification?
save_checkid_request
redirect_to proceed_path
elsif openid_request.immediate
render_response(openid_request.answer(false))
|
ruby
|
{
"resource": ""
}
|
q2509
|
Masq.ServerController.save_checkid_request
|
train
|
def save_checkid_request
clear_checkid_request
request = OpenIdRequest.create!(:parameters
|
ruby
|
{
"resource": ""
}
|
q2510
|
Masq.ServerController.ensure_valid_checkid_request
|
train
|
def ensure_valid_checkid_request
self.openid_request = checkid_request
if !openid_request.is_a?(OpenID::Server::CheckIDRequest)
redirect_to root_path, :alert => t(:identity_verification_request_invalid)
|
ruby
|
{
"resource": ""
}
|
q2511
|
Masq.ServerController.transform_ax_data
|
train
|
def transform_ax_data(parameters)
data = {}
parameters.each_pair do |key, details|
if details['value']
data["type.#{key}"] = details['type']
|
ruby
|
{
"resource": ""
}
|
q2512
|
Masq.ServerController.render_openid_error
|
train
|
def render_openid_error(exception)
error = case exception
when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'"
else exception.to_s
|
ruby
|
{
"resource": ""
}
|
q2513
|
MicroMagick.Image.add_input_option
|
train
|
def add_input_option(option_name, *args)
(@input_options ||= []).push(option_name)
args.each { |ea|
|
ruby
|
{
"resource": ""
}
|
q2514
|
MicroMagick.Image.square_crop
|
train
|
def square_crop(gravity = 'Center')
gravity(gravity) unless gravity.nil?
d
|
ruby
|
{
"resource": ""
}
|
q2515
|
OpenGraphReader.Base.method_missing
|
train
|
def method_missing(method, *args, &block)
name = method.to_s
if respond_to_missing?
|
ruby
|
{
"resource": ""
}
|
q2516
|
RandomData.Locations.uk_post_code
|
train
|
def uk_post_code
post_towns = %w(BM CB CV LE LI LS KT MK NE OX PL YO)
# Can't remember any othes at the moment
number_1 =
|
ruby
|
{
"resource": ""
}
|
q2517
|
GoogleStaticMapsHelper.Map.url
|
train
|
def url
raise BuildDataMissing, "We have to have markers, paths or center and zoom set when url is called!" unless can_build?
out = "#{API_URL}?"
params = []
(REQUIRED_OPTIONS + OPTIONAL_OPTIONS).each do |key|
value = send(key)
params << "#{key}=#{URI.escape(value.to_s)}" unless value.nil?
end
out += params.join('&')
params = []
grouped_markers.each_pair do |marker_options_as_url_params, markers|
|
ruby
|
{
"resource": ""
}
|
q2518
|
GoogleStaticMapsHelper.Map.grouped_markers
|
train
|
def grouped_markers
markers.inject(Hash.new {|hash, key| hash[key] = []}) do |groups, marker|
|
ruby
|
{
"resource": ""
}
|
q2519
|
GoogleStaticMapsHelper.Map.size=
|
train
|
def size=(size)
unless size.nil?
case size
when String
width, height = size.split('x')
when Array
width, height = size
when Hash
width = size[:width]
height = size[:height]
|
ruby
|
{
"resource": ""
}
|
q2520
|
RandomData.Text.alphanumeric
|
train
|
def alphanumeric(size=16)
s = ""
size.times { s << (i = Kernel.rand(62); i += ((i < 10) ?
|
ruby
|
{
"resource": ""
}
|
q2521
|
RandomData.MarkovGenerator.insert
|
train
|
def insert(result)
# puts "insert called with #{result}"
tabindex = Marshal.dump(@state)
if @table[tabindex].has_key?(result)
@table[tabindex][result] += 1
else
|
ruby
|
{
"resource": ""
}
|
q2522
|
Masq.PersonasHelper.countries_for_select
|
train
|
def countries_for_select
::I18nData.countries.map{|pair|
|
ruby
|
{
"resource": ""
}
|
q2523
|
Masq.PersonasHelper.languages_for_select
|
train
|
def languages_for_select
::I18nData.languages.map{|pair|
|
ruby
|
{
"resource": ""
}
|
q2524
|
Vcard.Vcard.lines
|
train
|
def lines(name=nil) #:yield: Line
# FIXME - this would be much easier if #lines was #each, and there was a
# different #lines that returned an Enumerator that used #each
unless block_given?
map do |f|
if( !name || f.name?(name) )
f2l(f)
else
nil
end
end.compact
|
ruby
|
{
"resource": ""
}
|
q2525
|
Vcard.Vcard.delete_if
|
train
|
def delete_if #:nodoc: :yield: line
# Do in two steps to not mess up progress through the enumerator.
rm = []
each do |f|
line = f2l(f)
if line && yield(line)
|
ruby
|
{
"resource": ""
}
|
q2526
|
Breadcrumble.ActionController.add_breadcrumb_to
|
train
|
def add_breadcrumb_to(name, url, trail_index)
breadcrumb_trails
@breadcrumb_trails[trail_index] ||= []
@breadcrumb_trails[trail_index] << {
name: case name
|
ruby
|
{
"resource": ""
}
|
q2527
|
Masq.AuthenticatedSystem.current_account=
|
train
|
def current_account=(new_account)
if self.auth_type_used != :basic
session[:account_id]
|
ruby
|
{
"resource": ""
}
|
q2528
|
Masq.AuthenticatedSystem.access_denied
|
train
|
def access_denied
respond_to do |format|
format.html do
store_location
|
ruby
|
{
"resource": ""
}
|
q2529
|
OpenGraphReader.Object.[]=
|
train
|
def []= name, value
if property?(name)
public_send "#{name}=", value
elsif OpenGraphReader.config.strict
|
ruby
|
{
"resource": ""
}
|
q2530
|
RandomData.Dates.date
|
train
|
def date(dayrange=10)
if dayrange.is_a?(Range)
offset = rand(dayrange.max-dayrange.min) + dayrange.min
else
offset
|
ruby
|
{
"resource": ""
}
|
q2531
|
RandomData.Dates.date_between
|
train
|
def date_between(range)
min_date = range.min.is_a?(Date) ? range.min : Date.parse(range.min)
max_date = range.max.is_a?(Date) ? range.max
|
ruby
|
{
"resource": ""
}
|
q2532
|
GoogleStaticMapsHelper.Path.url_params
|
train
|
def url_params # :nodoc:
raise BuildDataMissing, "Need at least 2 points to create a path!" unless can_build?
out = 'path='
path_params = OPTIONAL_OPTIONS.inject([]) do |path_params, attribute|
value = send(attribute)
path_params << "#{attribute}:#{URI.escape(value.to_s)}" unless value.nil?
path_params
end.join('|')
|
ruby
|
{
"resource": ""
}
|
q2533
|
GoogleStaticMapsHelper.Path.points=
|
train
|
def points=(array)
raise ArgumentError unless array.is_a? Array
|
ruby
|
{
"resource": ""
}
|
q2534
|
Masq.OpenidServerSystem.add_pape
|
train
|
def add_pape(resp, policies = [], nist_auth_level = 0, auth_time = nil)
if papereq = OpenID::PAPE::Request.from_openid_request(openid_request)
paperesp = OpenID::PAPE::Response.new
policies.each { |p| paperesp.add_policy_uri(p) }
|
ruby
|
{
"resource": ""
}
|
q2535
|
Masq.OpenidServerSystem.render_openid_response
|
train
|
def render_openid_response(resp)
signed_response = openid_server.signatory.sign(resp) if resp.needs_signing
web_response = openid_server.encode_response(resp)
case web_response.code
when OpenID::Server::HTTP_OK then render(:text => web_response.body, :status => 200)
|
ruby
|
{
"resource": ""
}
|
q2536
|
Masq.Persona.property
|
train
|
def property(type)
prop = Persona.mappings.detect { |i| i[1].include?(type) }
|
ruby
|
{
"resource": ""
}
|
q2537
|
Pandata.CLI.format_data
|
train
|
def format_data(data, json = false)
if json
JSON.generate(data)
else
data.map do |category, cat_data|
# Capitalize each word in the category symbol.
# e.g. :liked_tracks becomes 'Liked Tracks'
title = category.to_s.split('_').map(&:capitalize).join(' ')
output = if cat_data.empty?
" ** No Data **\n"
else
case category
when /liked_tracks/
formatter.tracks(cat_data)
when /liked_artists|liked_stations/
formatter.sort_list(cat_data)
|
ruby
|
{
"resource": ""
}
|
q2538
|
Pandata.CLI.download_data
|
train
|
def download_data
scraper_data = {}
@data_to_get.each do |data_category|
if /liked_(.*)/ =~ data_category
argument = $1.to_sym # :tracks, :artists, :stations or :albums
scraper_data[data_category] = @scraper.public_send(:likes, argument)
|
ruby
|
{
"resource": ""
}
|
q2539
|
Pandata.CLI.scraper_for
|
train
|
def scraper_for(user_id)
scraper = Pandata::Scraper.get(user_id)
if scraper.kind_of?(Array)
log "No exact match for '#{user_id}'."
unless scraper.empty?
|
ruby
|
{
"resource": ""
}
|
q2540
|
Masq.Site.ax_fetch=
|
train
|
def ax_fetch=(props)
props.each_pair do |property, details|
release_policies.build(:property => property,
|
ruby
|
{
"resource": ""
}
|
q2541
|
Masq.Site.sreg_properties
|
train
|
def sreg_properties
props = {}
release_policies.each do |rp|
is_sreg = (rp.property == rp.type_identifier)
|
ruby
|
{
"resource": ""
}
|
q2542
|
Masq.Site.ax_properties
|
train
|
def ax_properties
props = {}
release_policies.each do |rp|
if rp.type_identifier.match("://")
props["type.#{rp.property}"] = rp.type_identifier
|
ruby
|
{
"resource": ""
}
|
q2543
|
Pandata.DataFormatter.custom_sort
|
train
|
def custom_sort(enumerable)
sorted_array = enumerable.sort_by do |key, _|
key.sub(/^the\s*/i, '').downcase
end
# sort_by() returns an array when called on hashes.
if enumerable.kind_of?(Hash)
# Rebuild the hash.
sorted_hash = {}
|
ruby
|
{
"resource": ""
}
|
q2544
|
RandomData.ArrayRandomizer.roulette
|
train
|
def roulette(k=1)
wheel = []
weight = 0
# Create the cumulative array.
self.each do |x|
raise "Illegal negative weight #{x}" if x < 0
wheel.push(weight += x)
end
# print "wheel is #{wheel.inspect}\n";
# print "weight is #{weight.inspect}\n";
raise "Array had all zero weights" if weight.zero?
wheel.push(weight + 1) #Add extra element
if block_given?
k.times do
r = Kernel.rand() # so we don't pick up that from array.
# print "r is #{r.inspect}\n";
roll = weight.to_f * r
# print "roll is #{roll.inspect}\n";
0.upto(self.size - 1) do |i|
if wheel[i+1] > roll
yield i
break
end # if
|
ruby
|
{
"resource": ""
}
|
q2545
|
OpenGraphReader.Fetcher.body
|
train
|
def body
fetch_body unless fetched?
raise NoOpenGraphDataError, "No response body received for #{@uri}" if fetch_failed?
|
ruby
|
{
"resource": ""
}
|
q2546
|
OpenGraphReader.Fetcher.html?
|
train
|
def html?
fetch_headers unless fetched_headers?
response = @get_response || @head_response
return false if fetch_failed?
return false unless response
return false
|
ruby
|
{
"resource": ""
}
|
q2547
|
Boson.Scientist.redefine_command
|
train
|
def redefine_command(obj, command)
cmd_block = redefine_command_block(obj, command)
@no_option_commands << command if command.options.nil?
|
ruby
|
{
"resource": ""
}
|
q2548
|
Boson.Scientist.redefine_command_block
|
train
|
def redefine_command_block(obj, command)
object_methods(obj)[command.name] ||= begin
obj.method(command.name)
rescue NameError
raise Error, "No method exists to redefine command '#{command.name}'."
end
|
ruby
|
{
"resource": ""
}
|
q2549
|
Boson.Scientist.analyze
|
train
|
def analyze(obj, command, args, &block)
@global_options, @command, @original_args = {}, command, args.dup
@args = translate_args(obj, args)
|
ruby
|
{
"resource": ""
}
|
q2550
|
Boson.OptionParser.formatted_usage
|
train
|
def formatted_usage
return "" if @opt_types.empty?
@opt_types.map do |opt, type|
val = respond_to?("usage_for_#{type}", true) ?
|
ruby
|
{
"resource": ""
}
|
q2551
|
Boson.OptionParser.print_usage_table
|
train
|
def print_usage_table(options={})
fields = get_usage_fields options[:fields]
fields, opts =
|
ruby
|
{
"resource": ""
}
|
q2552
|
Boson.OptionParser.indifferent_hash
|
train
|
def indifferent_hash
Hash.new {|hash,key|
|
ruby
|
{
"resource": ""
}
|
q2553
|
Boson.Loader.load
|
train
|
def load
load_source_and_set_module
module_callbacks if @module
yield if block_given? # load dependencies
detect_additions
|
ruby
|
{
"resource": ""
}
|
q2554
|
Boson.Loader.detect_additions
|
train
|
def detect_additions(options={}, &block)
Util.detect(options, &block).tap do |detected|
|
ruby
|
{
"resource": ""
}
|
q2555
|
Boson.Loader.load_commands
|
train
|
def load_commands
@module = @module ? Util.constantize(@module) :
Util.create_module(Boson::Commands, clean_name)
before_load_commands
check_for_method_conflicts unless @force
|
ruby
|
{
"resource": ""
}
|
q2556
|
RedSnow.Object.deep_symbolize_keys
|
train
|
def deep_symbolize_keys
return each_with_object({}) { |memo, (k, v)| memo[k.to_sym] = v.deep_symbolize_keys } if self.is_a?(Hash)
|
ruby
|
{
"resource": ""
}
|
q2557
|
RedSnow.NamedBlueprintNode.ensure_description_newlines
|
train
|
def ensure_description_newlines(buffer)
return if description.empty?
if description[-1, 1] != '\n'
buffer << '\n\n'
|
ruby
|
{
"resource": ""
}
|
q2558
|
RedSnow.KeyValueCollection.filter_collection
|
train
|
def filter_collection(ignore_keys)
return @collection if ignore_keys.blank?
@collection.select { |kv_item|
|
ruby
|
{
"resource": ""
}
|
q2559
|
Boson.Library.command_objects
|
train
|
def command_objects(names=self.commands, command_array=Boson.commands)
|
ruby
|
{
"resource": ""
}
|
q2560
|
Boson.Util.create_module
|
train
|
def create_module(base_module, name)
desired_class = camelize(name)
possible_suffixes = [''] + %w{1 2 3 4 5 6 7 8 9 10}
if suffix = possible_suffixes.find {|e|
|
ruby
|
{
"resource": ""
}
|
q2561
|
HandleInvalidPercentEncodingRequests.Middleware.call
|
train
|
def call(env)
# calling env.dup here prevents bad things from happening
request = Rack::Request.new(env.dup)
# calling request.params is sufficient to trigger the error see
# https://github.com/rack/rack/issues/337#issuecomment-46453404
request.params
@app.call(env)
# Rescue from that specific ArgumentError
rescue ArgumentError => e
|
ruby
|
{
"resource": ""
}
|
q2562
|
Particle.Connection.connection
|
train
|
def connection
@connection ||= Faraday.new(conn_opts) do |http|
http.url_prefix = endpoint
if @access_token
|
ruby
|
{
"resource": ""
}
|
q2563
|
Boson.MethodInspector.new_method_added
|
train
|
def new_method_added(mod, meth)
self.current_module = mod
store[:temp] ||= {}
METHODS.each do |e|
store[e][meth.to_s] = store[:temp][e] if store[:temp][e]
end
if store[:temp][:option]
(store[:options][meth.to_s] ||= {}).merge! store[:temp][:option]
|
ruby
|
{
"resource": ""
}
|
q2564
|
Boson.OptionCommand.parse
|
train
|
def parse(args)
if args.size == 1 && args[0].is_a?(String)
args = Shellwords.shellwords(args[0]) if !Boson.in_shell
global_opt, parsed_options, args = parse_options args
# last string argument interpreted as args + options
elsif args.size > 1 && args[-1].is_a?(String)
temp_args = Boson.in_shell ? args : Shellwords.shellwords(args.pop)
global_opt, parsed_options, new_args = parse_options temp_args
Boson.in_shell ? args
|
ruby
|
{
"resource": ""
}
|
q2565
|
Boson.OptionCommand.modify_args
|
train
|
def modify_args(args)
if @command.default_option && @command.numerical_arg_size? &&
@command.arg_size <=
|
ruby
|
{
"resource": ""
}
|
q2566
|
Boson.OptionCommand.check_argument_size
|
train
|
def check_argument_size(args)
if @command.numerical_arg_size? && args.size != @command.arg_size
command_size, args_size = args.size > @command.arg_size ?
[@command.arg_size, args.size] :
[@command.arg_size - 1, args.size - 1]
|
ruby
|
{
"resource": ""
}
|
q2567
|
Boson.OptionCommand.add_default_args
|
train
|
def add_default_args(args, obj)
if @command.args && args.size < @command.arg_size - 1
# leave off last arg since its an option
@command.args.slice(0..-2).each_with_index {|arr,i|
next if args.size >= i + 1 # only fill in once args run out
|
ruby
|
{
"resource": ""
}
|
q2568
|
Kakurenbo.Core.delete
|
train
|
def delete(options = {:hard => false})
if options[:hard]
self.class.delete(self.id, options)
else
return if new_record?
|
ruby
|
{
"resource": ""
}
|
q2569
|
Kakurenbo.Core.destroy
|
train
|
def destroy(options = {:hard => false})
if options[:hard]
with_transaction_returning_status do
hard_destroy_associated_records
self.reload.hard_destroy
end
else
return true if destroyed?
|
ruby
|
{
"resource": ""
}
|
q2570
|
Kakurenbo.Core.restore
|
train
|
def restore(options = {:recursive => true})
return false unless destroyed?
with_transaction_returning_status do
run_callbacks(:restore) do
|
ruby
|
{
"resource": ""
}
|
q2571
|
Kakurenbo.Core.dependent_association_scopes
|
train
|
def dependent_association_scopes
self.class.reflect_on_all_associations.select { |reflection|
reflection.options[:dependent] == :destroy and reflection.klass.paranoid?
}.map { |reflection|
|
ruby
|
{
"resource": ""
}
|
q2572
|
KML.Geometry.altitude_mode=
|
train
|
def altitude_mode=(mode)
allowed_modes = %w(clampToGround relativeToGround absolute)
if allowed_modes.include?(mode)
@altitude_mode = mode
else
|
ruby
|
{
"resource": ""
}
|
q2573
|
KML.Feature.render
|
train
|
def render(xm=Builder::XmlMarkup.new(:indent => 2))
[:name, :visibility, :address].each do |a|
xm.__send__(a, self.__send__(a)) unless self.__send__(a).nil?
end
xm.description { xm.cdata!(description) } unless description.nil?
xm.open(self.open) unless open.nil?
xm.phoneNumber(phone_number) unless phone_number.nil?
xm.styleUrl(style_url) unless style_url.nil?
unless address_details.nil?
xm.AddressDetails(:xmlns => "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0") {
|
ruby
|
{
"resource": ""
}
|
q2574
|
RansackAdvancedSearch.SavedSearchUtils.perform_saved_searches_actions
|
train
|
def perform_saved_searches_actions(context, params={})
get_saved_searches(context)
|
ruby
|
{
"resource": ""
}
|
q2575
|
RansackAdvancedSearch.SavedSearchUtils.get_params_to_search
|
train
|
def get_params_to_search(context)
if params[:saved_search].present?
@saved_search = SavedSearch.find_by(id: params[:saved_search], context: context)
end
return params[:q] if
|
ruby
|
{
"resource": ""
}
|
q2576
|
RansackAdvancedSearch.SavedSearchUtils.save_or_update_saved_search
|
train
|
def save_or_update_saved_search(params)
if params[:save_new_search].present? || params[:save_search].present?
if params[:save_new_search].present?
@saved_search = new_saved_search(params)
elsif params[:save_search].present? && params[:saved_search].present?
@saved_search = update_saved_search(params)
elsif params[:save_search].present?
@saved_search = new_saved_search(params)
|
ruby
|
{
"resource": ""
}
|
q2577
|
Sudo.Wrapper.start!
|
train
|
def start!
Sudo::System.check
@sudo_pid = spawn(
"#{SUDO_CMD} -E #{RUBY_CMD} -I#{LIBDIR} #{@ruby_opts} #{SERVER_SCRIPT} #{@socket} #{Process.uid}"
)
Process.detach(@sudo_pid) if @sudo_pid # avoid zombies
|
ruby
|
{
"resource": ""
}
|
q2578
|
Sudo.Wrapper.load_gems
|
train
|
def load_gems
load_paths
prospective_gems.each do |prospect|
gem_name = prospect.dup
begin
loaded = @proxy.proxy(Kernel, :require, gem_name)
# puts "Loading Gem: #{gem_name} => #{loaded}"
rescue LoadError, NameError => e
|
ruby
|
{
"resource": ""
}
|
q2579
|
ChefRunDeck.Config.add
|
train
|
def add(config = {})
config.each do |key, value|
|
ruby
|
{
"resource": ""
}
|
q2580
|
ChefRunDeck.Chef.delete
|
train
|
def delete(node)
# => Make sure the Node Exists
return 'Node not found on Chef Server' unless Node.exists?(node)
# => Initialize the Admin API Client Settings
admin_api_client
|
ruby
|
{
"resource": ""
}
|
q2581
|
OctofactsUpdater.CLI.run
|
train
|
def run
unless opts[:action]
usage
exit 255
end
@config = {}
if opts[:config]
@config = YAML.load_file(opts[:config])
substitute_relative_paths!(@config, File.dirname(opts[:config]))
load_plugins(@config["plugins"]) if @config.key?("plugins")
end
@config[:options] = {}
opts.each do |k, v|
if v.is_a?(Hash)
@config[k.to_s] ||= {}
v.each do |v_key, v_val|
@config[k.to_s][v_key.to_s] = v_val
@config[k.to_s].delete(v_key.to_s) if
|
ruby
|
{
"resource": ""
}
|
q2582
|
OctofactsUpdater.CLI.index_file
|
train
|
def index_file
@index_file ||= begin
if config.fetch("index", {})["file"]
return config["index"]["file"] if File.file?(config["index"]["file"])
|
ruby
|
{
"resource": ""
}
|
q2583
|
OctofactsUpdater.CLI.print_or_write
|
train
|
def print_or_write(data)
if opts[:output_file]
File.open(opts[:output_file],
|
ruby
|
{
"resource": ""
}
|
q2584
|
Rake.Builder.ensure_headers
|
train
|
def ensure_headers
missing = missing_headers
return if missing.size == 0
message = "Compilation cannot proceed as the following header files
|
ruby
|
{
"resource": ""
}
|
q2585
|
Rake.Builder.source_files
|
train
|
def source_files
return @source_files if @source_files
old_dir = Dir.pwd
Dir.chdir @rakefile_path
@source_files = Rake::Path.find_files(@source_search_paths,
|
ruby
|
{
"resource": ""
}
|
q2586
|
AttrDeprecated.ClassMethods._set_attribute_as_deprecated
|
train
|
def _set_attribute_as_deprecated(attribute)
original_attribute_method = instance_method(attribute.to_sym)
klass = self
define_method attribute.to_sym do |*args|
backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
backtrace = backtrace_cleaner.clean(caller)
|
ruby
|
{
"resource": ""
}
|
q2587
|
OctofactsUpdater.FactIndex.reindex
|
train
|
def reindex(facts_to_index, fixtures)
@index_data = {}
facts_to_index.each { |fact| add(fact,
|
ruby
|
{
"resource": ""
}
|
q2588
|
OctofactsUpdater.FactIndex.write_file
|
train
|
def write_file(filename = nil)
filename ||= @filename
unless filename.is_a?(String)
raise ArgumentError, "Called write_file() for fact_index without
|
ruby
|
{
"resource": ""
}
|
q2589
|
Chore.Job.perform_async
|
train
|
def perform_async(*args)
self.class.run_hooks_for(:before_publish,*args)
@chore_publisher ||= self.class.options[:publisher]
|
ruby
|
{
"resource": ""
}
|
q2590
|
BeValidAsset.BeValidFeed.response_indicates_valid?
|
train
|
def response_indicates_valid?(response)
REXML::Document.new(response.body).root.get_ele
|
ruby
|
{
"resource": ""
}
|
q2591
|
Octofacts.Facts.method_missing
|
train
|
def method_missing(name, *args, &block)
if Octofacts::Manipulators.run(self, name, *args, &block)
@facts_manipulated = true
return self
end
if facts.respond_to?(name, false)
if args[0].is_a?(String) || args[0].is_a?(Symbol)
|
ruby
|
{
"resource": ""
}
|
q2592
|
ChefRunDeck.CLI.run
|
train
|
def run(argv = ARGV)
# => Parse CLI Configuration
cli = Options.new
cli.parse_options(argv)
# => Grab the Default Values
default = Config.options
# => Parse JSON Config File (If Specified and Exists)
json_config = Util.parse_json_config(cli.config[:config_file] || Config.config_file)
# => Merge Configuration (CLI Wins)
config = [default, json_config, cli.config].compact.reduce(:merge)
# => Apply Configuration
Config.setup do |cfg|
cfg.config_file = config[:config_file]
cfg.cache_timeout = config[:cache_timeout].to_i
cfg.bind = config[:bind]
cfg.port = config[:port]
cfg.auth_file = config[:auth_file]
cfg.state_file = config[:state_file]
cfg.environment = config[:environment].to_sym.downcase
|
ruby
|
{
"resource": ""
}
|
q2593
|
Soracom.Client.auth_by_user
|
train
|
def auth_by_user(operator_id, user_name, password, endpoint)
endpoint = API_BASE_URL if endpoint.nil?
res = RestClient.post endpoint + '/auth',
{ operatorId: operator_id, userName: user_name, password: password },
|
ruby
|
{
"resource": ""
}
|
q2594
|
OctofactsUpdater.Fact.set_value
|
train
|
def set_value(new_value, name_in = nil)
if name_in.nil?
if new_value.is_a?(Proc)
return @value = new_value.call(@value)
end
return @value = new_value
end
parts = if name_in.is_a?(String)
name_in.split("::")
elsif name_in.is_a?(Array)
name_in.map do |item|
if item.is_a?(String)
item
elsif item.is_a?(Hash) && item.key?("regexp")
Regexp.new(item["regexp"])
else
|
ruby
|
{
"resource": ""
}
|
q2595
|
OctofactsUpdater.Fact.set_structured_value
|
train
|
def set_structured_value(subhash, parts, value)
return if subhash.nil?
raise ArgumentError, "Cannot set structured value at #{parts.first.inspect}" unless subhash.is_a?(Hash)
raise ArgumentError, "parts must be an Array, got #{parts.inspect}" unless parts.is_a?(Array)
# At the top level, find all keys that match the first item in the parts.
matching_keys = subhash.keys.select do |key|
if parts.first.is_a?(String)
key == parts.first
elsif parts.first.is_a?(Regexp)
parts.first.match(key)
else
# :nocov:
# This is a bug - this code should be unreachable because of the checking in `set_value`
raise ArgumentError, "part must be a string or regexp, got #{parts.first.inspect}"
# :nocov:
end
end
# Auto-create a new hash if there is a value, the part is a string, and the key doesn't exist.
if parts.first.is_a?(String) && !value.nil? && !subhash.key?(parts.first)
subhash[parts.first] = {}
matching_keys << parts.first
end
return unless matching_keys.any?
# If we are at the end, set the value or delete the key.
if parts.size == 1
|
ruby
|
{
"resource": ""
}
|
q2596
|
Clash.Diff.diff_dirs
|
train
|
def diff_dirs(dir1, dir2)
mattching_dir_files(dir1, dir2).each do |file|
a = File.join(dir1, file)
|
ruby
|
{
"resource": ""
}
|
q2597
|
Clash.Diff.dir_files
|
train
|
def dir_files(dir)
Find.find(dir).to_a.reject!{|f|
|
ruby
|
{
"resource": ""
}
|
q2598
|
Clash.Diff.unique_files
|
train
|
def unique_files(dir, dir_files, common_files)
unique = dir_files - common_files
if !unique.empty?
@test_failures << yellowit("\nMissing from directory #{dir}:\n")
unique.each do |f|
failure = " - #{f}"
|
ruby
|
{
"resource": ""
}
|
q2599
|
OctofactsUpdater.Fixture.to_yaml
|
train
|
def to_yaml
sorted_facts = @facts.sort.to_h
facts_hash_with_expanded_values
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.