_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q7100
|
Jinx.Inverse.detect_inverse_attribute
|
train
|
def detect_inverse_attribute(klass)
# The candidate attributes return the referencing type and don't already have an inverse.
candidates = domain_attributes.compose { |prop| klass <= prop.type and prop.inverse.nil? }
pa = detect_inverse_attribute_from_candidates(klass, candidates)
if pa then
logger.debug { "#{qp} #{klass.qp} inverse attribute is #{pa}." }
else
logger.debug { "#{qp} #{klass.qp} inverse attribute was not detected." }
end
pa
end
|
ruby
|
{
"resource": ""
}
|
q7101
|
Jinx.Inverse.delegate_writer_to_inverse
|
train
|
def delegate_writer_to_inverse(attribute, inverse)
prop = property(attribute)
# nothing to do if no inverse
inv_prop = prop.inverse_property || return
logger.debug { "Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}..." }
# redefine the write to set the dependent inverse
redefine_method(prop.writer) do |old_writer|
# delegate to the Jinx::Resource set_inverse method
lambda { |dep| set_inverse(dep, old_writer, inv_prop.writer) }
end
end
|
ruby
|
{
"resource": ""
}
|
q7102
|
Jinx.Inverse.restrict_attribute_inverse
|
train
|
def restrict_attribute_inverse(prop, inverse)
logger.debug { "Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}..." }
rst_prop = prop.restrict(self, :inverse => inverse)
logger.debug { "Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}." }
rst_prop
end
|
ruby
|
{
"resource": ""
}
|
q7103
|
Jinx.Inverse.add_inverse_updater
|
train
|
def add_inverse_updater(attribute)
prop = property(attribute)
# the reader and writer methods
rdr, wtr = prop.accessors
# the inverse attribute metadata
inv_prop = prop.inverse_property
# the inverse attribute reader and writer
inv_rdr, inv_wtr = inv_accessors = inv_prop.accessors
# Redefine the writer method to update the inverse by delegating to the inverse.
redefine_method(wtr) do |old_wtr|
# the attribute reader and (superseded) writer
accessors = [rdr, old_wtr]
if inv_prop.collection? then
lambda { |other| add_to_inverse_collection(other, accessors, inv_rdr) }
else
lambda { |other| set_inversible_noncollection_attribute(other, accessors, inv_wtr) }
end
end
logger.debug { "Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}." }
end
|
ruby
|
{
"resource": ""
}
|
q7104
|
Epicmix.Client.login
|
train
|
def login
url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx'
options = { :query => { :loginID => username, :password => password }}
response = HTTParty.post(url, options)
token_from(response) # if response.instance_of? Net::HTTPOK
end
|
ruby
|
{
"resource": ""
}
|
q7105
|
Epicmix.Client.season_stats
|
train
|
def season_stats
url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx'
options = { :timetype => 'season', :token => token }
response = HTTParty.get(url, :query => options, :headers => headers)
JSON.parse(response.body)['seasonStats']
end
|
ruby
|
{
"resource": ""
}
|
q7106
|
Mousevc.Validation.min_length?
|
train
|
def min_length?(value, length)
has_min_length = coerce_bool (value.length >= length)
unless has_min_length
@error = "Error, expected value to have at least #{length} characters, got: #{value.length}"
end
has_min_length
end
|
ruby
|
{
"resource": ""
}
|
q7107
|
Mousevc.Validation.max_length?
|
train
|
def max_length?(value, length)
has_max_length = coerce_bool (value.length <= length)
unless has_max_length
@error = "Error, expected value to have at most #{length} characters, got: #{value.length}"
end
has_max_length
end
|
ruby
|
{
"resource": ""
}
|
q7108
|
Mousevc.Validation.exact_length?
|
train
|
def exact_length?(value, length)
has_exact_length = coerce_bool (value.length == length)
unless has_exact_length
@error = "Error, expected value to have exactly #{length} characters, got: #{value.length}"
end
has_exact_length
end
|
ruby
|
{
"resource": ""
}
|
q7109
|
BetaInvite.BetaInvitesController.create
|
train
|
def create
email = params[:beta_invite][:email]
beta_invite = BetaInvite.new( email: email, token: SecureRandom.hex(10) )
if beta_invite.save
flash[:success] = "#{email} has been registered for beta invite"
# send an email if configured
if BetaInviteSetup.send_email_to_admins
BetaInvite::BetaInviteNotificationMailer.notify_admins( BetaInviteSetup.from_email, BetaInviteSetup.admin_emails, email, BetaInvite.count ).deliver
end
if BetaInviteSetup.send_thank_you_email
BetaInvite::BetaInviteNotificationMailer.thank_user( BetaInviteSetup.from_email, email ).deliver
end
redirect_to beta_invites_path
else
flash[:alert] = beta_invite.errors.full_messages
redirect_to new_beta_invite_path
end
end
|
ruby
|
{
"resource": ""
}
|
q7110
|
Spockets.Watcher.stop
|
train
|
def stop
if(@runner.nil? && @stop)
raise NotRunning.new
elsif(@runner.nil? || !@runner.alive?)
@stop = true
@runner = nil
else
@stop = true
if(@runner)
@runner.raise Resync.new if @runner.alive? && @runner.stop?
@runner.join(0.05) if @runner
@runner.kill if @runner && @runner.alive?
end
@runner = nil
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q7111
|
Spockets.Watcher.watch
|
train
|
def watch
until(@stop)
begin
resultset = Kernel.select(@sockets.keys, nil, nil, nil)
for sock in resultset[0]
string = sock.gets
if(sock.closed? || string.nil?)
if(@sockets[sock][:closed])
@sockets[sock][:closed].each do |pr|
pr[1].call(*([sock]+pr[0]))
end
end
@sockets.delete(sock)
else
string = clean? ? do_clean(string) : string
process(string.dup, sock)
end
end
rescue Resync
# break select and relisten #
end
end
@runner = nil
end
|
ruby
|
{
"resource": ""
}
|
q7112
|
Hoodie.FileHelper.command_in_path?
|
train
|
def command_in_path?(command)
found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p|
File.exist?(File.join(p, command))
end
found.include?(true)
end
|
ruby
|
{
"resource": ""
}
|
q7113
|
Ducktrap.PrettyDump.pretty_inspect
|
train
|
def pretty_inspect
io = StringIO.new
formatter = Formatter.new(io)
pretty_dump(formatter)
io.rewind
io.read
end
|
ruby
|
{
"resource": ""
}
|
q7114
|
Fixer.Response.method_missing
|
train
|
def method_missing(method_name, *args, &block)
if self.has_key?(method_name.to_s)
self.[](method_name, &block)
elsif self.body.respond_to?(method_name)
self.body.send(method_name, *args, &block)
elsif self.request[:api].respond_to?(method_name)
self.request[:api].send(method_name, *args, &block)
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q7115
|
SK::SDK.Sync.update
|
train
|
def update(side, flds=nil)
raise ArgumentError, 'The side to update must be :l or :r' unless [:l, :r].include?(side)
target, source = (side==:l) ? [:l, :r] : [:r, :l]
# use set field/s or update all
flds ||= fields
target_obj = self.send("#{target}_obj")
source_obj = self.send("#{source}_obj")
flds.each do |fld|
target_name = fld.send("#{target}_name")
source_name = fld.send("#{source}_name")
# remember for log
old_val = target_obj.send(target_name) rescue 'empty'
# get new value through transfer method or direct
new_val = if fld.transition?
cur_trans = fld.send("#{target}_trans")
eval "#{cur_trans} source_obj.send( source_name )"
else
source_obj.send( source_name )
end
target_obj.send( "#{target_name}=" , new_val )
log << "#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}"
end
end
|
ruby
|
{
"resource": ""
}
|
q7116
|
Pith.Input.ignorable?
|
train
|
def ignorable?
@ignorable ||= path.each_filename do |path_component|
project.config.ignore_patterns.each do |pattern|
return true if File.fnmatch(pattern, path_component)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7117
|
Pith.Input.render
|
train
|
def render(context, locals = {}, &block)
return file.read if !template?
ensure_loaded
pipeline.inject(@template_text) do |text, processor|
template = processor.new(file.to_s, @template_start_line) { text }
template.render(context, locals, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q7118
|
Pith.Input.load
|
train
|
def load
@load_time = Time.now
@meta = {}
if template?
logger.debug "loading #{path}"
file.open do |io|
read_meta(io)
@template_start_line = io.lineno + 1
@template_text = io.read
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7119
|
Utf8Sanitizer.UTF.process_hash_row
|
train
|
def process_hash_row(hsh)
if @headers.any?
keys_or_values = hsh.values
@row_id = hsh[:row_id]
else
keys_or_values = hsh.keys.map(&:to_s)
end
file_line = keys_or_values.join(',')
validated_line = utf_filter(check_utf(file_line))
res = line_parse(validated_line)
res
end
|
ruby
|
{
"resource": ""
}
|
q7120
|
Utf8Sanitizer.UTF.line_parse
|
train
|
def line_parse(validated_line)
return unless validated_line
row = validated_line.split(',')
return unless row.any?
if @headers.empty?
@headers = row
else
@data_hash.merge!(row_to_hsh(row))
@valid_rows << @data_hash
end
end
|
ruby
|
{
"resource": ""
}
|
q7121
|
Shells.ShellBase.wait_for_prompt
|
train
|
def wait_for_prompt(silence_timeout = nil, command_timeout = nil, timeout_error = true) #:doc:
raise Shells::NotRunning unless running?
silence_timeout ||= options[:silence_timeout]
command_timeout ||= options[:command_timeout]
# when did we send a NL and how many have we sent while waiting for output?
nudged_at = nil
nudge_count = 0
silence_timeout = silence_timeout.to_s.to_f unless silence_timeout.is_a?(Numeric)
nudge_seconds =
if silence_timeout > 0
(silence_timeout / 3.0) # we want to nudge twice before officially timing out.
else
0
end
# if there is a limit for the command timeout, then set the absolute timeout for the loop.
command_timeout = command_timeout.to_s.to_f unless command_timeout.is_a?(Numeric)
timeout =
if command_timeout > 0
Time.now + command_timeout
else
nil
end
# loop until the output matches the prompt regex.
# if something gets output async server side, the silence timeout will be handy in getting the shell to reappear.
# a match while waiting for output is invalid, so by requiring that flag to be false this should work with
# unbuffered input as well.
until output =~ prompt_match && !wait_for_output
# hint that we need to let another thread run.
Thread.pass
last_response = last_output
# Do we need to nudge the shell?
if nudge_seconds > 0 && (Time.now - last_response) > nudge_seconds
nudge_count = (nudged_at.nil? || nudged_at < last_response) ? 1 : (nudge_count + 1)
# Have we previously nudged the shell?
if nudge_count > 2 # we timeout on the third nudge.
raise Shells::SilenceTimeout if timeout_error
debug ' > silence timeout'
return false
else
nudged_at = Time.now
queue_input line_ending
# wait a bit longer...
self.last_output = nudged_at
end
end
# honor the absolute timeout.
if timeout && Time.now > timeout
raise Shells::CommandTimeout if timeout_error
debug ' > command timeout'
return false
end
end
# make sure there is a newline before the prompt, just to keep everything clean.
pos = (output =~ prompt_match)
if output[pos - 1] != "\n"
# no newline before prompt, fix that.
self.output = output[0...pos] + "\n" + output[pos..-1]
end
# make sure there is a newline at the end of STDOUT content buffer.
if stdout[-1] != "\n"
# no newline at end, fix that.
self.stdout += "\n"
end
true
end
|
ruby
|
{
"resource": ""
}
|
q7122
|
Shells.ShellBase.temporary_prompt
|
train
|
def temporary_prompt(prompt) #:doc:
raise Shells::NotRunning unless running?
old_prompt = prompt_match
begin
self.prompt_match = prompt
yield if block_given?
ensure
self.prompt_match = old_prompt
end
end
|
ruby
|
{
"resource": ""
}
|
q7123
|
Rails::Generator::Commands.Base.next_migration_string
|
train
|
def next_migration_string(padding = 3)
@s = (!@s.nil?)? @s.to_i + 1 : if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.#{padding}d" % next_migration_number
end
end
|
ruby
|
{
"resource": ""
}
|
q7124
|
Rozi.Shared.interpret_color
|
train
|
def interpret_color(color)
if color.is_a? String
# Turns RRGGBB into BBGGRR for hex conversion.
color = color[-2..-1] << color[2..3] << color[0..1]
color = color.to_i(16)
end
color
end
|
ruby
|
{
"resource": ""
}
|
q7125
|
Mousevc.App.listen
|
train
|
def listen
begin
clear_view
@router.route unless Input.quit?
reset if Input.reset?
end until Input.quit?
end
|
ruby
|
{
"resource": ""
}
|
q7126
|
Jinx.MultilineLogger.format_message
|
train
|
def format_message(severity, datetime, progname, msg)
if String === msg then
msg.inject('') { |s, line| s << super(severity, datetime, progname, line.chomp) }
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q7127
|
UserInput.TypeSafeHash.each_pair
|
train
|
def each_pair(type, default = nil)
real_hash.each_key() { |key|
value = fetch(key, type, default)
if (!value.nil?)
yield(key, value)
end
}
end
|
ruby
|
{
"resource": ""
}
|
q7128
|
UserInput.TypeSafeHash.each_match
|
train
|
def each_match(regex, type, default = nil)
real_hash.each_key() { |key|
if (matchinfo = regex.match(key))
value = fetch(key, type, default)
if (!value.nil?)
yield(matchinfo, value)
end
end
}
end
|
ruby
|
{
"resource": ""
}
|
q7129
|
ScopedSerializer.Serializer.attributes_hash
|
train
|
def attributes_hash
attributes = @scope.attributes.collect do |attr|
value = fetch_property(attr)
if value.kind_of?(BigDecimal)
value = value.to_f
end
[attr, value]
end
Hash[attributes]
end
|
ruby
|
{
"resource": ""
}
|
q7130
|
ScopedSerializer.Serializer.associations_hash
|
train
|
def associations_hash
hash = {}
@scope.associations.each do |association, options|
hash.merge!(render_association(association, options))
end
hash
end
|
ruby
|
{
"resource": ""
}
|
q7131
|
ScopedSerializer.Serializer.render_association
|
train
|
def render_association(association_data, options={})
hash = {}
if association_data.is_a?(Hash)
association_data.each do |association, association_options|
data = render_association(association, options.merge(:include => association_options))
hash.merge!(data) if data
end
elsif association_data.is_a?(Array)
association_data.each do |option|
data = render_association(option)
hash.merge!(data) if data
end
else
if options[:preload]
includes = options[:preload] == true ? options[:include] : options[:preload]
end
if (object = fetch_association(association_data, includes))
data = ScopedSerializer.for(object, options.merge(:associations => options[:include])).as_json
hash.merge!(data) if data
end
end
hash
end
|
ruby
|
{
"resource": ""
}
|
q7132
|
ScopedSerializer.Serializer.fetch_property
|
train
|
def fetch_property(property)
return nil unless property
unless respond_to?(property)
object = @resource.send(property)
else
object = send(property)
end
end
|
ruby
|
{
"resource": ""
}
|
q7133
|
ScopedSerializer.Serializer.fetch_association
|
train
|
def fetch_association(name, includes=nil)
association = fetch_property(name)
if includes.present? && ! @resource.association(name).loaded?
association.includes(includes)
else
association
end
end
|
ruby
|
{
"resource": ""
}
|
q7134
|
Remi.Job.execute
|
train
|
def execute(*components)
execute_transforms if components.empty? || components.include?(:transforms)
execute_sub_jobs if components.empty? || components.include?(:sub_jobs)
execute_load_targets if components.empty? || components.include?(:load_targets)
self
end
|
ruby
|
{
"resource": ""
}
|
q7135
|
KeytechKit.User.load
|
train
|
def load(username)
options = {}
options[:basic_auth] = @auth
response = self.class.get("/user/#{username}", options)
if response.success?
self.response = response
parse_response
self
else
raise response.response
end
end
|
ruby
|
{
"resource": ""
}
|
q7136
|
Jinx.Dependency.add_dependent_property
|
train
|
def add_dependent_property(property, *flags)
logger.debug { "Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}..." }
flags << :dependent unless flags.include?(:dependent)
property.qualify(*flags)
inv = property.inverse
inv_type = property.type
# example: Parent.add_dependent_property(child_prop) with inverse :parent calls the following:
# Child.add_owner(Parent, :children, :parent)
inv_type.add_owner(self, property.attribute, inv)
if inv then
logger.debug "Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}."
else
logger.debug "Marked #{qp}.#{property} as a uni-directional dependent attribute."
end
end
|
ruby
|
{
"resource": ""
}
|
q7137
|
Jinx.Dependency.add_owner
|
train
|
def add_owner(klass, inverse, attribute=nil)
if inverse.nil? then
raise ValidationError.new("Owner #{klass.qp} missing dependent attribute for dependent #{qp}")
end
logger.debug { "Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}..." }
if @owner_prop_hash then
raise MetadataError.new("Can't add #{qp} owner #{klass.qp} after dependencies have been accessed")
end
# Detect the owner attribute, if necessary.
attribute ||= detect_owner_attribute(klass, inverse)
hash = local_owner_property_hash
# Guard against a conflicting owner reference attribute.
if hash[klass] then
raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}")
end
# Add the owner class => attribute entry.
# The attribute is nil if the dependency is unidirectional, i.e. there is an owner class which
# references this class via a dependency attribute but there is no inverse owner attribute.
prop = property(attribute) if attribute
hash[klass] = prop
# If the dependency is unidirectional, then our job is done.
if attribute.nil? then
logger.debug { "#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}." }
return
end
# Bi-directional: add the owner property.
local_owner_properties << prop
# Set the inverse if necessary.
unless prop.inverse then
set_attribute_inverse(attribute, inverse)
end
# Set the owner flag if necessary.
prop.qualify(:owner) unless prop.owner?
# Redefine the writer method to issue a warning if the owner is changed.
rdr, wtr = prop.accessors
redefine_method(wtr) do |old_wtr|
lambda do |ref|
prev = send(rdr)
send(old_wtr, ref)
if prev and prev != ref then
if ref.nil? then
logger.warn("Unset the #{self} owner #{attribute} #{prev}.")
elsif ref.key != prev.key then
logger.warn("Reset the #{self} owner #{attribute} from #{prev} to #{ref}.")
end
end
ref
end
end
logger.debug { "Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}." }
logger.debug { "#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}." }
end
|
ruby
|
{
"resource": ""
}
|
q7138
|
Jinx.Dependency.add_owner_attribute
|
train
|
def add_owner_attribute(attribute)
prop = property(attribute)
otype = prop.type
hash = local_owner_property_hash
if hash.include?(otype) then
oa = hash[otype]
unless oa.nil? then
raise MetadataError.new("Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}")
end
hash[otype] = prop
else
add_owner(otype, prop.inverse, attribute)
end
end
|
ruby
|
{
"resource": ""
}
|
q7139
|
NRSER.AbstractMethodError.method_instance
|
train
|
def method_instance
lazy_var :@method_instance do
# Just drop a warning if we can't get the method object
logger.catch.warn(
"Failed to get method",
instance: instance,
method_name: method_name,
) do
instance.method method_name
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7140
|
GHULS.Lib.get_user_and_check
|
train
|
def get_user_and_check(user)
user_full = @octokit.user(user)
{
username: user_full[:login],
avatar: user_full[:avatar_url]
}
rescue Octokit::NotFound
return false
end
|
ruby
|
{
"resource": ""
}
|
q7141
|
GHULS.Lib.get_forks_stars_watchers
|
train
|
def get_forks_stars_watchers(repository)
{
forks: @octokit.forks(repository).length,
stars: @octokit.stargazers(repository).length,
watchers: @octokit.subscribers(repository).length
}
end
|
ruby
|
{
"resource": ""
}
|
q7142
|
GHULS.Lib.get_followers_following
|
train
|
def get_followers_following(username)
{
following: @octokit.following(username).length,
followers: @octokit.followers(username).length
}
end
|
ruby
|
{
"resource": ""
}
|
q7143
|
GHULS.Lib.get_user_langs
|
train
|
def get_user_langs(username)
repos = get_user_repos(username)
langs = {}
repos[:public].each do |r|
next if repos[:forks].include? r
repo_langs = @octokit.languages(r)
repo_langs.each do |l, b|
if langs[l].nil?
langs[l] = b
else
langs[l] += b
end
end
end
langs
end
|
ruby
|
{
"resource": ""
}
|
q7144
|
GHULS.Lib.get_org_langs
|
train
|
def get_org_langs(username)
org_repos = get_org_repos(username)
langs = {}
org_repos[:public].each do |r|
next if org_repos[:forks].include? r
repo_langs = @octokit.languages(r)
repo_langs.each do |l, b|
if langs[l].nil?
langs[l] = b
else
langs[l] += b
end
end
end
langs
end
|
ruby
|
{
"resource": ""
}
|
q7145
|
GHULS.Lib.get_color_for_language
|
train
|
def get_color_for_language(lang)
color_lang = @colors[lang]
color = color_lang['color']
if color_lang.nil? || color.nil?
return StringUtility.random_color_six
else
return color
end
end
|
ruby
|
{
"resource": ""
}
|
q7146
|
GHULS.Lib.get_language_percentages
|
train
|
def get_language_percentages(langs)
total = 0
langs.each { |_, b| total += b }
lang_percents = {}
langs.each do |l, b|
percent = self.class.calculate_percent(b, total.to_f)
lang_percents[l] = percent.round(2)
end
lang_percents
end
|
ruby
|
{
"resource": ""
}
|
q7147
|
YumRepo.Repomd.filelists
|
train
|
def filelists
fl = []
@repomd.xpath("/xmlns:repomd/xmlns:data[@type=\"filelists\"]/xmlns:location").each do |f|
fl << File.join(@url, f['href'])
end
fl
end
|
ruby
|
{
"resource": ""
}
|
q7148
|
Xpay.Payment.rewrite_request_block
|
train
|
def rewrite_request_block(auth_type="ST3DAUTH")
# set the required AUTH type
REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = auth_type
# delete term url and merchant name
ops = REXML::XPath.first(@request_xml, "//Operation")
["TermUrl", "MerchantName"].each { |e| ops.delete_element e }
# delete accept and user agent in customer info
customer_info = REXML::XPath.first(@request_xml, "//CustomerInfo")
["Accept", "UserAgent"].each { |e| customer_info.delete_element e }
# delete credit card details and add TransactionVerifier and TransactionReference from response xml
# CC details are not needed anymore as verifier and reference are sufficient
cc_details = REXML::XPath.first(@request_xml, "//CreditCard")
["Number", "Type", "SecurityCode", "StartDate", "ExpiryDate", "Issue"].each { |e| cc_details.delete_element e }
cc_details.add_element("TransactionVerifier").text = REXML::XPath.first(@response_xml, "//TransactionVerifier").text
cc_details.add_element("ParentTransactionReference").text = REXML::XPath.first(@response_xml, "//TransactionReference").text
# unless it is an AUTH request, add additional required info for a 3DAUTH request
unless auth_type == "AUTH"
pm_method = REXML::XPath.first(@request_xml, "//PaymentMethod")
threedsecure = pm_method.add_element("ThreeDSecure")
threedsecure.add_element("Enrolled").text = REXML::XPath.first(@response_xml, "//Enrolled").text
threedsecure.add_element("MD").text = REXML::XPath.first(@response_xml, "//MD").text rescue ""
end
true
end
|
ruby
|
{
"resource": ""
}
|
q7149
|
Skeletor.CLI.clean
|
train
|
def clean
print 'Are you sure you want to clean this project directory? (Y|n): '
confirm = $stdin.gets.chomp
if confirm != 'Y' && confirm != 'n'
puts 'Please enter Y or n'
elsif confirm == 'Y'
path = options[:directory] || Dir.pwd
Builder.clean path
end
end
|
ruby
|
{
"resource": ""
}
|
q7150
|
Layabout.FileUpload.wrap
|
train
|
def wrap(http_response)
OpenStruct.new.tap do |obj|
obj.code = http_response.code.to_i
obj.body = http_response.body
obj.headers = {}
http_response.each_header{|k,v| obj.headers[k] = v }
end
end
|
ruby
|
{
"resource": ""
}
|
q7151
|
Montage.OrderParser.clause_valid?
|
train
|
def clause_valid?
if @clause.is_a?(Hash)
@clause.flatten.find do |e|
return true unless (/\basc\b|\bdesc\b/).match(e).nil?
end
else
return true unless @clause.split.empty?
end
end
|
ruby
|
{
"resource": ""
}
|
q7152
|
Montage.OrderParser.parse_hash
|
train
|
def parse_hash
direction = clause.values.first
field = clause.keys.first.to_s
["$order_by", ["$#{direction}", field]]
end
|
ruby
|
{
"resource": ""
}
|
q7153
|
Montage.OrderParser.parse_string
|
train
|
def parse_string
direction = clause.split[1]
field = clause.split[0]
direction = "asc" unless %w(asc desc).include?(direction)
["$order_by", ["$#{direction}", field]]
end
|
ruby
|
{
"resource": ""
}
|
q7154
|
ZendeskTools.CleanSuspended.run
|
train
|
def run
@client.suspended_tickets.each do |suspended_ticket|
if should_delete?(suspended_ticket)
log.info "Deleting: #{suspended_ticket.subject}"
suspended_ticket.destroy
else
log.info "Keeping: #{suspended_ticket.subject}"
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7155
|
SimpleCLI.Command.summary
|
train
|
def summary
if @summary.nil?
match = Command::SummaryMatcher.match documentation
match.captures.first.strip if match
else
@summary
end
end
|
ruby
|
{
"resource": ""
}
|
q7156
|
HueBridge.LightBulb.set_color
|
train
|
def set_color(opts = {})
color = Color.new(opts)
response = put('state', color.to_h)
response_successful?(response)
end
|
ruby
|
{
"resource": ""
}
|
q7157
|
HueBridge.LightBulb.store_state
|
train
|
def store_state
response = get
success = !!(response.body =~ %r(state))
data = JSON.parse(response.body) if success
@state = data.fetch('state')
delete_forbidden_stats
success
end
|
ruby
|
{
"resource": ""
}
|
q7158
|
CruLib.Async.perform
|
train
|
def perform(id, method, *args)
if id
begin
self.class.find(id).send(method, *args)
rescue ActiveRecord::RecordNotFound
# If the record was deleted after the job was created, swallow it
end
else
self.class.send(method, *args)
end
end
|
ruby
|
{
"resource": ""
}
|
q7159
|
Gitolite.Utils.is_subset?
|
train
|
def is_subset?(array1, array2)
result = array1 & array2
(array2.length == result.length)
end
|
ruby
|
{
"resource": ""
}
|
q7160
|
Gitolite.Utils.gitolite_friendly
|
train
|
def gitolite_friendly(permission)
if permission.empty?
return nil
elsif permission.match(/^RWDP?/)
return "RW+"
elsif permission.match(/^RW/)
return "RW+"
elsif permission.match(/^R/)
return 'R'
else
return nil
end
end
|
ruby
|
{
"resource": ""
}
|
q7161
|
Bebox.EnvironmentWizard.create_new_environment
|
train
|
def create_new_environment(project_root, environment_name)
# Check if the environment exist
return error(_('wizard.environment.name_exist')%{environment: environment_name}) if Bebox::Environment.environment_exists?(project_root, environment_name)
# Environment creation
environment = Bebox::Environment.new(environment_name, project_root)
output = environment.create
ok _('wizard.environment.creation_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q7162
|
Bebox.EnvironmentWizard.remove_environment
|
train
|
def remove_environment(project_root, environment_name)
# Check if the environment exist
return error(_('wizard.environment.name_not_exist')%{environment: environment_name}) unless Bebox::Environment.environment_exists?(project_root, environment_name)
# Confirm deletion
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.environment.confirm_deletion'))
# Environment deletion
environment = Bebox::Environment.new(environment_name, project_root)
output = environment.remove
ok _('wizard.environment.deletion_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q7163
|
Asset.Item.write_cache
|
train
|
def write_cache
compressed.tap{|c| File.atomic_write(cache_path){|f| f.write(c)}}
end
|
ruby
|
{
"resource": ""
}
|
q7164
|
Asset.Item.compressed
|
train
|
def compressed
@compressed ||= case @type
when 'css'
Sass::Engine.new(joined, :syntax => :scss, :cache => false, :style => :compressed).render rescue joined
when 'js'
Uglifier.compile(joined, :mangle => false, :comments => :none) rescue joined
end
end
|
ruby
|
{
"resource": ""
}
|
q7165
|
Asset.Item.joined
|
train
|
def joined
@joined ||= files.map{|f| File.read(File.join(::Asset.path, @type, f))}.join
end
|
ruby
|
{
"resource": ""
}
|
q7166
|
Zomato2.Zomato.locations
|
train
|
def locations(params={})
args = [ :query, :lat, :lon, :count ]
params.each do |k,v|
if !args.include?(k)
raise ArgumentError.new 'Search term not allowed: ' + k.to_s
end
end
if !params.include?(:query)
raise ArgumentError.new '"query" term with location name is required'
end
results = get('locations', params)
if results.key?("location_suggestions")
results["location_suggestions"].map { |l| Location.new(self, l) }
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q7167
|
Zomato2.Zomato.restaurants
|
train
|
def restaurants(params={})
args = [ :entity_id, :entity_type, # location
:q, :start, :count, :lat, :lon,
:radius, :cuisines, :establishment_type,
:collection_id, :category, :sort, :order,
:start, :count ]
params.each do |k,v|
if !args.include?(k)
raise ArgumentError.new 'Search term not allowed: ' + k.to_s
end
end
if params[:count] && params[:count].to_i > 20
warn 'Count maxes out at 20'
end
# these filters are already city-specific
has_sub_city = params[:establishment_type] || params[:collection_id] || params[:cuisines]
if (has_sub_city && params[:q]) ||
(has_sub_city && params[:entity_type] == 'city') ||
(params[:q] && params[:entity_type] == 'city')
warn 'More than 2 different kinds of City searches cannot be combined'
end
results = get('search', params)
results['restaurants'].map { |e| Restaurant.new(self, e['restaurant']) }
end
|
ruby
|
{
"resource": ""
}
|
q7168
|
Resumator.Client.get
|
train
|
def get(object, options = {})
if options[:all_pages]
options.delete(:all_pages)
options[:page] = 1
out = []
begin
data = get(object, options)
out = out | data
options[:page] += 1
end while data.count >= 100
return out
else
if options[:id]
resp = @connection.get "#{object}/#{options[:id]}"
elsif options.size > 0
resp = @connection.get "#{object}#{Client.parse_options(options)}"
else
resp = @connection.get object
end
raise "Bad response: #{resp.status}" unless resp.status == 200
Client.mash(JSON.parse(resp.body))
end
end
|
ruby
|
{
"resource": ""
}
|
q7169
|
IRCSupport.Masks.matches_mask_array
|
train
|
def matches_mask_array(masks, strings, casemapping = :rfc1459)
results = {}
masks.each do |mask|
strings.each do |string|
if matches_mask(mask, string, casemapping)
results[mask] ||= []
results[mask] << string
end
end
end
return results
end
|
ruby
|
{
"resource": ""
}
|
q7170
|
ScopedSerializer.Scope.merge!
|
train
|
def merge!(scope)
@options.merge!(scope.options)
@attributes += scope.attributes
@associations.merge!(scope.associations)
@attributes.uniq!
self
end
|
ruby
|
{
"resource": ""
}
|
q7171
|
ScopedSerializer.Scope._association
|
train
|
def _association(args, default_options={})
return if options.nil?
options = args.first
if options.is_a?(Hash)
options = {}.merge(options)
name = options.keys.first
properties = options.delete(name)
@associations[name] = default_options.merge({ :include => properties }).merge(options)
elsif options.is_a?(Array)
options.each do |option|
association option
end
else
@associations[options] = args[1] || {}
end
end
|
ruby
|
{
"resource": ""
}
|
q7172
|
Pocus.Resource.get
|
train
|
def get(request_path, klass)
response = session.send_request('GET', path + request_path)
data = response.fetch(klass.tag)
resource = klass.new(data.merge(parent: self))
resource.assign_errors(response)
resource
end
|
ruby
|
{
"resource": ""
}
|
q7173
|
Pocus.Resource.reload
|
train
|
def reload
response = session.send_request('GET', path)
assign_attributes(response.fetch(self.class.tag))
assign_errors(response)
self
end
|
ruby
|
{
"resource": ""
}
|
q7174
|
MMETools.Enumerable.compose
|
train
|
def compose(*enumerables)
res=[]
enumerables.map(&:size).max.times do
tupla=[]
for enumerable in enumerables
tupla << enumerable.shift
end
res << (block_given? ? yield(tupla) : tupla)
end
res
end
|
ruby
|
{
"resource": ""
}
|
q7175
|
SpiderCore.FieldDSL.field
|
train
|
def field(display, pattern, opts = {}, &block)
actions << lambda {
action_for(:field, {display: display, pattern: pattern}, opts, &block)
}
end
|
ruby
|
{
"resource": ""
}
|
q7176
|
Encruby.Message.encrypt
|
train
|
def encrypt(message)
raise Error, "data must not be empty" if message.to_s.strip.empty?
# 1
@cipher.reset
@cipher.encrypt
aes_key = @cipher.random_key
aes_iv = @cipher.random_iv
encrypted = @cipher.update(message) + @cipher.final
# 2
rsa_encrypted_aes_key = @rsa.public_encrypt(aes_key)
rsa_encrypted_aes_iv = @rsa.public_encrypt(aes_iv)
# 3
content = rsa_encrypted_aes_key + rsa_encrypted_aes_iv + encrypted
# 4
hmac = hmac_signature(content)
content = Base64.encode64(hmac + content)
{ signature: hmac, content: content }
rescue OpenSSL::OpenSSLError => e
raise Error.new(e.message)
end
|
ruby
|
{
"resource": ""
}
|
q7177
|
Encruby.Message.decrypt
|
train
|
def decrypt(message, hash: nil)
# 0
message = Base64.decode64(message)
hmac = message[0..63] # 64 bits of hmac signature
case
when hash && hmac != hash
raise Error, "Provided hash mismatch for encrypted file!"
when hmac != hmac_signature(message[64..-1])
raise Error, "HMAC signature mismatch for encrypted file!"
end
# 1
rsa_encrypted_aes_key = message[64..319] # next 256 bits
rsa_encrypted_aes_iv = message[320..575] # next 256 bits
aes_encrypted_message = message[576..-1]
# 2
aes_key = @rsa.private_decrypt rsa_encrypted_aes_key
aes_iv = @rsa.private_decrypt rsa_encrypted_aes_iv
# 3
@cipher.reset
@cipher.decrypt
@cipher.key = aes_key
@cipher.iv = aes_iv
content = @cipher.update(aes_encrypted_message) + @cipher.final
{ signature: hmac, content: content }
rescue OpenSSL::OpenSSLError => e
raise Error.new(e.message)
end
|
ruby
|
{
"resource": ""
}
|
q7178
|
RefBiblio.Referencia.titulo
|
train
|
def titulo (titulo)
tit = titulo.split(' ')
tit.each do |word|
if word.length > 3
word.capitalize!
else
word.downcase!
end
if word == tit[0]
word.capitalize!
end
@titulo = tit.join(' ')
end
# Metodo para guardar el editorial de la referencia
# @param [editorial] editorial Editorial de la referencia a introducir
def editorial(editorial)
@editorial = editorial
end
# Metodo para guardar la fecha de publicacion de la referencia
# @param [publicacion] publicacion Fecha de publicacion de la referencia a introducir
def publicacion (publicacion)
@publicacion = publicacion
end
# Metodo para obtener el titulo de la referencia
# @return Titulo de la referencia
def get_titulo
@titulo
end
# Metodo para obtener el autor/autores de la referencia
# @return Autor/autores de la referencia
def get_autor
@autor
end
# Metodo para obtener el editorial de la referencia
# @return Editorial de la referencia
def get_editorial
@editorial
end
# Metodo para obtener la fecha de publicacion de la referencia
# @return Fecha de publicacion de la referencia
def get_publicacion
@publicacion
end
# Método con el que podemos usar el modulo Enumerable
# @param otro Otro elemento a comparar
# @return Devuelve valores entre -1 y 1 segun el orden
def <=> (otro)
if(@autor == otro.get_autor)
if(@publicacion == otro.get_publicacion)
if(@titulo == otro.get_titulo)
return 0
else
arr = [@titulo, otro.get_titulo]
arr.sort_by!{|t| t.downcase}
if(arr.first == @titulo)
return 1
end
return -1
end
elsif publicacion > otro.get_publicacion
return -1
else
return 1
end
else
arr = [@autor, otro.get_autor]
arr.sort_by!{|t| t.downcase}
if(arr.first == @autor)
return -1
end
return 1
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7179
|
RefBiblio.ArtPeriodico.to_s
|
train
|
def to_s
string = ""
string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << ". " << @editorial << ", pp. " << @formato << ", " << @paginas.to_s << " paginas" << "."
end
|
ruby
|
{
"resource": ""
}
|
q7180
|
RefBiblio.DocElectronico.to_s
|
train
|
def to_s
string = ""
string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << @formato << ". " << @editorial << ": " << @edicion << ". Disponible en: " << @url << " (" << Date::MONTHNAMES[get_fechacceso.month] << " " << get_fechacceso.day.to_s << ", " << get_fechacceso.year.to_s << "). "
end
|
ruby
|
{
"resource": ""
}
|
q7181
|
Evvnt.PathHelpers.nest_path_within_parent
|
train
|
def nest_path_within_parent(path, params)
return path unless params_include_parent_resource_id?(params)
params.symbolize_keys!
parent_resource = parent_resource_name(params)
parent_id = params.delete(parent_resource_param(params)).try(:to_s)
File.join(*[parent_resource, parent_id, path].compact).to_s
end
|
ruby
|
{
"resource": ""
}
|
q7182
|
DynamicRegistrar.Registrar.dispatch
|
train
|
def dispatch name, namespace = nil
responses = Hash.new
namespaces_to_search = namespace ? [namespace] : namespaces
namespaces_to_search.each do |namespace|
responses[namespace] ||= Hash.new
responses[namespace][name] = @registered_callbacks[namespace][name].call if @registered_callbacks[namespace].has_key?(name)
end
responses
end
|
ruby
|
{
"resource": ""
}
|
q7183
|
DynamicRegistrar.Registrar.registered?
|
train
|
def registered? name
registration_map = namespaces.map do |namespace|
registered_in_namespace? name, namespace
end
registration_map.any?
end
|
ruby
|
{
"resource": ""
}
|
q7184
|
EasyTag.MP3AttributeAccessors.read_all_tags
|
train
|
def read_all_tags(taglib, id3v2_frames, id3v1_tag = nil, **opts)
frames = []
id3v2_frames.each { |frame_id| frames += id3v2_frames(taglib, frame_id) }
data = []
# only check id3v1 if no id3v2 frames found
if frames.empty?
data << id3v1_tag(taglib, id3v1_tag) unless id3v1_tag.nil?
else
frames.each { |frame| data << data_from_frame(frame, **opts) }
end
data.compact
end
|
ruby
|
{
"resource": ""
}
|
q7185
|
RComp.Runner.run
|
train
|
def run(suite, type, options={})
@conf = Conf.instance
reporter = Reporter.new(type)
reporter.header
suite.each do |test|
case type
when :test
run_test(test) if expected_exists?(test)
when :generate
if expected_exists?(test)
run_test(test, true) if options[:overwrite]
else
run_test(test, true)
end
end
reporter.report(test)
end
reporter.summary
end
|
ruby
|
{
"resource": ""
}
|
q7186
|
RComp.Runner.cmp_output
|
train
|
def cmp_output(test)
# test out and err
if test.expected_out_exists? && test.expected_err_exists?
cmp_out(test)
cmp_err(test)
return :success if (test.out_result && test.err_result)
# test only out
elsif test.expected_out_exists?
cmp_out(test)
return :success if test.out_result
# test only err
else
cmp_err(test)
return :success if test.err_result
end
return :failed
end
|
ruby
|
{
"resource": ""
}
|
q7187
|
RComp.Runner.cmp_out
|
train
|
def cmp_out(test)
test.out_result = FileUtils.cmp(test.expected_out_path,
test.result_out_path)
end
|
ruby
|
{
"resource": ""
}
|
q7188
|
RComp.Runner.cmp_err
|
train
|
def cmp_err(test)
test.err_result = FileUtils.cmp(test.expected_err_path,
test.result_err_path)
end
|
ruby
|
{
"resource": ""
}
|
q7189
|
ScopedSerializer.BaseSerializer.default_root_key
|
train
|
def default_root_key(object_class)
if (serializer = ScopedSerializer.find_serializer_by_class(object_class))
root_key = serializer.find_scope(:default).options[:root]
end
if root_key
root_key.to_s
elsif object_class.respond_to?(:model_name)
object_class.model_name.element
else
object_class.name
end
end
|
ruby
|
{
"resource": ""
}
|
q7190
|
Garcon.TimerSet.post
|
train
|
def post(delay, *args, &task)
raise ArgumentError, 'no block given' unless block_given?
delay = TimerSet.calculate_delay!(delay)
mutex.synchronize do
return false unless running?
if (delay) <= 0.01
@task_executor.post(*args, &task)
else
@queue.push(Task.new(Garcon.monotonic_time + delay, args, task))
@timer_executor.post(&method(:process_tasks))
end
end
@condition.signal
true
end
|
ruby
|
{
"resource": ""
}
|
q7191
|
Garcon.TimerSet.process_tasks
|
train
|
def process_tasks
loop do
task = mutex.synchronize { @queue.peek }
break unless task
now = Garcon.monotonic_time
diff = task.time - now
if diff <= 0
# We need to remove the task from the queue before passing it to the
# executor, to avoid race conditions where we pass the peek'ed task
# to the executor and then pop a different one that's been added in
# the meantime.
#
# Note that there's no race condition between the peek and this pop -
# this pop could retrieve a different task from the peek, but that
# task would be due to fire now anyway (because @queue is a priority
# queue, and this thread is the only reader, so whatever timer is at
# the head of the queue now must have the same pop time, or a closer
# one, as when we peeked).
#
task = mutex.synchronize { @queue.pop }
@task_executor.post(*task.args, &task.op)
else
mutex.synchronize do
@condition.wait(mutex, [diff, 60].min)
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7192
|
Roroacms.Admin::AdministratorsController.create
|
train
|
def create
@admin = Admin.new(administrator_params)
respond_to do |format|
if @admin.save
profile_images(params, @admin)
Emailer.profile(@admin).deliver
format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.create.flash.success") }
else
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("generic.add_new_user")
@action = 'create'
flash[:error] = I18n.t('generic.validation.no_passed')
render action: "new"
}
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7193
|
Roroacms.Admin::AdministratorsController.edit
|
train
|
def edit
@admin = current_admin.id == params[:id].to_i ? @current_admin : Admin.find(params[:id])
# add breadcrumb and set title
set_title(I18n.t("controllers.admin.administrators.edit.title", username: @admin.username))
add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb")
# action for the form as both edit/new are using the same form.
@action = 'update'
# only allowed to edit the super user if you are the super user.
if @admin.overlord == 'Y' && @admin.id != session[:admin_id]
respond_to do |format|
flash[:error] = I18n.t("controllers.admin.administrators.edit.flash.error")
format.html { redirect_to admin_administrators_path }
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7194
|
Roroacms.Admin::AdministratorsController.update
|
train
|
def update
@admin = Admin.find(params[:id])
@admin.deal_with_cover params
respond_to do |format|
admin_passed =
if params[:admin][:password].blank?
@admin.update_without_password(administrator_params)
else
@admin.update_attributes(administrator_params)
end
if admin_passed
clear_cache
profile_images(params, @admin)
format.html { redirect_to edit_admin_administrator_path(@admin), notice: I18n.t("controllers.admin.administrators.update.flash.success") }
else
@action = 'update'
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb")
flash[:error] = I18n.t('generic.validation.no_passed')
render action: "edit"
}
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7195
|
Roroacms.Admin::AdministratorsController.destroy
|
train
|
def destroy
@admin = Admin.find(params[:id])
@admin.destroy if @admin.overlord == 'N'
respond_to do |format|
format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.destroy.flash.success") }
end
end
|
ruby
|
{
"resource": ""
}
|
q7196
|
Shells.PfShellWrapper.exec
|
train
|
def exec(*commands)
ret = ''
commands.each { |cmd| ret += shell.exec(cmd) }
ret + shell.exec('exec')
end
|
ruby
|
{
"resource": ""
}
|
q7197
|
Shells.PfShellWrapper.set_config_section
|
train
|
def set_config_section(section_name, values, message = '')
current_values = get_config_section(section_name)
changes = generate_config_changes("$config[#{section_name.to_s.inspect}]", current_values, values)
if changes&.any?
if message.to_s.strip == ''
message = "Updating #{section_name} section."
end
changes << "write_config(#{message.inspect});"
exec(*changes)
(changes.size - 1)
else
0
end
end
|
ruby
|
{
"resource": ""
}
|
q7198
|
Shells.PfShellWrapper.enable_cert_auth
|
train
|
def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub')
cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m
# get our cert unless the user provided a full cert for us.
unless public_key =~ cert_regex
public_key = File.expand_path(public_key)
if File.exist?(public_key)
public_key = File.read(public_key).to_s.strip
else
raise Shells::PfSenseCommon::PublicKeyNotFound
end
raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex
end
cfg = get_config_section 'system'
user_id = nil
user_name = options[:user].downcase
cfg['user'].each_with_index do |user,index|
if user['name'].downcase == user_name
user_id = index
authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip
unless authkeys == '' || authkeys =~ cert_regex
warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset."
authkeys = ''
end
if authkeys == ''
user['authorizedkeys'] = Base64.strict_encode64(public_key)
else
authkeys = authkeys.split("\n")
unless authkeys.include?(public_key)
authkeys << public_key unless authkeys.include?(public_key)
user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n"))
end
end
break
end
end
raise Shells::PfSenseCommon::UserNotFound unless user_id
set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}."
apply_user_config user_id
end
|
ruby
|
{
"resource": ""
}
|
q7199
|
BarkestCore.HtmlHelper.glyph
|
train
|
def glyph(name, size = nil)
size = size.to_s.downcase
if %w(small smaller big bigger).include?(size)
size = ' glyph-' + size
else
size = ''
end
"<i class=\"glyphicon glyphicon-#{h name}#{size}\"></i>".html_safe
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.