_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1000
|
Sweetify.SweetAlert.sweetalert
|
train
|
def sweetalert(text, title = '', opts = {})
opts = {
showConfirmButton: false,
timer: 2000,
allowOutsideClick: true,
confirmButtonText: 'OK'
}.merge(opts)
opts[:text] = text
opts[:title] = title
if opts[:button]
opts[:showConfirmButton] = true
opts[:confirmButtonText] = opts[:button] if opts[:button].is_a?(String)
opts.delete(:button)
end
if opts[:persistent]
opts[:showConfirmButton] = true
opts[:allowOutsideClick] = false
opts[:timer] = nil
opts[:confirmButtonText] = opts[:persistent] if opts[:persistent].is_a?(String)
opts.delete(:persistent)
end
flash_config(opts)
end
|
ruby
|
{
"resource": ""
}
|
q1001
|
Sweetify.SweetAlert.flash_config
|
train
|
def flash_config(opts)
if opts[:title].blank?
opts[:title] = opts[:text]
opts.delete(:text)
end
flash[:sweetify] = opts.to_json
end
|
ruby
|
{
"resource": ""
}
|
q1002
|
Exchanger.Element.to_xml
|
train
|
def to_xml(options = {})
doc = Nokogiri::XML::Document.new
root = doc.create_element(tag_name)
self.class.keys.each do |name|
value = read_attribute(name)
next if value.blank?
root[name.to_s.camelize] = value
end
self.class.elements.each do |name, field|
next if options[:only] && !options[:only].include?(name)
next if field.options[:readonly]
value = read_attribute(name)
next if field.type.is_a?(Array) && value.blank?
next if new_record? && field.type == Identifier
next if new_record? && value.blank?
if name == :text
root << value.to_s
else
root << field.to_xml(value)
end
end
root
end
|
ruby
|
{
"resource": ""
}
|
q1003
|
Middleware.Builder.insert
|
train
|
def insert(index, middleware, *args, &block)
index = self.index(index) unless index.is_a?(Integer)
raise "no such middleware to insert before: #{index.inspect}" unless index
stack.insert(index, [middleware, args, block])
end
|
ruby
|
{
"resource": ""
}
|
q1004
|
Middleware.Builder.replace
|
train
|
def replace(index, middleware, *args, &block)
if index.is_a?(Integer)
delete(index)
insert(index, middleware, *args, &block)
else
insert_before(index, middleware, *args, &block)
delete(index)
end
end
|
ruby
|
{
"resource": ""
}
|
q1005
|
Exchanger.Persistence.reload
|
train
|
def reload
if new_record?
false
else
reloaded_element = self.class.find(self.id)
@attributes = reloaded_element.attributes
reset_modifications
true
end
end
|
ruby
|
{
"resource": ""
}
|
q1006
|
Exchanger.Field.to_xml
|
train
|
def to_xml(value, options = {})
if value.is_a?(Exchanger::Element)
value.tag_name = tag_name
value.to_xml(options)
else
doc = Nokogiri::XML::Document.new
root = doc.create_element(tag_name)
case value
when Array
value.each do |sub_value|
root << sub_field.to_xml(sub_value, options)
end
when Boolean
root << doc.create_text_node(value == true)
when Time
root << doc.create_text_node(value.xmlschema)
else # String, Integer, etc
root << doc.create_text_node(value.to_s)
end
root
end
end
|
ruby
|
{
"resource": ""
}
|
q1007
|
Exchanger.Field.value_from_xml
|
train
|
def value_from_xml(node)
if type.respond_to?(:new_from_xml)
type.new_from_xml(node)
elsif type.is_a?(Array)
node.children.map do |sub_node|
sub_field.value_from_xml(sub_node)
end
elsif type == Boolean
node.text == "true"
elsif type == Integer
node.text.to_i unless node.text.empty?
elsif type == Time
Time.xmlschema(node.text) unless node.text.empty?
else
node.text
end
end
|
ruby
|
{
"resource": ""
}
|
q1008
|
Exchanger.Dirty.reset_attribute!
|
train
|
def reset_attribute!(name)
value = attribute_was(name)
if value
@attributes[name] = value
modifications.delete(name)
end
end
|
ruby
|
{
"resource": ""
}
|
q1009
|
Exchanger.Dirty.accessed
|
train
|
def accessed(name, value)
@accessed ||= {}
@accessed[name] = value.dup if (value.is_a?(Array) || value.is_a?(Hash)) && [email protected]_key?(name)
value
end
|
ruby
|
{
"resource": ""
}
|
q1010
|
Exchanger.Dirty.modifications
|
train
|
def modifications
@accessed.each_pair do |field, value|
current = @attributes[field]
if current != value || (current.is_a?(Array) &&
current.any? { |v| v.respond_to?(:changed?) && v.changed? })
@modifications[field] = [ value, current ]
end
end
@accessed.clear
@modifications
end
|
ruby
|
{
"resource": ""
}
|
q1011
|
Exchanger.Dirty.modify
|
train
|
def modify(name, old_value, new_value)
@attributes[name] = new_value
if @modifications && (old_value != new_value)
original = @modifications[name].first if @modifications[name]
@modifications[name] = [ (original || old_value), new_value ]
end
end
|
ruby
|
{
"resource": ""
}
|
q1012
|
Exchanger.Attributes.method_missing
|
train
|
def method_missing(name, *args)
attr = name.to_s.sub("=", "")
return super unless attributes.has_key?(attr)
if name.to_s.ends_with?("=")
write_attribute(attr, *args)
else
read_attribute(attr)
end
end
|
ruby
|
{
"resource": ""
}
|
q1013
|
Exchanger.Client.request
|
train
|
def request(post_body, headers)
response = @client.post(endpoint, post_body, headers)
return { :status => response.status, :body => response.content, :content_type => response.contenttype }
end
|
ruby
|
{
"resource": ""
}
|
q1014
|
Adauth.Connection.bind
|
train
|
def bind
conn = Net::LDAP.new :host => @config[:server],
:port => @config[:port],
:base => @config[:base]
if @config[:encryption]
conn.encryption @config[:encryption]
end
raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind])
conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password]
begin
Timeout::timeout(10){
if conn.bind
return conn
else
raise 'Query User Rejected'
end
}
rescue Timeout::Error
raise 'Unable to connect to LDAP Server'
rescue Errno::ECONNRESET
if @config[:allow_fallback]
@config[:port] = @config[:allow_fallback]
@config[:encryption] = false
return Adauth::Connection.new(@config).bind
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1015
|
Nextcloud.Api.request
|
train
|
def request(method, path, params = nil, body = nil, depth = nil, destination = nil, raw = false)
response = Net::HTTP.start(@url.host, @url.port,
use_ssl: @url.scheme == "https") do |http|
req = Kernel.const_get("Net::HTTP::#{method.capitalize}").new(@url.request_uri + path)
req["OCS-APIRequest"] = true
req.basic_auth @username, @password
req["Content-Type"] = "application/x-www-form-urlencoded"
req["Depth"] = 0 if depth
req["Destination"] = destination if destination
req.set_form_data(params) if params
req.body = body if body
http.request(req)
end
# if ![201, 204, 207].include? response.code
# raise Errors::Error.new("Nextcloud received invalid status code")
# end
raw ? response.body : Nokogiri::XML.parse(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q1016
|
Nextcloud.Helpers.parse_with_meta
|
train
|
def parse_with_meta(doc, xpath)
groups = []
doc.xpath(xpath).each do |prop|
groups << prop.text
end
meta = get_meta(doc)
groups.send(:define_singleton_method, :meta) do
meta
end
groups
end
|
ruby
|
{
"resource": ""
}
|
q1017
|
Nextcloud.Helpers.get_meta
|
train
|
def get_meta(doc)
meta = doc.xpath("//meta/*").each_with_object({}) do |node, meta|
meta[node.name] = node.text
end
end
|
ruby
|
{
"resource": ""
}
|
q1018
|
Nextcloud.Helpers.doc_to_hash
|
train
|
def doc_to_hash(doc, xpath = "/")
h = Hash.from_xml(doc.xpath(xpath).to_xml)
h
end
|
ruby
|
{
"resource": ""
}
|
q1019
|
Nextcloud.Helpers.add_meta
|
train
|
def add_meta(doc, obj)
meta = get_meta(doc)
obj.define_singleton_method(:meta) { meta } && obj
end
|
ruby
|
{
"resource": ""
}
|
q1020
|
Nextcloud.Helpers.parse_dav_response
|
train
|
def parse_dav_response(doc)
doc.remove_namespaces!
if doc.at_xpath("//error")
{
exception: doc.xpath("//exception").text,
message: doc.xpath("//message").text
}
elsif doc.at_xpath("//status")
{
status: doc.xpath("//status").text
}
else
{
status: "ok"
}
end
end
|
ruby
|
{
"resource": ""
}
|
q1021
|
Nextcloud.Helpers.has_dav_errors
|
train
|
def has_dav_errors(doc)
doc.remove_namespaces!
if doc.at_xpath("//error")
{
exception: doc.xpath("//exception").text,
message: doc.xpath("//message").text
}
else
false
end
end
|
ruby
|
{
"resource": ""
}
|
q1022
|
Adauth.AdObject.handle_field
|
train
|
def handle_field(field)
case field
when Symbol then return return_symbol_value(field)
when Array then return @ldap_object.try(field.first).try(:collect, &field.last)
end
end
|
ruby
|
{
"resource": ""
}
|
q1023
|
Adauth.AdObject.cn_groups_nested
|
train
|
def cn_groups_nested
@cn_groups_nested = cn_groups
cn_groups.each do |group|
ado = Adauth::AdObjects::Group.where('name', group).first
if ado
groups = convert_to_objects ado.cn_groups
groups.each do |g|
@cn_groups_nested.push g if !(@cn_groups_nested.include?(g))
end
end
end
return @cn_groups_nested
end
|
ruby
|
{
"resource": ""
}
|
q1024
|
Adauth.AdObject.ous
|
train
|
def ous
unless @ous
@ous = []
@ldap_object.dn.split(/,/).each do |entry|
@ous.push Adauth::AdObjects::OU.where('name', entry.gsub(/OU=/, '')).first if entry =~ /OU=/
end
end
@ous
end
|
ruby
|
{
"resource": ""
}
|
q1025
|
Adauth.AdObject.modify
|
train
|
def modify(operations)
Adauth.logger.info(self.class.inspect) { "Attempting modify operation" }
unless Adauth.connection.modify :dn => @ldap_object.dn, :operations => operations
Adauth.logger.fatal(self.class.inspect) { "Modify Operation Failed! Code: #{Adauth.connection.get_operation_result.code} Message: #{Adauth.connection.get_operation_result.message}" }
raise 'Modify Operation Failed (see log for details)'
end
end
|
ruby
|
{
"resource": ""
}
|
q1026
|
Adauth.AdObject.members
|
train
|
def members
unless @members
@members = []
[Adauth::AdObjects::Computer, Adauth::AdObjects::OU, Adauth::AdObjects::User, Adauth::AdObjects::Group].each do |object|
object.all.each do |entity|
@members.push entity if entity.is_a_member?(self)
end
end
end
@members
end
|
ruby
|
{
"resource": ""
}
|
q1027
|
WDM.SpecSupport.run_and_collect_multiple_changes
|
train
|
def run_and_collect_multiple_changes(monitor, times, directory, *flags, &block)
watch_and_run(monitor, times, false, directory, *flags, &block)
end
|
ruby
|
{
"resource": ""
}
|
q1028
|
WDM.SpecSupport.run
|
train
|
def run(monitor, directory, *flags, &block)
result = watch_and_run(monitor, 1, false, directory, *flags, &block)
result.changes[0].directory = result.directory
result.changes[0]
end
|
ruby
|
{
"resource": ""
}
|
q1029
|
WDM.SpecSupport.run_with_fixture
|
train
|
def run_with_fixture(monitor, *flags, &block)
fixture do |f|
run(monitor, f, *flags, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q1030
|
WDM.SpecSupport.run_recursively_and_collect_multiple_changes
|
train
|
def run_recursively_and_collect_multiple_changes(monitor, times, directory, *flags, &block)
watch_and_run(monitor, times, true, directory, *flags, &block)
end
|
ruby
|
{
"resource": ""
}
|
q1031
|
WDM.SpecSupport.run_recursively
|
train
|
def run_recursively(monitor, directory, *flags, &block)
result = watch_and_run(monitor, 1, true, directory, *flags, &block)
result.changes[0].directory = result.directory
result.changes[0]
end
|
ruby
|
{
"resource": ""
}
|
q1032
|
WDM.SpecSupport.run_recursively_with_fixture
|
train
|
def run_recursively_with_fixture(monitor, *flags, &block)
fixture do |f|
run_recursively(monitor, f, *flags, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q1033
|
WDM.SpecSupport.watch_and_run
|
train
|
def watch_and_run(monitor, times, recursively, directory, *flags)
result = OpenStruct.new(directory: directory, changes: [])
i = 0
result.changes[i] = OpenStruct.new(called: false)
can_return = false
callback = Proc.new do |change|
next if can_return
result.changes[i].called = true;
result.changes[i].change = change
i += 1
if i < times
result.changes[i] = OpenStruct.new(called: false)
else
can_return = true
end
end
if recursively
monitor.watch_recursively(directory, *flags, &callback)
else
monitor.watch(directory, *flags, &callback)
end
thread = Thread.new(monitor) { |m| m.run! }
sleep(0.2) # give time for the monitor to bootup
yield # So much boilerplate code to get here :S
sleep(0.2) # allow the monitor to run the callbacks
# Nothing can change after the callback if there is only one of them,
# so never wait for one callback
if times > 1
until can_return
sleep(0.1)
end
end
return result
ensure
monitor.stop
thread.join if thread
end
|
ruby
|
{
"resource": ""
}
|
q1034
|
WDM.SpecSupport.fixture
|
train
|
def fixture
pwd = FileUtils.pwd
path = File.expand_path(File.join(pwd, "spec/.fixtures/#{rand(99999)}"))
FileUtils.mkdir_p(path)
FileUtils.cd(path)
yield(path)
ensure
FileUtils.cd pwd
FileUtils.rm_rf(path) if File.exists?(path)
end
|
ruby
|
{
"resource": ""
}
|
q1035
|
PryTheme.RGB.to_term
|
train
|
def to_term(color_model = 256)
term = case color_model
when 256 then PryTheme::RGB::TABLE.index(@value)
when 16 then PryTheme::RGB::SYSTEM.index(@value)
when 8 then PryTheme::RGB::LINUX.index(@value)
else raise ArgumentError,
"invalid value for PryTheme::HEX#to_term(): #{ @value }"
end
term = find_among_term_colors(term, color_model) if term.nil?
PryTheme::TERM.new(term, color_model)
end
|
ruby
|
{
"resource": ""
}
|
q1036
|
PryTheme.RGB.validate_array
|
train
|
def validate_array(ary)
correct_size = ary.size.equal?(3)
correct_vals = ary.all?{ |val| val.is_a?(Integer) && val.between?(0, 255) }
return true if correct_size && correct_vals
raise ArgumentError,
%|invalid value for PryTheme::RGB#validate_array(): "#{ ary }"|
end
|
ruby
|
{
"resource": ""
}
|
q1037
|
PryTheme.RGB.nearest_term_256
|
train
|
def nearest_term_256(byte)
for i in 0..4
lower, upper = BYTEPOINTS_256[i], BYTEPOINTS_256[i + 1]
next unless byte.between?(lower, upper)
distance_from_lower = (lower - byte).abs
distance_from_upper = (upper - byte).abs
closest = distance_from_lower < distance_from_upper ? lower : upper
end
closest
end
|
ruby
|
{
"resource": ""
}
|
q1038
|
PryTheme.RGB.find_among_term_colors
|
train
|
def find_among_term_colors(term, color_model)
rgb = @value.map { |byte| nearest_term_256(byte) }
term = PryTheme::RGB::TABLE.index(rgb)
approximate(term, color_model)
end
|
ruby
|
{
"resource": ""
}
|
q1039
|
PryTheme.RGB.approximate
|
train
|
def approximate(term, color_model)
needs_approximation = (term > color_model - 1)
if needs_approximation
case color_model
when 16 then nearest_term_16(term)
when 8 then nearest_term_8(term)
end
else
term
end
end
|
ruby
|
{
"resource": ""
}
|
q1040
|
Sinatra.SwaggerExposer.endpoint_parameter
|
train
|
def endpoint_parameter(name, description, how_to_pass, required, type, params = {})
parameters = settings.swagger_current_endpoint_parameters
check_if_not_duplicate(name, parameters, 'Parameter')
parameters[name] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointParameter.new(
name,
description,
how_to_pass,
required,
type,
params,
settings.swagger_types.types_names)
end
|
ruby
|
{
"resource": ""
}
|
q1041
|
Sinatra.SwaggerExposer.endpoint
|
train
|
def endpoint(params)
params.each_pair do |param_name, param_value|
case param_name
when :summary
endpoint_summary param_value
when :description
endpoint_description param_value
when :tags
endpoint_tags *param_value
when :produces
endpoint_produces *param_value
when :path
endpoint_path param_value
when :parameters
param_value.each do |param, args_param|
endpoint_parameter param, *args_param
end
when :responses
param_value.each do |code, args_response|
endpoint_response code, *args_response
end
else
raise SwaggerInvalidException.new("Invalid endpoint parameter [#{param_name}]")
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1042
|
Sinatra.SwaggerExposer.response_header
|
train
|
def response_header(name, type, description)
settings.swagger_response_headers.add_response_header(name, type, description)
end
|
ruby
|
{
"resource": ""
}
|
q1043
|
Sinatra.SwaggerExposer.endpoint_response
|
train
|
def endpoint_response(code, type = nil, description = nil, headers = [])
responses = settings.swagger_current_endpoint_responses
check_if_not_duplicate(code, responses, 'Response')
responses[code] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointResponse.new(
type,
description,
settings.swagger_types.types_names,
headers,
settings.swagger_response_headers
)
end
|
ruby
|
{
"resource": ""
}
|
q1044
|
Sinatra.SwaggerExposer.route
|
train
|
def route(verb, path, options = {}, &block)
no_swagger = options[:no_swagger]
options.delete(:no_swagger)
if (verb == 'HEAD') || no_swagger
super(verb, path, options, &block)
else
request_processor = create_request_processor(verb.downcase, path, options)
super(verb, path, options) do |*params|
response = catch(:halt) do
request_processor.run(self, params, &block)
end
if settings.result_validation
begin
# Inspired from Sinatra#invoke
if (Fixnum === response) or (String === response)
response = [response]
end
if (Array === response) and (Fixnum === response.first)
response_for_validation = response.dup
response_status = response_for_validation.shift
response_body = response_for_validation.pop
response_headers = (response_for_validation.pop || {}).merge(self.response.header)
response_content_type = response_headers['Content-Type']
request_processor.validate_response(response_body, response_content_type, response_status)
elsif response.respond_to? :each
request_processor.validate_response(response.first.dup, self.response.header['Content-Type'], 200)
end
rescue Sinatra::SwaggerExposer::SwaggerInvalidException => e
content_type :json
throw :halt, [400, {:code => 400, :message => e.message}.to_json]
end
end
throw :halt, response
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1045
|
Sinatra.SwaggerExposer.create_request_processor
|
train
|
def create_request_processor(type, path, opts)
current_endpoint_info = settings.swagger_current_endpoint_info
current_endpoint_parameters = settings.swagger_current_endpoint_parameters
current_endpoint_responses = settings.swagger_current_endpoint_responses
endpoint = Sinatra::SwaggerExposer::Configuration::SwaggerEndpoint.new(
type,
path,
current_endpoint_parameters.values,
current_endpoint_responses.clone,
current_endpoint_info[:summary],
current_endpoint_info[:description],
current_endpoint_info[:tags],
current_endpoint_info[:path],
current_endpoint_info[:produces])
settings.swagger_endpoints << endpoint
current_endpoint_info.clear
current_endpoint_parameters.clear
current_endpoint_responses.clear
settings.swagger_processor_creator.create_request_processor(endpoint)
end
|
ruby
|
{
"resource": ""
}
|
q1046
|
Sinatra.SwaggerExposer.check_if_not_duplicate
|
train
|
def check_if_not_duplicate(key, values, name)
if values.key? key
raise SwaggerInvalidException.new("#{name} already exist for #{key} with value [#{values[key]}]")
end
end
|
ruby
|
{
"resource": ""
}
|
q1047
|
PryTheme.HEX.validate_value
|
train
|
def validate_value(value)
unless value.is_a?(String)
raise TypeError, "can't convert #{ value.class } into PryTheme::HEX"
end
if value !~ PryTheme::HEX::PATTERN
fail ArgumentError, %|invalid value for PryTheme::HEX#new(): "#{value}"|
end
true
end
|
ruby
|
{
"resource": ""
}
|
q1048
|
PryTheme.WhenStartedHook.recreate_user_themes_from_default_ones
|
train
|
def recreate_user_themes_from_default_ones
FileUtils.mkdir_p(USER_THEMES_DIR) unless File.exist?(USER_THEMES_DIR)
default_themes = Dir.entries(DEF_THEMES_DIR) - %w(. ..)
default_themes.each do |theme|
user_theme_path = File.join(USER_THEMES_DIR, theme)
next if File.exist?(user_theme_path)
def_theme_path = File.join(DEF_THEMES_DIR, theme)
FileUtils.cp(def_theme_path, USER_THEMES_DIR)
end
end
|
ruby
|
{
"resource": ""
}
|
q1049
|
Bond.Rc.files
|
train
|
def files(input)
(::Readline::FILENAME_COMPLETION_PROC.call(input) || []).map {|f|
f =~ /^~/ ? File.expand_path(f) : f
}
end
|
ruby
|
{
"resource": ""
}
|
q1050
|
Bond.Rc.objects_of
|
train
|
def objects_of(klass)
object = []
ObjectSpace.each_object(klass) {|e| object.push(e) }
object
end
|
ruby
|
{
"resource": ""
}
|
q1051
|
Bond.Mission.call_search
|
train
|
def call_search(search, input, list)
Rc.send("#{search}_search", input || '', list)
rescue
message = $!.is_a?(NoMethodError) && !Rc.respond_to?("#{search}_search") ?
"Completion search '#{search}' doesn't exist." :
"Failed during completion search with '#{$!.message}'."
raise FailedMissionError.new(self), message
end
|
ruby
|
{
"resource": ""
}
|
q1052
|
Bond.Mission.call_action
|
train
|
def call_action(input)
@action.respond_to?(:call) ? @action.call(input) : Rc.send(@action, input)
rescue StandardError, SyntaxError
message = $!.is_a?(NoMethodError) && [email protected]_to?(:call) &&
!Rc.respond_to?(@action) ? "Completion action '#{@action}' doesn't exist." :
"Failed during completion action '#{name}' with '#{$!.message}'."
raise FailedMissionError.new(self), message
end
|
ruby
|
{
"resource": ""
}
|
q1053
|
MagicCloud.Spriter.ensure_position
|
train
|
def ensure_position(rect)
# no place in current row -> go to next row
if cur_x + rect.width > canvas.width
@cur_x = 0
@cur_y += row_height
@row_height = 0
end
# no place in current canvas -> restart canvas
restart_canvas! if cur_y + rect.height > canvas.height
end
|
ruby
|
{
"resource": ""
}
|
q1054
|
NBayes.Data.remove_token_from_category
|
train
|
def remove_token_from_category(category, token)
cat_data(category)[:tokens][token] -= 1
delete_token_from_category(category, token) if cat_data(category)[:tokens][token] < 1
cat_data(category)[:total_tokens] -= 1
delete_category(category) if cat_data(category)[:total_tokens] < 1
end
|
ruby
|
{
"resource": ""
}
|
q1055
|
NBayes.Base.load
|
train
|
def load(yml)
if yml.nil?
nbayes = NBayes::Base.new
elsif yml[0..2] == "---"
nbayes = self.class.from_yml(yml)
else
nbayes = self.class.from(yml)
end
nbayes
end
|
ruby
|
{
"resource": ""
}
|
q1056
|
Bond.Agent.complete
|
train
|
def complete(options={}, &block)
if (mission = create_mission(options, &block)).is_a?(Mission)
mission.place.is_a?(Integer) ? @missions.insert(mission.place - 1, mission).compact! : @missions << mission
sort_last_missions
end
mission
end
|
ruby
|
{
"resource": ""
}
|
q1057
|
Bond.Agent.recomplete
|
train
|
def recomplete(options={}, &block)
if (mission = create_mission(options, &block)).is_a?(Mission)
if (existing_mission = @missions.find {|e| e.name == mission.name })
@missions[@missions.index(existing_mission)] = mission
sort_last_missions
else
return "No existing mission found to recomplete."
end
end
mission
end
|
ruby
|
{
"resource": ""
}
|
q1058
|
Bond.Agent.spy
|
train
|
def spy(input)
if (mission = find_mission(input))
puts mission.match_message, "Possible completions: #{mission.execute.inspect}",
"Matches for #{mission.condition.inspect} are #{mission.matched.to_a.inspect}"
else
puts "Doesn't match a completion."
end
rescue FailedMissionError => e
puts e.mission.match_message, e.message,
"Matches for #{e.mission.condition.inspect} are #{e.mission.matched.to_a.inspect}"
end
|
ruby
|
{
"resource": ""
}
|
q1059
|
Bond.M.debrief
|
train
|
def debrief(options={})
config.merge! options
config[:readline] ||= default_readline
if !config[:readline].is_a?(Module) &&
Bond.const_defined?(config[:readline].to_s.capitalize)
config[:readline] = Bond.const_get(config[:readline].to_s.capitalize)
end
unless %w{setup line_buffer}.all? {|e| config[:readline].respond_to?(e) }
$stderr.puts "Bond Error: Invalid readline plugin '#{config[:readline]}'."
end
end
|
ruby
|
{
"resource": ""
}
|
q1060
|
Bond.M.find_gem_file
|
train
|
def find_gem_file(rubygem, file)
begin gem(rubygem); rescue Exception; end
(dir = $:.find {|e| File.exist?(File.join(e, file)) }) && File.join(dir, file)
end
|
ruby
|
{
"resource": ""
}
|
q1061
|
Bond.M.load_file
|
train
|
def load_file(file)
Rc.module_eval File.read(file)
rescue Exception => e
$stderr.puts "Bond Error: Completion file '#{file}' failed to load with:", e.message
end
|
ruby
|
{
"resource": ""
}
|
q1062
|
Bond.M.load_dir
|
train
|
def load_dir(base_dir)
if File.exist?(dir = File.join(base_dir, 'completions'))
Dir[dir + '/*.rb'].each {|file| load_file(file) }
true
end
end
|
ruby
|
{
"resource": ""
}
|
q1063
|
Bond.M.home
|
train
|
def home
['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] }
return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH']
File.expand_path("~")
rescue
File::ALT_SEPARATOR ? "C:/" : "/"
end
|
ruby
|
{
"resource": ""
}
|
q1064
|
NessusREST.Client.user_add
|
train
|
def user_add(username, password, permissions, type)
payload = {
:username => username,
:password => password,
:permissions => permissions,
:type => type,
:json => 1
}
http_post(:uri=>"/users", :fields=>x_cookie, :data=>payload)
end
|
ruby
|
{
"resource": ""
}
|
q1065
|
NessusREST.Client.user_chpasswd
|
train
|
def user_chpasswd(user_id, password)
payload = {
:password => password,
:json => 1
}
res = http_put(:uri=>"/users/#{user_id}/chpasswd", :data=>payload, :fields=>x_cookie)
return res.code
end
|
ruby
|
{
"resource": ""
}
|
q1066
|
NessusREST.Client.http_delete
|
train
|
def http_delete(opts={})
ret=http_delete_low(opts)
if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then
authdefault
ret=http_delete_low(opts)
return ret
else
return ret
end
end
|
ruby
|
{
"resource": ""
}
|
q1067
|
NessusREST.Client.http_get
|
train
|
def http_get(opts={})
raw_content = opts[:raw_content] || false
ret=http_get_low(opts)
if !raw_content then
if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then
authdefault
ret=http_get_low(opts)
return ret
else
return ret
end
else
return ret
end
end
|
ruby
|
{
"resource": ""
}
|
q1068
|
NessusREST.Client.http_post
|
train
|
def http_post(opts={})
if opts.has_key?(:authenticationmethod) then
# i know authzmethod = opts.delete(:authorizationmethod) is short, but not readable
authzmethod = opts[:authenticationmethod]
opts.delete(:authenticationmethod)
end
ret=http_post_low(opts)
if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then
if not authzmethod
authdefault
ret=http_post_low(opts)
return ret
end
else
return ret
end
end
|
ruby
|
{
"resource": ""
}
|
q1069
|
NessusREST.Client.parse_json
|
train
|
def parse_json(body)
buf = {}
begin
buf = JSON.parse(body)
rescue JSON::ParserError
end
buf
end
|
ruby
|
{
"resource": ""
}
|
q1070
|
OAuth2Client.UrlHelper.build_url
|
train
|
def build_url(uri, opts={})
path = opts[:path] || ''
query = opts[:params] || {}
fragment = opts[:fragment] || {}
url = Addressable::URI.parse uri
url.path = path
url.query_values = query unless query.empty?
url.fragment = Addressable::URI.form_encode(fragment) unless fragment.empty?
url.to_s
end
|
ruby
|
{
"resource": ""
}
|
q1071
|
OAuth2Client.UrlHelper.generate_urlsafe_key
|
train
|
def generate_urlsafe_key(size=48)
seed = Time.now.to_i
size = size - seed.to_s.length
Base64.encode64("#{ OpenSSL::Random.random_bytes(size) }#{ seed }").gsub(/\W/, '')
end
|
ruby
|
{
"resource": ""
}
|
q1072
|
OAuth2Client.UrlHelper.to_query
|
train
|
def to_query(params)
unless params.is_a?(Hash)
raise "Expected Hash but got #{params.class.name}"
end
Addressable::URI.form_encode(params)
end
|
ruby
|
{
"resource": ""
}
|
q1073
|
OData.Entity.[]
|
train
|
def [](property_name)
if get_property(property_name).is_a?(::OData::ComplexType)
get_property(property_name)
else
get_property(property_name).value
end
rescue NoMethodError
raise ArgumentError, "Unknown property: #{property_name}"
end
|
ruby
|
{
"resource": ""
}
|
q1074
|
OData.Entity.[]=
|
train
|
def []=(property_name, value)
properties[property_name.to_s].value = value
rescue NoMethodError
raise ArgumentError, "Unknown property: #{property_name}"
end
|
ruby
|
{
"resource": ""
}
|
q1075
|
OData.Entity.to_xml
|
train
|
def to_xml
builder = Nokogiri::XML::Builder.new do |xml|
xml.entry('xmlns' => 'http://www.w3.org/2005/Atom',
'xmlns:data' => 'http://schemas.microsoft.com/ado/2007/08/dataservices',
'xmlns:metadata' => 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata',
'xmlns:georss' => 'http://www.georss.org/georss',
'xmlns:gml' => 'http://www.opengis.net/gml',
'xml:base' => 'http://services.odata.org/OData/OData.svc/') do
xml.category(term: "#{namespace}.#{type}",
scheme: 'http://schemas.microsoft.com/ado/2007/08/dataservices/scheme')
xml.author { xml.name }
xml.content(type: 'application/xml') do
xml['metadata'].properties do
properties.keys.each do |name|
next if name == primary_key
get_property(name).to_xml(xml)
end
end
end
end
end
builder.to_xml
end
|
ruby
|
{
"resource": ""
}
|
q1076
|
OData.ServiceRegistry.add
|
train
|
def add(service)
initialize_instance_variables
@services << service if service.is_a?(OData::Service) && [email protected]?(service)
@services_by_name[service.name] = @services.find_index(service)
@services_by_url[service.service_url] = @services.find_index(service)
end
|
ruby
|
{
"resource": ""
}
|
q1077
|
OData.Service.entity_sets
|
train
|
def entity_sets
@entity_sets ||= Hash[metadata.xpath('//EntityContainer/EntitySet').collect {|entity|
[
entity.attributes['EntityType'].value.gsub("#{namespace}.", ''),
entity.attributes['Name'].value
]
}]
end
|
ruby
|
{
"resource": ""
}
|
q1078
|
OData.Service.associations
|
train
|
def associations
@associations ||= Hash[metadata.xpath('//Association').collect do |association_definition|
[
association_definition.attributes['Name'].value,
build_association(association_definition)
]
end]
end
|
ruby
|
{
"resource": ""
}
|
q1079
|
OData.Service.execute
|
train
|
def execute(url_chunk, additional_options = {})
request = ::Typhoeus::Request.new(
URI.escape("#{service_url}/#{url_chunk}"),
options[:typhoeus].merge({ method: :get
})
.merge(additional_options)
)
request.run
response = request.response
validate_response(response)
response
end
|
ruby
|
{
"resource": ""
}
|
q1080
|
OData.Service.find_node
|
train
|
def find_node(results, node_name)
document = ::Nokogiri::XML(results.body)
document.remove_namespaces!
document.xpath("//#{node_name}").first
end
|
ruby
|
{
"resource": ""
}
|
q1081
|
OData.Service.find_entities
|
train
|
def find_entities(results)
document = ::Nokogiri::XML(results.body)
document.remove_namespaces!
document.xpath('//entry')
end
|
ruby
|
{
"resource": ""
}
|
q1082
|
OData.Service.get_title_property_name
|
train
|
def get_title_property_name(entity_name)
node = metadata.xpath("//EntityType[@Name='#{entity_name}']/Property[@FC_TargetPath='SyndicationTitle']").first
node.nil? ? nil : node.attributes['Name'].value
end
|
ruby
|
{
"resource": ""
}
|
q1083
|
OData.Service.properties_for_entity
|
train
|
def properties_for_entity(entity_name)
type_definition = metadata.xpath("//EntityType[@Name='#{entity_name}']").first
raise ArgumentError, "Unknown EntityType: #{entity_name}" if type_definition.nil?
properties_to_return = {}
type_definition.xpath('./Property').each do |property_xml|
property_name, property = process_property_from_xml(property_xml)
properties_to_return[property_name] = property
end
properties_to_return
end
|
ruby
|
{
"resource": ""
}
|
q1084
|
OData.Service.properties_for_complex_type
|
train
|
def properties_for_complex_type(type_name)
type_definition = metadata.xpath("//ComplexType[@Name='#{type_name}']").first
raise ArgumentError, "Unknown ComplexType: #{type_name}" if type_definition.nil?
properties_to_return = {}
type_definition.xpath('./Property').each do |property_xml|
property_name, property = process_property_from_xml(property_xml)
properties_to_return[property_name] = property
end
properties_to_return
end
|
ruby
|
{
"resource": ""
}
|
q1085
|
OData.EntitySet.each
|
train
|
def each(&block)
per_page = @each_batch_size
page = 0
loop do
entities = get_paginated_entities(per_page, page)
break if entities.empty?
entities.each do |entity|
block_given? ? block.call(entity) : yield(entity)
end
page += 1
end
end
|
ruby
|
{
"resource": ""
}
|
q1086
|
OData.EntitySet.first
|
train
|
def first(count = 1)
query = OData::Query.new(self).limit(count)
result = service.execute(query)
entities = service.find_entities(result)
res = count == 1 ? single_entity_from_xml(entities) : multiple_entities_from_xml(entities)
res
end
|
ruby
|
{
"resource": ""
}
|
q1087
|
OData.EntitySet.[]
|
train
|
def [](key)
entity = new_entity
key_property = entity.get_property(entity.primary_key)
key_property.value = key
result = service.execute("#{name}(#{key_property.url_value})")
entities = service.find_entities(result)
single_entity_from_xml(entities)
end
|
ruby
|
{
"resource": ""
}
|
q1088
|
NumbersInWords.NumberGroup.groups
|
train
|
def groups size
#1234567 => %w(765 432 1)
@array = in_groups_of(@number.to_s.reverse.split(""), size)
#%w(765 432 1) => %w(1 432 765)
@array.reverse!
#%w(1 432 765) => [1, 234, 567]
@array.map! {|group| group.reverse.join("").to_i}
@array.reverse! # put in ascending order of power of ten
power = 0
#[1, 234, 567] => {6 => 1, 3 => 234, 0 => 567}
@array.inject({}) do |o, digits|
o[power] = digits
power += size
o
end
end
|
ruby
|
{
"resource": ""
}
|
q1089
|
OData.Query.[]
|
train
|
def [](property)
property_instance = @entity_set.new_entity.get_property(property)
property_instance = property if property_instance.nil?
OData::Query::Criteria.new(property: property_instance)
end
|
ruby
|
{
"resource": ""
}
|
q1090
|
OData.Query.execute
|
train
|
def execute
response = entity_set.service.execute(self.to_s)
OData::Query::Result.new(self, response)
end
|
ruby
|
{
"resource": ""
}
|
q1091
|
Retrospec::Puppet::Generators.ProviderGenerator.template_dir
|
train
|
def template_dir
external_templates = File.expand_path(File.join(config_data[:template_dir], 'providers', 'provider_template.rb.retrospec.erb'))
if File.exist?(external_templates)
File.join(config_data[:template_dir], 'providers')
else
File.expand_path(File.join(File.dirname(File.dirname(__FILE__)), 'templates', 'providers'))
end
end
|
ruby
|
{
"resource": ""
}
|
q1092
|
Retrospec::Puppet::Generators.ProviderGenerator.type_file
|
train
|
def type_file(p_type = provider_type)
if TypeGenerator::CORE_TYPES.include?(p_type)
type_file = "puppet/type/#{p_type}.rb"
else
type_file = File.join(type_dir, "#{p_type}.rb")
end
type_file
end
|
ruby
|
{
"resource": ""
}
|
q1093
|
Utilities.PuppetModule.create_tmp_module_path
|
train
|
def create_tmp_module_path(module_path)
fail 'ModulePathNotFound' unless module_path
path = File.join(tmp_modules_dir, module_dir_name)
unless File.exist?(path) # only create if it doesn't already exist
# create a link where source is the current repo and dest is /tmp/modules/module_name
FileUtils.ln_s(module_path, path)
end
path
end
|
ruby
|
{
"resource": ""
}
|
q1094
|
Utilities.PuppetModule.tmp_modules_dir
|
train
|
def tmp_modules_dir
if @tmp_modules_dir.nil? || !File.exist?(@tmp_modules_dir)
tmp_path = File.expand_path(File.join(temporary_environment_path, 'modules'))
FileUtils.mkdir_p(tmp_path)
@tmp_modules_dir = tmp_path
end
@tmp_modules_dir
end
|
ruby
|
{
"resource": ""
}
|
q1095
|
Utilities.PuppetModule.request
|
train
|
def request(key, method)
instance = ::Puppet::Indirector::Indirection.instance(:resource_type)
indirection_name = 'test'
@request = ::Puppet::Indirector::Request.new(indirection_name, method, key, instance)
@request.environment = puppet_environment
@request
end
|
ruby
|
{
"resource": ""
}
|
q1096
|
Stemcell.Launcher.render_template
|
train
|
def render_template(opts={})
template_file_path = File.expand_path(TEMPLATE_PATH, __FILE__)
template_file = File.read(template_file_path)
erb_template = ERB.new(template_file)
last_bootstrap_line = LAST_BOOTSTRAP_LINE
generated_template = erb_template.result(binding)
@log.debug "genereated template is #{generated_template}"
return generated_template
end
|
ruby
|
{
"resource": ""
}
|
q1097
|
Stemcell.Launcher.get_vpc_security_group_ids
|
train
|
def get_vpc_security_group_ids(vpc_id, group_names)
group_map = {}
@log.info "resolving security groups #{group_names} in #{vpc_id}"
vpc = AWS::EC2::VPC.new(vpc_id, :ec2_endpoint => "ec2.#{@region}.amazonaws.com")
vpc.security_groups.each do |sg|
next if sg.vpc_id != vpc_id
group_map[sg.name] = sg.group_id
end
group_ids = []
group_names.each do |sg_name|
raise "Couldn't find security group #{sg_name} in #{vpc_id}" unless group_map.has_key?(sg_name)
group_ids << group_map[sg_name]
end
group_ids
end
|
ruby
|
{
"resource": ""
}
|
q1098
|
Rubyipmi.BaseCommand.runcmd
|
train
|
def runcmd
@success = false
@success = run
logger.debug(@lastcall.inspect) unless @lastcall.nil? if logger
logger.debug(@result) unless @result.nil? if logger
@success
end
|
ruby
|
{
"resource": ""
}
|
q1099
|
Rubyipmi.BaseCommand.find_fix
|
train
|
def find_fix(result)
return unless result
# The errorcode code hash contains the fix
begin
fix = ErrorCodes.search(result)
@options.merge_notify!(fix)
rescue
Rubyipmi.logger.debug("Could not find fix for error code: \n#{result}") if logger
raise "Could not find fix for error code: \n#{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.