_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8900 | Kanpachi.ResourceList.named | train | def named(name)
resource = all.detect { |resource| resource.name == name }
if resource.nil?
raise UnknownResource, "Resource named #{name} doesn't exist"
else
resource
end
end | ruby | {
"resource": ""
} |
q8901 | EM::Xmpp.CertStore.trusted? | train | def trusted?(pem)
if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
@store.verify(cert).tap do |trusted|
@store.add_cert(cert) if trusted rescue nil
end
end
end | ruby | {
"resource": ""
} |
q8902 | EM::Xmpp.CertStore.certs | train | def certs
unless @@certs
pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
dir = @cert_directory
certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
certs = certs.map {|c| c.scan(pattern) }.flatten
certs.map! {|c| OpenSSL::X509::Certificate.new(c... | ruby | {
"resource": ""
} |
q8903 | StorageRoom.Image.url | train | def url(name = nil)
if name
if version_identifiers.include?(name.to_s)
self[:@versions][name.to_s][:@url]
else
raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})"
end
else
self[:@url]
end
end | ruby | {
"resource": ""
} |
q8904 | Iord.Fields.field_attribute | train | def field_attribute(attr)
return 'id' if attr == :_id
# default, simply return name
return attr unless attr.is_a? Hash
# else, Hash
return attr[:object] if attr.has_key? :object
return attr[:array] if attr.has_key? :array
return attr[:value] if attr.has... | ruby | {
"resource": ""
} |
q8905 | Faker.Taxonomy.lookup | train | def lookup(code)
TAXONOMY.select {|t| t.code.eql?(code) }.first
end | ruby | {
"resource": ""
} |
q8906 | Kanpachi.ErrorList.add | train | def add(error)
if @list.key? error.name
raise DuplicateError, "An error named #{error.name} already exists"
end
@list[error.name] = error
end | ruby | {
"resource": ""
} |
q8907 | Lotto.Draw.draw | train | def draw
drawns = []
@options[:include].each { |n| drawns << n } unless @options[:include].nil?
count = @options[:include] ? @options[:pick] - @options[:include].count : @options[:pick]
count.times { drawns << pick(drawns) }
drawns
end | ruby | {
"resource": ""
} |
q8908 | Lotto.Draw.basket | train | def basket
numbers = (1..@options[:of])
numbers = numbers.reject { |n| @options[:include].include? n } unless @options[:include].nil?
numbers = numbers.reject { |n| @options[:exclude].include? n } unless @options[:exclude].nil?
numbers
end | ruby | {
"resource": ""
} |
q8909 | Checkdin.Activities.activities | train | def activities(options={})
response = connection.get do |req|
req.url "activities", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q8910 | Digistore24.Notification.signature | train | def signature
# Remove 'sha_sign' key from request params and concatenate all
# key value pairs
params = payload.to_h
.reject { |key, value| key == :sha_sign }
.reject { |key, value| value == '' || value == false }.sort
.map { | key, value| "#{key}=#{value}#{passphrase}" }.join... | ruby | {
"resource": ""
} |
q8911 | Edoors.Board.process_p | train | def process_p p
@viewer.receive_p p if @viewer
if p.action!=Edoors::ACT_ERROR and p.action!=Edoors::ACT_PASS_THROUGH
p2 = @postponed[p.link_value] ||= p
return if p2==p
@postponed.delete p.link_value
p,p2 = p2,p if p.action==Edoors:... | ruby | {
"resource": ""
} |
q8912 | TCOMethod.BlockExtractor.determine_offsets | train | def determine_offsets(block, source)
tokens = Ripper.lex(source)
start_offset, start_token = determine_start_offset(block, tokens)
expected_match = start_token == :on_kw ? :on_kw : :on_rbrace
end_offset = determine_end_offset(block, tokens, source, expected_match)
[start_offset, end_offset... | ruby | {
"resource": ""
} |
q8913 | ExtendModelAt.Extention.method_missing | train | def method_missing(m, *args, &block)
column_name = m.to_s.gsub(/\=$/, '')
raise ExtendModelAt::InvalidColumn, "#{column_name} not exist" if @static == true and not (@columns.try(:keys).try(:include?, column_name.to_sym) )
# If the method don't finish with "=" is fore read
if m !~ /\=$/
s... | ruby | {
"resource": ""
} |
q8914 | ExtendModelAt.Extention.get_adapter | train | def get_adapter(column, value)
if @columns[column.to_sym][:type] == String
return :to_s
elsif @columns[column.to_sym][:type] == Fixnum
return :to_i if value.respond_to? :to_i
elsif @columns[column.to_sym][:type] == Float
return :to_f if value.respond_to? :to_f
elsif @colu... | ruby | {
"resource": ""
} |
q8915 | ExtendModelAt.Extention.get_defaults_values | train | def get_defaults_values(options = {})
defaults_ = {}
options[:columns].each do |column, config|
defaults_[column.to_s] = @columns[column.to_sym][:default] || nil
end
defaults_
end | ruby | {
"resource": ""
} |
q8916 | Checkdin.PointAccountEntries.point_account_entries | train | def point_account_entries(options={})
response = connection.get do |req|
req.url "point_account_entries", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q8917 | Fetch.Request.process! | train | def process!(body, url, effective_url)
before_process!
body = parse!(body)
@process_callback.call(body, url, effective_url) if @process_callback
after_process!
rescue => e
error!(e)
end | ruby | {
"resource": ""
} |
q8918 | GroupDocsSignatureCloud.SignatureApi.get_qr_codes_with_http_info | train | def get_qr_codes_with_http_info()
@api_client.config.logger.debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client.config.debugging
# resource path
local_var_path = '/signature/qrcodes'
# query parameters
query_params = {}
# header parameters
header_params ... | ruby | {
"resource": ""
} |
q8919 | GroupDocsSignatureCloud.SignatureApi.post_verification_collection_with_http_info | train | def post_verification_collection_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest
@api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging
# verify the requi... | ruby | {
"resource": ""
} |
q8920 | Nokogiri::Decorators::XBEL.Entry.desc= | train | def desc=(value)
node = at './desc'
node ||= add_child Nokogiri::XML::Node.new('desc', document)
node.content = value
end | ruby | {
"resource": ""
} |
q8921 | Nokogiri::Decorators::XBEL.Entry.added= | train | def added=(value)
set_attribute 'added', case value
when Time; value.strftime '%Y-%m-%d'
when String; value
else
raise ArgumentError
end
end | ruby | {
"resource": ""
} |
q8922 | Empyrean.TweetParser.parse | train | def parse(tweets)
retdict = {
mentions: {},
hashtags: {},
clients: {},
smileys: {},
times_of_day: [0] * 24,
tweet_count: 0,
retweet_count: 0,
selftweet_count: 0,
}
tweets.each do |tweet|
parsed_tweet = self.parse_one tweet
... | ruby | {
"resource": ""
} |
q8923 | Fb.HTTPRequest.run | train | def run
if response.is_a? @expected_response
self.class.on_response.call(self, response)
response.tap do
parse_response!
end
else
raise HTTPError.new(error_message, response: response)
end
end | ruby | {
"resource": ""
} |
q8924 | BitMagic.Bits.read | train | def read(name, field = nil)
field ||= self.field
if name.is_a?(Integer)
field.read_field(name)
elsif bits = @field_list[name]
field.read_field(bits)
end
end | ruby | {
"resource": ""
} |
q8925 | BitMagic.Bits.write | train | def write(name, target_value)
if name.is_a?(Symbol)
self.write(@field_list[name], target_value)
elsif name.is_a?(Integer)
self.update self.field.write_bits(name => @options[:bool_caster].call(target_value))
elsif name.respond_to?(:[]) and target_value.respond_to?(:[])
bits = {}... | ruby | {
"resource": ""
} |
q8926 | MassShootings.Shooting.as_json | train | def as_json(_=nil)
json = {'id' => id}
json['allegedShooters'] = alleged_shooters unless alleged_shooters.nil?
json.merge(
'casualties' => casualties.stringify_keys,
'date' => date.iso8601,
'location' => location,
'references' => references.map(&:to_s))
end | ruby | {
"resource": ""
} |
q8927 | SimilarityTree.SimilarityTree.prune | train | def prune(nodes)
nodes.each do |node|
node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold)
end
end | ruby | {
"resource": ""
} |
q8928 | Redhead.String.headers! | train | def headers!(hash)
changing = headers.select { |header| hash.has_key?(header.key) }
# modifies its elements!
changing.each do |header|
new_values = hash[header.key]
header.raw = new_values[:raw] if new_values[:raw]
header.key = new_values[:key] if new_values[:key]
end
... | ruby | {
"resource": ""
} |
q8929 | Easymongo.Document.method_missing | train | def method_missing(name, *args, &block)
return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '='
end | ruby | {
"resource": ""
} |
q8930 | AndFeathers.Sugar.dir | train | def dir(name, mode = 16877, &block)
name_parts = name.split(::File::SEPARATOR)
innermost_child_name = name_parts.pop
if name_parts.empty?
Directory.new(name, mode).tap do |directory|
add_directory(directory)
block.call(directory) if block
end
else
i... | ruby | {
"resource": ""
} |
q8931 | AndFeathers.Sugar.file | train | def file(name, mode = 33188, &content)
content ||= NO_CONTENT
name_parts = name.split(::File::SEPARATOR)
file_name = name_parts.pop
if name_parts.empty?
File.new(name, mode, content).tap do |file|
add_file(file)
end
else
dir(name_parts.join(::File::SEPA... | ruby | {
"resource": ""
} |
q8932 | Tropo.Message.request_xml | train | def request_xml
request_params = @params.dup
token = request_params.delete("token")
xml = ""
request_params.each do |key, value|
xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>"
end
"<sessions><token>#{token}</token>#{xml}</sessions>"
end | ruby | {
"resource": ""
} |
q8933 | Shamu.Attributes.to_attributes | train | def to_attributes( only: nil, except: nil )
self.class.attributes.each_with_object({}) do |(name, options), attrs|
next if ( only && !match_attribute?( only, name ) ) || ( except && match_attribute?( except, name ) )
next unless serialize_attribute?( name, options )
attrs[name] = send( na... | ruby | {
"resource": ""
} |
q8934 | Rsxml.Namespace.compact_attr_qnames | train | def compact_attr_qnames(ns_stack, attrs)
Hash[attrs.map do |name,value|
[compact_qname(ns_stack, name), value]
end]
end | ruby | {
"resource": ""
} |
q8935 | Rsxml.Namespace.find_namespace_uri | train | def find_namespace_uri(ns_stack, prefix, uri_check=nil)
tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}
uri = tns[prefix] if tns
raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check
uri
end | ruby | {
"resource": ""
} |
q8936 | Rsxml.Namespace.undeclared_namespace_bindings | train | def undeclared_namespace_bindings(ns_stack, ns_explicit)
Hash[ns_explicit.map do |prefix,uri|
[prefix, uri] if !find_namespace_uri(ns_stack, prefix, uri)
end.compact]
end | ruby | {
"resource": ""
} |
q8937 | Rsxml.Namespace.exploded_namespace_declarations | train | def exploded_namespace_declarations(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[[prefix, "xmlns"], uri]
end
end]
end | ruby | {
"resource": ""
} |
q8938 | Rsxml.Namespace.namespace_attributes | train | def namespace_attributes(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[["xmlns", prefix].join(":"), uri]
end
end]
end | ruby | {
"resource": ""
} |
q8939 | Rsxml.Namespace.merge_namespace_bindings | train | def merge_namespace_bindings(ns1, ns2)
m = ns1.clone
ns2.each do |k,v|
raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m.has_key?(k) && m[k]!=v
m[k]=v
end
m
end | ruby | {
"resource": ""
} |
q8940 | Caliph.Shell.spawn_process | train | def spawn_process(command_line)
host_stdout, cmd_stdout = IO.pipe
host_stderr, cmd_stderr = IO.pipe
pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr)
cmd_stdout.close
cmd_stderr.close
return pid, host_stdout, host_st... | ruby | {
"resource": ""
} |
q8941 | Caliph.Shell.execute | train | def execute(command_line)
result = collect_result(command_line, *spawn_process(command_line))
result.wait
result
end | ruby | {
"resource": ""
} |
q8942 | Caliph.Shell.run_as_replacement | train | def run_as_replacement(*args, &block)
command_line = normalize_command_line(*args, &block)
report "Ceding execution to: "
report command_line.string_format
Process.exec(command_line.command_environment, command_line.command)
end | ruby | {
"resource": ""
} |
q8943 | Caliph.Shell.run_detached | train | def run_detached(*args, &block)
command_line = normalize_command_line(*args, &block)
pid, out, err = spawn_process(command_line)
Process.detach(pid)
return collect_result(command_line, pid, out, err)
end | ruby | {
"resource": ""
} |
q8944 | Scram.Holder.can? | train | def can? action, target
target = target.to_s if target.is_a? Symbol
action = action.to_s
# Checks policies in priority order for explicit allow or deny.
policies.sort_by(&:priority).reverse.each do |policy|
opinion = policy.can?(self, action, target)
return opinion.to_bool if %i... | ruby | {
"resource": ""
} |
q8945 | SectionsRails.Section.referenced_sections | train | def referenced_sections recursive = true
result = PartialParser.find_sections partial_content
# Find all sections within the already known sections.
if recursive
i = -1
while (i += 1) < result.size
Section.new(result[i]).referenced_sections(false).each do |referenced_section... | ruby | {
"resource": ""
} |
q8946 | SectionsRails.Section.render | train | def render &block
raise "Section #{folder_filepath} doesn't exist." unless Dir.exists? folder_filepath
result = []
render_assets result if Rails.application.config.assets.compile
render_partial result, &block
result.join("\n").html_safe
end | ruby | {
"resource": ""
} |
q8947 | ChainOptions.Option.new_value | train | def new_value(*args, &block)
value = value_from_args(args, &block)
value = if incremental
incremental_value(value)
else
filter_value(transformed_value(value))
end
if value_valid?(value)
self.custom_value = value
elsif invalid.... | ruby | {
"resource": ""
} |
q8948 | ChainOptions.Option.to_h | train | def to_h
PARAMETERS.each_with_object({}) do |param, hash|
next if send(param).nil?
hash[param] = send(param)
end
end | ruby | {
"resource": ""
} |
q8949 | ChainOptions.Option.value_from_args | train | def value_from_args(args, &block)
return block if ChainOptions::Util.blank?(args) && block && allow_block
flat_value(args)
end | ruby | {
"resource": ""
} |
q8950 | ChainOptions.Option.flat_value | train | def flat_value(args)
return args.first if args.is_a?(Enumerable) && args.count == 1
args
end | ruby | {
"resource": ""
} |
q8951 | ChainOptions.Option.transformed_value | train | def transformed_value(value)
return value unless transform
transformed = Array(value).map(&transform)
value.is_a?(Enumerable) ? transformed : transformed.first
end | ruby | {
"resource": ""
} |
q8952 | MissingText.Writer.get_entry_for | train | def get_entry_for(entry, language)
if entry.length > 1
entry_string = get_entry_for_rec(entry[1..-1], language, hashes[language][entry[0]])
else
entry_string = hashes[language][entry[0]]
end
if entry_string.kind_of?(Array)
entry_string = entry_string.map(&:inspect).join(... | ruby | {
"resource": ""
} |
q8953 | Redlander.Parsing.from | train | def from(content, options = {})
format = options[:format].to_s
mime_type = options[:mime_type] && options[:mime_type].to_s
type_uri = options[:type_uri] && options[:type_uri].to_s
base_uri = options[:base_uri] && options[:base_uri].to_s
content = Uri.new(content) if content.is_a?(URI)
... | ruby | {
"resource": ""
} |
q8954 | Cathode.IndexRequest.model | train | def model
if @resource_tree.size > 1
parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"]
model = @resource_tree.first.model.find(parent_model_id)
@resource_tree.drop(1).each do |resource|
model = model.send resource.name
end
model
el... | ruby | {
"resource": ""
} |
q8955 | Cathode.IndexRequest.default_action_block | train | def default_action_block
proc do
all_records = model
if allowed?(:paging) && params[:page]
page = params[:page]
per_page = params[:per_page] || 10
lower_bound = (per_page - 1) * page
upper_bound = lower_bound + per_page - 1
body all_records[lower... | ruby | {
"resource": ""
} |
q8956 | Simulator.Equation.evaluate_in | train | def evaluate_in(context, periods = [])
sandbox = Sandbox.new context, periods
sandbox.instance_eval &@equation_block
end | ruby | {
"resource": ""
} |
q8957 | Rufus::Jig.Couch.all | train | def all(opts={})
opts = opts.dup
# don't touch the original
path = adjust('_all_docs')
opts[:include_docs] = true if opts[:include_docs].nil?
adjust_params(opts)
keys = opts.delete(:keys)
return [] if keys && keys.empty?
res = if keys
opts[:cache] = :with... | ruby | {
"resource": ""
} |
q8958 | Rufus::Jig.Couch.attach | train | def attach(doc_id, doc_rev, attachment_name, data, opts=nil)
if opts.nil?
opts = data
data = attachment_name
attachment_name = doc_rev
doc_rev = doc_id['_rev']
doc_id = doc_id['_id']
end
attachment_name = attachment_name.gsub(/\//, '%2F')
ct = opts[:con... | ruby | {
"resource": ""
} |
q8959 | Rufus::Jig.Couch.detach | train | def detach(doc_id, doc_rev, attachment_name=nil)
if attachment_name.nil?
attachment_name = doc_rev
doc_rev = doc_id['_rev']
doc_id = doc_id['_id']
end
attachment_name = attachment_name.gsub(/\//, '%2F')
path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")
... | ruby | {
"resource": ""
} |
q8960 | Rufus::Jig.Couch.on_change | train | def on_change(opts={}, &block)
query = {
'feed' => 'continuous',
'heartbeat' => opts[:heartbeat] || 20_000 }
#'since' => 0 } # that's already the default
query['include_docs'] = true if block.arity > 2
query = query.map { |k, v| "#{k}=#{v}" }.join('&')
socket = TCPSocke... | ruby | {
"resource": ""
} |
q8961 | Rufus::Jig.Couch.nuke_design_documents | train | def nuke_design_documents
docs = get('_all_docs')['rows']
views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) }
views.each { |v| delete(v['id'], v['value']['rev']) }
end | ruby | {
"resource": ""
} |
q8962 | Rufus::Jig.Couch.query | train | def query(path, opts={})
opts = opts.dup
# don't touch the original
raw = opts.delete(:raw)
path = if DESIGN_PATH_REGEX.match(path)
path
else
doc_id, view = path.split(':')
path = "_design/#{doc_id}/_view/#{view}"
end
path = adjust(path)
adj... | ruby | {
"resource": ""
} |
q8963 | Rufus::Jig.Couch.query_for_docs | train | def query_for_docs(path, opts={})
res = query(path, opts.merge(:include_docs => true))
if res.nil?
nil
elsif opts[:raw]
res
else
res.collect { |row| row['doc'] }.uniq
end
end | ruby | {
"resource": ""
} |
q8964 | Motivosity.Client.send_appreciation! | train | def send_appreciation!(user_id, opts = {})
params = { "toUserID" => user_id }
params["companyValueID"] = opts[:company_value_id] if opts[:company_value_id]
params["amount"] = opts[:amount] if opts[:amount]
params["note"] = opts[:note] if opts[:note]
params["privateAppreciation"] = opts[:pr... | ruby | {
"resource": ""
} |
q8965 | NsOptions.NamespaceData.define | train | def define(&block)
if block && block.arity > 0
block.call @ns
elsif block
@ns.instance_eval(&block)
end
@ns
end | ruby | {
"resource": ""
} |
q8966 | Tay.Packager.extension_id | train | def extension_id
raise Tay::PrivateKeyNotFound.new unless private_key_exists?
public_key = OpenSSL::PKey::RSA.new(File.read(full_key_path)).public_key.to_der
hash = Digest::SHA256.hexdigest(public_key)[0...32]
hash.unpack('C*').map{ |c| c < 97 ? c + 49 : c + 10 }.pack('C*')
end | ruby | {
"resource": ""
} |
q8967 | Tay.Packager.write_new_key | train | def write_new_key
File.open(full_key_path, 'w') do |f|
f.write OpenSSL::PKey::RSA.generate(1024).export()
end
end | ruby | {
"resource": ""
} |
q8968 | Rsxml.Xml.traverse | train | def traverse(element, visitor, context = Visitor::Context.new)
ns_bindings = namespace_bindings_from_defs(element.namespace_definitions)
context.ns_stack.push(ns_bindings)
eelement, eattrs = explode_element(element)
begin
visitor.element(context, eelement, eattrs, ns_bindings) do
... | ruby | {
"resource": ""
} |
q8969 | FentonShell.ConfigFile.config_file_create | train | def config_file_create(global_options, options)
config_directory_create(global_options)
file = "#{global_options[:directory]}/config"
options.store(:fenton_server_url, global_options[:fenton_server_url])
content = config_generation(options)
File.write(file, content)
[true, 'ConfigF... | ruby | {
"resource": ""
} |
q8970 | FentonShell.ConfigFile.config_generation | train | def config_generation(options)
config_contents = {}
config_options = options.keys.map(&:to_sym).sort.uniq
config_options.delete(:password)
config_options.each do |config_option|
config_contents.store(config_option.to_sym, options[config_option])
end
config_contents.store(:d... | ruby | {
"resource": ""
} |
q8971 | Conify.Helpers.format_with_bang | train | def format_with_bang(message)
return message if !message.is_a?(String)
return '' if message.to_s.strip == ''
" ! " + message.encode('utf-8', 'binary', invalid: :replace, undef: :replace).split("\n").join("\n ! ")
end | ruby | {
"resource": ""
} |
q8972 | Conify.Helpers.to_table | train | def to_table(data, headers)
column_lengths = []
gutter = 2
table = ''
# Figure out column widths based on longest string in each column (including the header string)
headers.each { |header|
width = data.map { |_| _[header] }.max_by(&:length).length
width = header.length i... | ruby | {
"resource": ""
} |
q8973 | Warden.Proxy.clear_strategies_cache! | train | def clear_strategies_cache!(*args)
scope, opts = _retrieve_scope_and_opts(args)
@winning_strategies.delete(scope)
@strategies[scope].each do |k, v|
v.clear! if args.empty? || args.include?(k)
end
end | ruby | {
"resource": ""
} |
q8974 | Warden.Proxy.set_user | train | def set_user(user, opts = {})
scope = (opts[:scope] ||= @config.default_scope)
# Get the default options from the master configuration for the given scope
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
opts[:event] ||= :set_user
@users[scope] = user
if opts[:store] != f... | ruby | {
"resource": ""
} |
q8975 | Lono.Core.env_from_profile | train | def env_from_profile(aws_profile)
data = YAML.load_file("#{Lono.root}/config/settings.yml")
env = data.find do |_env, setting|
setting ||= {}
profiles = setting['aws_profiles']
profiles && profiles.include?(aws_profile)
end
env.first if env
end | ruby | {
"resource": ""
} |
q8976 | HashControl.Validator.require | train | def require(*keys)
permitted_keys.merge keys
required_keys = keys.to_set
unless (missing_keys = required_keys - hash_keys).empty?
error "required #{terms} #{missing_keys.to_a} missing" + postscript
end
self
end | ruby | {
"resource": ""
} |
q8977 | Redlander.Node.datatype | train | def datatype
if instance_variable_defined?(:@datatype)
@datatype
else
@datatype = if literal?
rdf_uri = Redland.librdf_node_get_literal_value_datatype_uri(rdf_node)
rdf_uri.null? ? XmlSchema.datatype_of("") : URI.parse(Redland.librdf_uri_to_string(... | ruby | {
"resource": ""
} |
q8978 | Redlander.Node.value | train | def value
if resource?
uri
elsif blank?
Redland.librdf_node_get_blank_identifier(rdf_node).force_encoding("UTF-8")
else
v = Redland.librdf_node_get_literal_value(rdf_node).force_encoding("UTF-8")
v << "@#{lang}" if lang
XmlSchema.instantiate(v, datatype)
e... | ruby | {
"resource": ""
} |
q8979 | Repository.Base.delete | train | def delete(identifier)
RecordDeleter.new(identifier: identifier, dao: dao, factory: factory)
.delete
end | ruby | {
"resource": ""
} |
q8980 | WillPaginateRenderers.Gmail.window | train | def window
base = @collection.offset
high = base + @collection.per_page
high = @collection.total_entries if high > @collection.total_entries
# TODO: What's the best way to allow customization of this text, particularly "of"?
tag(:span, " #{base + 1} - #{high} of #{@collection.total_entrie... | ruby | {
"resource": ""
} |
q8981 | Echonest.Artist.news | train | def news(options = { results: 1 })
response = get_response(results: options[:results], name: @name)
response[:news].collect do |b|
Blog.new(name: b[:name], site: b[:site], url: b[:url])
end
end | ruby | {
"resource": ""
} |
q8982 | SycLink.Website.list_links | train | def list_links(args = {})
if args.empty?
links
else
links.select { |link| link.match? args }
end
end | ruby | {
"resource": ""
} |
q8983 | SycLink.Website.merge_links_on | train | def merge_links_on(attribute, concat_string = ',')
links_group_by(attribute)
.select { |key, link_list| links.size > 1 }
.map do |key, link_list|
merge_attributes = Link::ATTRS - [attribute]
link_list.first
.update(Hash[extract_columns(link_lis... | ruby | {
"resource": ""
} |
q8984 | SycLink.Website.links_group_by | train | def links_group_by(attribute, linkz = links)
linkz.map { |link| { key: link.send(attribute), link: link } }
.group_by { |entry| entry[:key] }
.each { |key, link| link.map! { |l| l[:link] }}
end | ruby | {
"resource": ""
} |
q8985 | SycLink.Website.links_duplicate_on | train | def links_duplicate_on(attribute, separator)
links.map do |link|
link.send(attribute).split(separator).collect do |value|
link.dup.update(Hash[attribute, value])
end
end.flatten
end | ruby | {
"resource": ""
} |
q8986 | SycLink.Website.link_attribute_list | train | def link_attribute_list(attribute, separator = nil)
links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort
end | ruby | {
"resource": ""
} |
q8987 | DCPU16.CPU.run | train | def run
@started_at = Time.now
max_cycles = 1
while true do
if @cycle < max_cycles
step
else
diff = Time.now - @started_at
max_cycles = (diff * @clock_cycle)
end
end
end | ruby | {
"resource": ""
} |
q8988 | Imwukong.Base.wk_api_info | train | def wk_api_info(api_method='')
api_method ||= ''
fail 'Invalid wukong api' unless api_method == '' || api_method =~ WK_API_FORMAT
if api_method.size > 0
m = api_method.to_s.match(/^wk_([a-zA-Z0-9]+)_(.+)/)
method_group = m[1].singularize
method_name = m[2]
end... | ruby | {
"resource": ""
} |
q8989 | Cornerstone.Post.update_counter_cache | train | def update_counter_cache
self.discussion.reply_count = Post.where(:discussion_id => self.discussion.id)
.count - 1
self.discussion.save
end | ruby | {
"resource": ""
} |
q8990 | Cornerstone.Post.anonymous_or_user_attr | train | def anonymous_or_user_attr(attr)
unless self.user_id.nil?
mthd = "user_#{attr.to_s}"
# TODO: rails caching is messing this relationship up.
# will .user work even if model name is something else. e.g. AdminUser ??
self.user.send(attr)
else
case attr
when... | ruby | {
"resource": ""
} |
q8991 | Taxonifi::Export.OboNomenclature.export | train | def export()
super
f = new_output_file('obo_nomenclature.obo')
# header
f.puts 'format-version: 1.2'
f.puts "date: #{@time}"
f.puts 'saved-by: someone'
f.puts 'auto-generated-by: Taxonifi'
f.puts 'synonymtypedef: COMMONNAME "common name"'
f.puts 'synonymtype... | ruby | {
"resource": ""
} |
q8992 | Templatr.Field.has_unique_name | train | def has_unique_name
invalid = false
if template
invalid ||= template.common_fields.any? {|field| field.name.downcase == self.name.downcase && field != self }
invalid ||= template.default_fields.any? {|field| field.name.downcase == self.name.downcase && field != self }
else
scop... | ruby | {
"resource": ""
} |
q8993 | Templatr.Field.disambiguate_fields | train | def disambiguate_fields
if name_changed? # New, Updated
fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name)
fields.update_all(:disambiguate => fields.many?)
end
if name_was # Updated, Destroyed
fields = self.class.specific.where("LOWER(name) = LOWER(?)", se... | ruby | {
"resource": ""
} |
q8994 | FlexibleAccessibility.RouteProvider.app_routes_as_hash | train | def app_routes_as_hash
Rails.application.routes.routes.each do |route|
controller = route.defaults[:controller]
next if controller.nil?
key = controller.split('/').map(&:camelize).join('::')
routes[key] ||= []
routes[key] << route.defaults[:action]
end
end | ruby | {
"resource": ""
} |
q8995 | BcaStatement.Client.get_statement | train | def get_statement(start_date = '2016-08-29', end_date = '2016-09-01')
return nil unless @access_token
@timestamp = Time.now.iso8601(3)
@start_date = start_date.to_s
@end_date = end_date.to_s
@path = "/banking/v3/corporates/"
@relative_url = "#{@path}#{@corporate_id}/accounts/#{@acc... | ruby | {
"resource": ""
} |
q8996 | BcaStatement.Client.balance | train | def balance
return nil unless @access_token
begin
@timestamp = Time.now.iso8601(3)
@relative_url = "/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}"
response = RestClient.get("#{@base_url}#{@relative_url}",
"Content-Type": 'application/json',
... | ruby | {
"resource": ""
} |
q8997 | SimpleGeocoder.Geocoder.geocode! | train | def geocode!(address, options = {})
response = call_geocoder_service(address, options)
if response.is_a?(Net::HTTPOK)
return JSON.parse response.body
else
raise ResponseError.new response
end
end | ruby | {
"resource": ""
} |
q8998 | SimpleGeocoder.Geocoder.find_location | train | def find_location(address)
result = geocode(address)
if result['status'] == 'OK'
return result['results'][0]['geometry']['location']
else
latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/
if ad... | ruby | {
"resource": ""
} |
q8999 | PSQL.Database.object | train | def object( object_name )
object = objects.find do |obj|
obj[ 'name' ] == object_name
end
if !object
raise "Database #{name} does not have an object named '#{object_name}'."
end
klass = PSQL.const_get object[ 'type' ].capitalize
klass.new object[ 'name' ], name
... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.