_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q7700
|
Mellon.Keychain.read
|
train
|
def read(key)
command "find-generic-password", "-g", "-l", key do |info, password_info|
[Utils.parse_info(info), Utils.parse_contents(password_info)]
end
rescue CommandError => e
raise unless e.message =~ ENTRY_MISSING
nil
end
|
ruby
|
{
"resource": ""
}
|
q7701
|
Mellon.Keychain.write
|
train
|
def write(key, data, options = {})
info = Utils.build_info(key, options)
command "add-generic-password",
"-a", info[:account_name],
"-s", info[:service_name],
"-l", info[:label],
"-D", info[:kind],
"-C", info[:type],
"-T", "", # which applications have access (none)
"-U", # upsert
"-w", data
end
|
ruby
|
{
"resource": ""
}
|
q7702
|
Mellon.Keychain.delete
|
train
|
def delete(key, options = {})
info = Utils.build_info(key, options)
command "delete-generic-password",
"-a", info[:account_name],
"-s", info[:service_name],
"-l", info[:label],
"-D", info[:kind],
"-C", info[:type]
end
|
ruby
|
{
"resource": ""
}
|
q7703
|
Typekit.Family.variation
|
train
|
def variation(id)
variations.select { |v| v.id.split(':').last == id }.first
end
|
ruby
|
{
"resource": ""
}
|
q7704
|
Framework.Application.load_application_files
|
train
|
def load_application_files
if %w(development test).include?(env.to_s)
config['autoload_paths'].each(&method(:autoreload_constants))
autoreload_yml
end
config['autoload_paths'].each(&method(:require_dependencies))
end
|
ruby
|
{
"resource": ""
}
|
q7705
|
ComicVine.Resource.fetch!
|
train
|
def fetch!
obj = ComicVine::API.get_details_by_url(self.api_detail_url)
self.methods.each do |m|
# Look for methods that can be set (i.e. ends with a =)
if m.to_s =~ /^(?!_)([\w\d\_]+)=$/
# Save our method symbols in a more readable fashion
get_m = $1.to_sym
set_m = m
# Skip setting ids, as this should be handled by the classes when setting the children objects if needed
next if get_m.to_s =~ /\_ids?$/ || set_m.to_s =~ /attributes/
# Verify the new object has a get method and it is not nil or empty
if self.respond_to?(set_m) && obj.respond_to?(get_m) && !obj.method(get_m).call.nil?
# Now set the method to the new value
self.method(set_m).call obj.method(get_m).call
end
end
end
self
end
|
ruby
|
{
"resource": ""
}
|
q7706
|
Pluckers.Base.configure_query
|
train
|
def configure_query
@query_to_pluck = @records
@attributes_to_pluck = [{ name: @query_to_pluck.primary_key.to_sym, sql: "\"#{@query_to_pluck.table_name}\".#{@query_to_pluck.primary_key}" }]
@results = {}
@klass_reflections = @query_to_pluck.reflections.with_indifferent_access
pluck_reflections = @options[:reflections] || {}
# Validate that all relations exists in the model
if (missing_reflections = pluck_reflections.symbolize_keys.keys - @klass_reflections.symbolize_keys.keys).any?
raise ArgumentError.new("Plucker reflections '#{missing_reflections.to_sentence}', are missing in #{@records.klass}")
end
end
|
ruby
|
{
"resource": ""
}
|
q7707
|
Pluckers.Base.build_results
|
train
|
def build_results
# Now we uinq the attributes
@attributes_to_pluck.uniq!{|f| f[:name] }
# Obtain both the names and SQL columns
names_to_pluck = @attributes_to_pluck.map{|f| f[:name] }
sql_to_pluck = @attributes_to_pluck.map{|f| f[:sql] }
# And perform the real ActiveRecord pluck.
pluck_records(sql_to_pluck).each_with_index do |record, index|
# After the pluck we have to create the hash for each record.
# If there's only a field we will not receive an array. But we need it
# so we built it.
record = [record] unless record.is_a? Array
# Now we zip it with the attribute names and create a hash. If we have
# have a record: [1, "Test title 1", "Test text 1"] and the
# names_to_pluck are [:id, :title, :text] we will end with {:id=>1,
# :title=>"Test title 1", :text=>"Test text 1"}
attributes_to_return = Hash[names_to_pluck.zip(record)]
# Now we store it in the results hash
@results[attributes_to_return[:id]] = attributes_to_return
end
end
|
ruby
|
{
"resource": ""
}
|
q7708
|
Bisques.AwsRequestAuthorization.signing_key
|
train
|
def signing_key
digest = "SHA256"
kDate = OpenSSL::HMAC.digest(digest, "AWS4" + credentials.aws_secret, request_datestamp)
kRegion = OpenSSL::HMAC.digest(digest, kDate, region)
kService = OpenSSL::HMAC.digest(digest, kRegion, service)
OpenSSL::HMAC.digest(digest, kService, "aws4_request")
end
|
ruby
|
{
"resource": ""
}
|
q7709
|
Bisques.AwsRequestAuthorization.canonical_headers
|
train
|
def canonical_headers
hash = headers.dup
hash["host"] ||= Addressable::URI.parse(url).host
hash = hash.map{|name,value| [name.downcase,value]}
hash.reject!{|name,value| name == "authorization"}
hash.sort
end
|
ruby
|
{
"resource": ""
}
|
q7710
|
MigrationBundler.Actions.git
|
train
|
def git(commands={})
if commands.is_a?(Symbol)
run "git #{commands}"
else
commands.each do |cmd, options|
run "git #{cmd} #{options}"
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7711
|
PuppetDBQuery.PuppetDB.node_properties
|
train
|
def node_properties
result = {}
api_nodes.each do |data|
next if data['deactivated']
# in '/v3/nodes' we must take 'name'
name = data['certname']
values = data.dup
%w[deactivated certname].each { |key| values.delete(key) }
result[name] = values
end
result
end
|
ruby
|
{
"resource": ""
}
|
q7712
|
PuppetDBQuery.PuppetDB.nodes_update_facts_since
|
train
|
def nodes_update_facts_since(timestamp)
ts = (timestamp.is_a?(String) ? Time.iso8601(ts) : timestamp)
node_properties.delete_if do |_k, data|
# in '/v3/nodes' we must take 'facts-timestamp'
!data["facts_timestamp"] || Time.iso8601(data["facts_timestamp"]) < ts
end.keys
end
|
ruby
|
{
"resource": ""
}
|
q7713
|
PuppetDBQuery.PuppetDB.single_node_facts
|
train
|
def single_node_facts(node)
json = get_json("#{@nodes_url}/#{node}/facts", 10)
return nil if json.include?("error")
Hash[json.map { |data| [data["name"], data["value"]] }]
end
|
ruby
|
{
"resource": ""
}
|
q7714
|
PuppetDBQuery.PuppetDB.facts
|
train
|
def facts
json = get_json(@facts_url, 60)
result = {}
json.each do |fact|
data = result[fact["certname"]]
result[fact["certname"]] = data = {} unless data
data[fact["name"]] = fact["value"]
end
result
end
|
ruby
|
{
"resource": ""
}
|
q7715
|
Swirl.AWS.call
|
train
|
def call(action, query={}, &blk)
call!(action, expand(query)) do |code, data|
case code
when 200
response = compact(data)
when 400...500
messages = if data["Response"]
Array(data["Response"]["Errors"]).map {|_, e| e["Message"] }
elsif data["ErrorResponse"]
Array(data["ErrorResponse"]["Error"]["Code"])
end
raise InvalidRequest, messages.join(",")
else
msg = "unexpected response #{code} -> #{data.inspect}"
raise InvalidRequest, msg
end
if blk
blk.call(response)
else
response
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7716
|
Words.PureWordnetConnection.open!
|
train
|
def open!
raise BadWordnetDataset, "Failed to locate the wordnet database. Please ensure it is installed and that if it resides at a custom path that path is given as an argument when constructing the Words object." if @wordnet_path.nil?
@connected = true
# try and open evocations too
evocation_path = @data_path + 'evocations.dmp'
File.open(evocation_path, 'r') do |file|
@evocations = Marshal.load file.read
end if evocation_path.exist?
return nil
end
|
ruby
|
{
"resource": ""
}
|
q7717
|
Words.PureWordnetConnection.homographs
|
train
|
def homographs(term, use_cache = true)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
# Ensure that the term is either in the cache. If not, locate and add it if possable.
cache_ensure_from_wordnet(term, use_cache)
# We should either have the word in cache now or nowt... we should now change that into homograph input format (we do this here to improve performance during the cacheing performed above)
cached_entry_to_homograph_hash(term)
end
|
ruby
|
{
"resource": ""
}
|
q7718
|
Words.PureWordnetConnection.synset
|
train
|
def synset(synset_id)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
pos = synset_id[0,1]
File.open(@wordnet_path + "data.#{SHORT_TO_POS_FILE_TYPE[pos]}","r") do |file|
file.seek(synset_id[1..-1].to_i)
data_line, gloss = file.readline.strip.split(" | ")
lexical_filenum, synset_type, word_count, *data_parts = data_line.split(" ")[1..-1]
words = Array.new(word_count.to_i(16)).map { "#{data_parts.shift}.#{data_parts.shift}" }
relations = Array.new(data_parts.shift.to_i).map { "#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}" }
return { "synset_id" => synset_id, "lexical_filenum" => lexical_filenum, "synset_type" => synset_type, "words" => words.join('|'), "relations" => relations.join('|'), "gloss" => gloss.strip }
end
end
|
ruby
|
{
"resource": ""
}
|
q7719
|
Words.PureWordnetConnection.evocations
|
train
|
def evocations(synset_id)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
if defined? @evocations
raw_evocations = @evocations[synset_id + "s"]
{ 'relations' => raw_evocations[0], 'means' => raw_evocations[1], 'medians' => raw_evocations[2]} unless raw_evocations.nil?
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q7720
|
Hey.Account.create
|
train
|
def create name, password, params = {}
params.merge!({
new_account_username: name,
new_account_passcode: password
})
post 'accounts', params
end
|
ruby
|
{
"resource": ""
}
|
q7721
|
Threadz.Batch.when_done
|
train
|
def when_done(&block)
call_block = false
@job_lock.synchronize do
if completed?
call_block = true
else
@when_done_callbacks << block
end
end
yield if call_block
end
|
ruby
|
{
"resource": ""
}
|
q7722
|
RightDevelop::Commands.Git.prune
|
train
|
def prune(options={})
puts describe_prune(options)
puts "Fetching latest branches and tags from remotes"
@git.fetch_all(:prune => true)
branches = @git.branches(:all => true)
#Filter by name prefix
branches = branches.select { |x| x =~ options[:only] } if options[:only]
branches = branches.reject { |x| x =~ options[:except] } if options[:except]
#Filter by location (local/remote)
if options[:local] && !options[:remote]
branches = branches.local
elsif options[:remote] && !options[:local]
branches = branches.remote
elsif options[:remote] && options[:local]
raise ArgumentError, "Cannot specify both --local and --remote!"
end
#Filter by merge status
if options[:merged]
puts "Checking merge status of #{branches.size} branches; please be patient"
branches = branches.merged(options[:merged])
end
old = {}
branches.each do |branch|
latest = @git.log(branch, :tail => 1).first
timestamp = latest.timestamp
if timestamp < options[:age] &&
old[branch] = timestamp
end
end
if old.empty?
STDERR.puts "No branches found; try different options"
exit -2
end
puts
all_by_prefix = branches.group_by { |b| b.name.split(NAME_SPLIT_CHARS).first }
all_by_prefix.each_pair do |prefix, branches|
old_in_group = branches.select { |b| old.key?(b) }
next if old_in_group.empty?
old_in_group = old_in_group.sort { |a, b| old[a] <=> old[b] }
puts prefix
puts '-' * prefix.length
old_in_group.each do |b|
puts "\t" + b.display(40) + "\t" + time_ago_in_words(old[b])
end
puts
end
unless options[:force]
return unless prompt("Delete all #{old.size} branches above?", true)
end
old.each do |branch, timestamp|
branch.delete
puts " deleted #{branch}"
end
end
|
ruby
|
{
"resource": ""
}
|
q7723
|
RightDevelop::Commands.Git.describe_prune
|
train
|
def describe_prune(options)
statement = ['Pruning']
if options[:remote]
statement << 'remote'
elsif options[:local]
statement << 'local'
end
statement << 'branches'
if options[:age]
statement << "older than #{time_ago_in_words(options[:age])}"
end
if options[:merged]
statement << "that are fully merged into #{options[:merged]}"
end
if options[:only]
naming = "with a name containing '#{options[:only]}'"
if options[:except]
naming << " (but not '#{options[:except]}')"
end
statement << naming
end
statement.join(' ')
end
|
ruby
|
{
"resource": ""
}
|
q7724
|
RightDevelop::Commands.Git.prompt
|
train
|
def prompt(p, yes_no=false)
puts #newline for newline's sake!
loop do
print p, ' '
line = STDIN.readline.strip
if yes_no
return true if line =~ YES
return false if line =~ NO
else
return line
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7725
|
RightDevelop::Commands.Git.parse_age
|
train
|
def parse_age(str)
ord, word = str.split(/[. ]+/, 2)
ord = Integer(ord)
word.gsub!(/s$/, '')
ago = nil
TIME_INTERVALS.each do |pair|
mag, term = pair.first, pair.last
if term == word
ago = Time.at(Time.now.to_i - ord * mag)
break
end
end
if ago
ago
else
raise ArgumentError, "Cannot parse '#{str}' as an age"
end
end
|
ruby
|
{
"resource": ""
}
|
q7726
|
SquashMatrix.Client.get_save_params
|
train
|
def get_save_params
{
player: @player,
email: @email,
password: @password,
suppress_errors: @suppress_errors,
timeout: @timeout,
user_agent: @user_agent,
cookie: get_cookie_string,
expires: @expires.to_s,
proxy_addr: @proxy_addr,
proxy_port: @proxy_port
}.delete_if { |_k, v| v.nil? }
end
|
ruby
|
{
"resource": ""
}
|
q7727
|
SquashMatrix.Client.get_club_info
|
train
|
def get_club_info(id = nil)
return unless id.to_i.positive?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::CLUB_PATH.gsub(':id', id.to_s)
)
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_club_info(res.body)
end
handle_http_request(uri, success_proc)
end
|
ruby
|
{
"resource": ""
}
|
q7728
|
SquashMatrix.Client.get_player_results
|
train
|
def get_player_results(id = nil)
return unless id.to_i.positive?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::PLAYER_RESULTS_PATH.gsub(':id', id.to_s),
query: SquashMatrix::Constants::PLAYER_RSULTS_QUERY
)
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_player_results(res.body)
end
handle_http_request(uri, success_proc)
end
|
ruby
|
{
"resource": ""
}
|
q7729
|
SquashMatrix.Client.get_search_results
|
train
|
def get_search_results(query = nil,
squash_only: false,
racquetball_only: false)
return if query.to_s.empty?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::SEARCH_RESULTS_PATH
)
query_params = {
Criteria: query,
SquashOnly: squash_only,
RacquetballOnly: racquetball_only
}
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_search_results(res.body)
end
handle_http_request(uri, success_proc,
is_get_request: false,
query_params: query_params)
end
|
ruby
|
{
"resource": ""
}
|
q7730
|
Hardmock.Mock.expects
|
train
|
def expects(*args, &block)
expector = Expector.new(self,@control,@expectation_builder)
# If there are no args, we return the Expector
return expector if args.empty?
# If there ARE args, we set up the expectation right here and return it
expector.send(args.shift.to_sym, *args, &block)
end
|
ruby
|
{
"resource": ""
}
|
q7731
|
Download.Object.file_path
|
train
|
def file_path
self.path= File.join(Dir.pwd, uri_file_name) unless path
if File.directory?(path)
self.path= File.join(self.path, uri_file_name)
end
self.path
end
|
ruby
|
{
"resource": ""
}
|
q7732
|
Download.Object.start
|
train
|
def start(hash={})
set_multi(hash)
File.delete(file_path) if File.exist?(file_path)
File.open(file_path, 'wb') do |file_obj|
Kernel.open(*[url,options].compact) do |fin|
while (buf = fin.read(8192))
file_obj << buf
end
end
end
return file_path
end
|
ruby
|
{
"resource": ""
}
|
q7733
|
FixedWidthFileValidator.FieldValidator.validate
|
train
|
def validate(record, field_name, bindings = {})
if validations
validations.collect do |validation|
unless valid_value?(validation, record, field_name, bindings)
FieldValidationError.new(validation, record, field_name, pos, width)
end
end.compact
elsif record && record[field_name]
# when no validation rules exist for the field, just check if the field exists in the record
[]
else
raise "found field value nil in #{record} field #{field_name}, shouldn't be possible?"
end
end
|
ruby
|
{
"resource": ""
}
|
q7734
|
ParcelApi.Label.details
|
train
|
def details(label_id)
details_url = File.join(LABEL_URL, "#{label_id}.json")
response = connection.get details_url
details = response.parsed.tap {|d| d.delete('success')}
OpenStruct.new(details)
end
|
ruby
|
{
"resource": ""
}
|
q7735
|
Akasha.EventRouter.connect!
|
train
|
def connect!(repository)
repository.subscribe do |aggregate_id, event|
route(event.name, aggregate_id, **event.data)
end
end
|
ruby
|
{
"resource": ""
}
|
q7736
|
CalendarizeHelper.MonthlyCalendarBuilder.days_range
|
train
|
def days_range
ws = Date::DAYS_INTO_WEEK[@options[:week_start]]
(ws...ws+number_of_days_per_week).map{ |d| d % 7 }
end
|
ruby
|
{
"resource": ""
}
|
q7737
|
CalendarizeHelper.MonthlyCalendarBuilder.row_to_day
|
train
|
def row_to_day(i, j)
starting_wday = @day_start.wday - 1
starting_wday = 6 if starting_wday < 0
# day without taking into account the :week_start so every 1st
# of the month is on a :monday on case [0, 0]
base = (i * 7) + j
# we add the :week_start
base += Date::DAYS_INTO_WEEK[@options[:week_start]]
# we adjust with the starting day of the month
base -= starting_wday
base += 1
return nil if base < 1 || base > days_in_month(@day_start)
base
end
|
ruby
|
{
"resource": ""
}
|
q7738
|
Typekit.Variation.fetch
|
train
|
def fetch(attribute)
family_id, variation_id = @id.split(':')
mass_assign Client.get("/families/#{family_id}/#{variation_id}")
attribute ? instance_variable_get("@#{attribute}") : self
end
|
ruby
|
{
"resource": ""
}
|
q7739
|
Scale.API.method_missing
|
train
|
def method_missing(m, *array)
endpoint = Scale.descendants(Scale::Endpoints::Endpoint).find { |e| e.match? m }
return endpoint.new(self, *array).process if endpoint
super
end
|
ruby
|
{
"resource": ""
}
|
q7740
|
Bourgeois.Presenter.execute_helper
|
train
|
def execute_helper(block, opts)
if_condition = execute_helper_condition(opts[:if])
unless_condition = !execute_helper_condition(opts[:unless], false)
block.call if if_condition && unless_condition
end
|
ruby
|
{
"resource": ""
}
|
q7741
|
Rattler::Runtime.ParseNode.method_missing
|
train
|
def method_missing(symbol, *args)
(args.empty? and labeled.has_key?(symbol)) ? labeled[symbol] : super
end
|
ruby
|
{
"resource": ""
}
|
q7742
|
ProfitBricks.Volume.create_snapshot
|
train
|
def create_snapshot(options = {})
response = ProfitBricks.request(
method: :post,
path: "/datacenters/#{datacenterId}/volumes/#{id}/create-snapshot",
headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },
expects: 202,
body: URI.encode_www_form(options)
)
ProfitBricks::Snapshot.new(response)
end
|
ruby
|
{
"resource": ""
}
|
q7743
|
Rack::AcceptHeaders.Header.parse_range_params
|
train
|
def parse_range_params(params)
params.split(';').inject({'q' => '1'}) do |m, p|
k, v = p.split('=', 2)
m[k.strip] = v.strip if v
m
end
end
|
ruby
|
{
"resource": ""
}
|
q7744
|
Rack::AcceptHeaders.Header.normalize_qvalue
|
train
|
def normalize_qvalue(q)
(q == 1 || q == 0) && q.is_a?(Float) ? q.to_i : q
end
|
ruby
|
{
"resource": ""
}
|
q7745
|
DuckMap.RouteFilter.match_any?
|
train
|
def match_any?(data = nil, values = [])
unless data.blank?
unless values.kind_of?(Array)
# wow, this worked!!??
# values was not an array, so, add values to a new array and assign back to values
values = [values]
end
values.each do |value|
if value.kind_of?(String) && (data.to_s.downcase.eql?(value.downcase) || value.eql?("all"))
return true
elsif value.kind_of?(Symbol) && (data.downcase.to_sym.eql?(value) || value.eql?(:all))
return true
elsif value.kind_of?(Regexp) && data.match(value)
return true
end
end
end
return false
end
|
ruby
|
{
"resource": ""
}
|
q7746
|
CachedBelongsTo.ClassMethods.cached_belongs_to
|
train
|
def cached_belongs_to(*args)
caches = Array(args[1].delete(:caches))
association = belongs_to(*args)
create_cached_belongs_to_child_callbacks(caches, association)
create_cached_belongs_to_parent_callbacks(caches, association)
end
|
ruby
|
{
"resource": ""
}
|
q7747
|
PBIO.Delimited.read
|
train
|
def read(klass)
size = Delimited.read_uvarint(io)
klass.decode io.read(size) unless size.zero?
end
|
ruby
|
{
"resource": ""
}
|
q7748
|
Panoptimon.Monitor._dirjson
|
train
|
def _dirjson (x)
x = Pathname.new(x)
x.entries.find_all {|f| f.to_s =~ /\.json$/i}.
map {|f| x + f}
end
|
ruby
|
{
"resource": ""
}
|
q7749
|
Rattler.HelperMethods.compile_parser
|
train
|
def compile_parser(*args)
options = @@defaults.dup
grammar = nil
for arg in args
case arg
when Hash then options.merge!(arg)
when String then grammar = arg
end
end
base_class = options.delete(:class) ||
(Rattler::Runtime::const_get @@parser_types[options[:type]])
Rattler::Compiler.compile_parser(base_class, grammar, options)
end
|
ruby
|
{
"resource": ""
}
|
q7750
|
AnySMS.Configuration.default_backend=
|
train
|
def default_backend=(value)
raise ArgumentError, "default_backend must be a symbol!" unless value.is_a? Symbol
unless @backends.keys.include? value
raise ArgumentError, "Unregistered backend cannot be set as default!"
end
@default_backend = value
end
|
ruby
|
{
"resource": ""
}
|
q7751
|
AnySMS.Configuration.register_backend
|
train
|
def register_backend(key, classname, params = {})
raise ArgumentError, "backend key must be a symbol!" unless key.is_a? Symbol
unless classname.class == Class
raise ArgumentError, "backend class must be class (not instance or string)"
end
unless classname.method_defined? :send_sms
raise ArgumentError, "backend must provide method send_sms"
end
define_backend(key, classname, params)
end
|
ruby
|
{
"resource": ""
}
|
q7752
|
CConfig.Config.fetch
|
train
|
def fetch
cfg = File.file?(@default) ? YAML.load_file(@default) : {}
local = fetch_local
hsh = strict_merge_with_env(default: cfg, local: local, prefix: @prefix)
hsh.extend(::CConfig::HashUtils::Extensions)
hsh.defaults = cfg
hsh
end
|
ruby
|
{
"resource": ""
}
|
q7753
|
CConfig.Config.fetch_local
|
train
|
def fetch_local
if File.file?(@local)
# Check for bad user input in the local config.yml file.
local = YAML.load_file(@local)
raise FormatError unless local.is_a?(::Hash)
local
else
{}
end
end
|
ruby
|
{
"resource": ""
}
|
q7754
|
ValidatesCaptcha.FormHelper.captcha_challenge
|
train
|
def captcha_challenge(object_name, options = {})
options.symbolize_keys!
object = options.delete(:object)
sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
ValidatesCaptcha.provider.render_challenge sanitized_object_name, object, options
end
|
ruby
|
{
"resource": ""
}
|
q7755
|
ValidatesCaptcha.FormHelper.captcha_field
|
train
|
def captcha_field(object_name, options = {})
options.delete(:id)
hidden_field(object_name, :captcha_challenge, options) + text_field(object_name, :captcha_solution, options)
end
|
ruby
|
{
"resource": ""
}
|
q7756
|
ValidatesCaptcha.FormHelper.regenerate_captcha_challenge_link
|
train
|
def regenerate_captcha_challenge_link(object_name, options = {}, html_options = {})
options.symbolize_keys!
object = options.delete(:object)
sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
ValidatesCaptcha.provider.render_regenerate_challenge_link sanitized_object_name, object, options, html_options
end
|
ruby
|
{
"resource": ""
}
|
q7757
|
DuckMap.SitemapObject.sitemap_capture_segments
|
train
|
def sitemap_capture_segments(segment_mappings = {}, segments = [])
values = {}
# do nothing if there are no segments to work on
if segments.kind_of?(Array)
# first, look for mappings
unless segment_mappings.blank?
segments.each do |key|
attribute_name = segment_mappings[key.to_sym].blank? ? key : segment_mappings[key.to_sym]
if self.respond_to?(attribute_name)
values[key] = self.send(attribute_name)
end
end
end
# second, look for attributes that have not already been found.
segments.each do |key|
unless values.has_key?(key)
if self.respond_to?(key)
values[key] = self.send(key)
end
end
end
end
return values
end
|
ruby
|
{
"resource": ""
}
|
q7758
|
BELParser.ASTGenerator.each
|
train
|
def each # rubocop:disable MethodLength
if block_given?
line_number = 1
expanded_line = nil
map_lines(@io.each_line.lazy).each do |line|
if line.end_with?(LINE_CONTINUATOR)
expanded_line = "#{expanded_line}#{line.chomp(LINE_CONTINUATOR)}"
else
expanded_line = "#{expanded_line}#{line}"
ast_results = []
PARSERS.map do |parser|
parser.parse(expanded_line) { |ast| ast_results << ast }
end
yield [line_number, expanded_line, ast_results]
line_number += 1
expanded_line = nil
end
end
else
enum_for(:each)
end
end
|
ruby
|
{
"resource": ""
}
|
q7759
|
EtherPing.Client.ping
|
train
|
def ping(data, timeout = 1)
if data.kind_of? Numeric
data = "\0" * data
end
# Pad data to have at least 64 bytes.
data += "\0" * (64 - data.length) if data.length < 64
ping_packet = [@dest_mac, @source_mac, @ether_type, data].join
response = nil
receive_ts = nil
send_ts = nil
begin
Timeout.timeout timeout do
send_ts = Time.now
@socket.send ping_packet, 0
response = @socket.recv ping_packet.length * 2
receive_ts = Time.now
end
rescue Timeout::Error
response = nil
end
return false unless response
response_packet = [@source_mac, @dest_mac, @ether_type, data].join
response == response_packet ? receive_ts - send_ts :
[response, response_packet]
end
|
ruby
|
{
"resource": ""
}
|
q7760
|
Dominion.DomainSuffixRule.=~
|
train
|
def =~(domain)
labels.zip(domain.labels).all? { |r, d| ["*", d].include? r }
end
|
ruby
|
{
"resource": ""
}
|
q7761
|
TimeExt.Iterations.each
|
train
|
def each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => false), &block)
end
|
ruby
|
{
"resource": ""
}
|
q7762
|
TimeExt.Iterations.beginning_of_each
|
train
|
def beginning_of_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => false, :beginning_of => true), &block)
end
|
ruby
|
{
"resource": ""
}
|
q7763
|
TimeExt.Iterations.map_each
|
train
|
def map_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => true), &block)
end
|
ruby
|
{
"resource": ""
}
|
q7764
|
TimeExt.Iterations.map_beginning_of_each
|
train
|
def map_beginning_of_each(unit, options = {}, &block)
iterate(unit, options.merge(:map_result => true, :beginning_of => true), &block)
end
|
ruby
|
{
"resource": ""
}
|
q7765
|
Mellon.Utils.build_info
|
train
|
def build_info(key, options = {})
options = DEFAULT_OPTIONS.merge(options)
note_type = TYPES.fetch(options.fetch(:type, :note).to_s)
account_name = options.fetch(:account_name, "")
service_name = options.fetch(:service_name, key)
label = options.fetch(:label, service_name)
{
account_name: account_name,
service_name: service_name,
label: label,
kind: note_type.fetch(:kind),
type: note_type.fetch(:type),
}
end
|
ruby
|
{
"resource": ""
}
|
q7766
|
Mellon.Utils.parse_contents
|
train
|
def parse_contents(password_string)
unpacked = password_string[/password: 0x([a-f0-9]+)/i, 1]
password = if unpacked
[unpacked].pack("H*")
else
password_string[/password: "(.+)"/m, 1]
end
password ||= ""
parsed = Plist.parse_xml(password.force_encoding("".encoding))
if parsed and parsed["NOTE"]
parsed["NOTE"]
else
password
end
end
|
ruby
|
{
"resource": ""
}
|
q7767
|
Maliq.FileUtils.split
|
train
|
def split(path, marker=nil)
marker ||= SPLIT_MARKER
content = File.read(path)
filename = File.basename(path, '.*')
yfm, content = retrieveYFM(content)
contents = [filename] + content.split(marker)
prev_name = filename
contents.each_slice(2).with({}) do |(fname, text), h|
fname = prev_name = create_filename(prev_name) if fname.strip.empty?
h[fname.strip] = yfm + text
end
end
|
ruby
|
{
"resource": ""
}
|
q7768
|
Akasha.Aggregate.apply_events
|
train
|
def apply_events(events)
events.each do |event|
method_name = event_handler(event)
public_send(method_name, event.data) if respond_to?(method_name)
end
@revision = events.last&.revision.to_i if events.last.respond_to?(:revision)
end
|
ruby
|
{
"resource": ""
}
|
q7769
|
RubyPandoc.Dependencies.get_pandoc
|
train
|
def get_pandoc
return if has_pandoc
Dir.mktmpdir do |dir|
Dir.chdir(dir) do
system("wget #{PANDOC_URL} -O pandoc.deb")
system("sudo dpkg -i pandoc.deb")
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7770
|
XcodeBuilder.XcodeBuilder.build
|
train
|
def build
clean unless @configuration.skip_clean
# update the long version number with the date
@configuration.timestamp_plist if @configuration.timestamp_build
print "Building Project..."
success = xcodebuild @configuration.build_arguments, "build"
raise "** BUILD FAILED **" unless success
puts "Done"
end
|
ruby
|
{
"resource": ""
}
|
q7771
|
XcodeBuilder.XcodeBuilder.pod_dry_run
|
train
|
def pod_dry_run
print "Pod dry run..."
repos = resolved_repos.join ","
result = system "pod lib lint #{@configuration.podspec_file} --allow-warnings --sources=#{repos}"
raise "** Pod dry run failed **" if !result
puts "Done"
end
|
ruby
|
{
"resource": ""
}
|
q7772
|
Hetchy.Dataset.percentile
|
train
|
def percentile(perc)
if perc > 100.0 || perc < 0.0
raise InvalidPercentile, "percentile must be between 0.0 and 100.0"
end
return 0.0 if data.empty?
rank = (perc / 100.0) * (size + 1)
return data[0] if rank < 1
return data[-1] if rank > size
return data[rank - 1] if rank == Integer(rank)
weighted_average_for(rank)
end
|
ruby
|
{
"resource": ""
}
|
q7773
|
Hetchy.Dataset.weighted_average_for
|
train
|
def weighted_average_for(rank)
above = data[rank.to_i]
below = data[rank.to_i - 1]
fractional = rank - rank.floor
below + ((above - below) * fractional)
end
|
ruby
|
{
"resource": ""
}
|
q7774
|
JBLAS.MatrixConvertMixin.to_s
|
train
|
def to_s(fmt=nil, coljoin=', ', rowjoin='; ')
if fmt
x = rows_to_a
'[' + x.map do |r|
if Enumerable === r
r.map {|e| sprintf(fmt, e)}.join(coljoin)
else
sprintf(fmt, r)
end
end.join(rowjoin) + ']'
else
toString
end
end
|
ruby
|
{
"resource": ""
}
|
q7775
|
CRA.Services.by_name_and_dob
|
train
|
def by_name_and_dob(lname, fname, year, month, day)
body = self.gov_talk_request({
service: 'GetDataUsingCriteriaParameter',
message: 'CRAGetDataUsingCriteria',
class: 'CRAGetDataUsingCriteria',
params: {
LastName: lname,
FirstName: fname,
Year: year,
Month: month,
Day: day,
}
})
CRA::PassportInfo.list_with_hash(body)
end
|
ruby
|
{
"resource": ""
}
|
q7776
|
CRA.Services.by_id_card
|
train
|
def by_id_card(private_number, id_card_serial, id_card_numb)
body = self.gov_talk_request({
service: 'GetDataUsingPrivateNumberAndIdCardParameter',
message: 'GetDataUsingPrivateNumberAndCard',
class: 'GetDataUsingPrivateNumberAndCard',
params: {
PrivateNumber: private_number,
IdCardSerial: id_card_serial,
IdCardNumber: id_card_numb,
}
})
CRA::PassportInfo.init_with_hash(body)
end
|
ruby
|
{
"resource": ""
}
|
q7777
|
CRA.Services.by_passport
|
train
|
def by_passport(private_number, passport)
body = self.gov_talk_request({
service: 'FetchPersonInfoByPassportNumberUsingCriteriaParameter',
message: 'CRA_FetchInfoByPassportCriteria',
class: 'CRA_FetchInfoByPassportCriteria',
params: {
PrivateNumber: private_number,
Number: passport
}
})
CRA::PassportInfo.init_with_hash(body)
end
|
ruby
|
{
"resource": ""
}
|
q7778
|
CRA.Services.address_by_name
|
train
|
def address_by_name(parent_id, name)
body = self.gov_talk_request({
service: 'AddrFindeAddressByNameParameter',
message: 'CRA_AddrFindeAddressByName',
class: 'CRA_AddrFindeAddressByName',
params: {
Id: parent_id,
Word: name,
}
})
CRA::Address.list_from_hash(body['ArrayOfResults']['Results'])
end
|
ruby
|
{
"resource": ""
}
|
q7779
|
CRA.Services.address_by_parent
|
train
|
def address_by_parent(parent_id)
body = self.gov_talk_request({
message: 'CRA_AddrGetNodesByParentID',
class: 'CRA_AddrGetNodesByParentID',
params: {
long: parent_id,
}
})
CRA::AddressNode.list_from_hash(body['ArrayOfNodeInfo']['NodeInfo'])
end
|
ruby
|
{
"resource": ""
}
|
q7780
|
CRA.Services.address_info
|
train
|
def address_info(id)
body = self.gov_talk_request({
message: 'CRA_AddrGetAddressInfoByID',
class: 'CRA_AddrGetAddressInfoByID',
params: {
long: id,
}
})
# puts body.to_s
CRA::AddressInfo.init_from_hash(body['AddressInfo'])
end
|
ruby
|
{
"resource": ""
}
|
q7781
|
CRA.Services.persons_at_address
|
train
|
def persons_at_address(address_id)
body = self.gov_talk_request({
message: 'CRA_GetPersonsAtAddress',
class: 'CRA_GetPersonsAtAddress',
params: {
long: address_id,
}
})
CRA::PersonAtAddress.list_from_hash(body['ArrayOfPersonsAtAddress'])
end
|
ruby
|
{
"resource": ""
}
|
q7782
|
Firering.Requests.user
|
train
|
def user(id, &callback)
http(:get, "/users/#{id}.json") do |data, http|
Firering::User.instantiate(self, data, :user, &callback)
end
end
|
ruby
|
{
"resource": ""
}
|
q7783
|
Firering.Requests.room
|
train
|
def room(id, &callback)
http(:get, "/room/#{id}.json") do |data, http|
Firering::Room.instantiate(self, data, :room, &callback)
end
end
|
ruby
|
{
"resource": ""
}
|
q7784
|
Firering.Requests.search_messages
|
train
|
def search_messages(query, &callback)
http(:get, "/search/#{query}.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(self, msg) }) if callback
end
end
|
ruby
|
{
"resource": ""
}
|
q7785
|
Firering.Requests.star_message
|
train
|
def star_message(id, yes_or_no = true, &callback)
http(yes_or_no ? :post : :delete, "/messages/#{id}/star.json") do |data, http|
callback.call(data) if callback
end
end
|
ruby
|
{
"resource": ""
}
|
q7786
|
Slugforge.Configuration.defaults
|
train
|
def defaults
@values = Hash[self.class.options.select { |_, c| c.key?(:default) }.map { |n,c| [n, c[:default]] }].merge(@values)
end
|
ruby
|
{
"resource": ""
}
|
q7787
|
Slugforge.Configuration.read_yaml
|
train
|
def read_yaml(path)
return unless File.exist?(path)
source = YAML.load_file(path)
return unless source.is_a?(Hash)
update_with { |config| read_yaml_key(source, config[:key]) }
end
|
ruby
|
{
"resource": ""
}
|
q7788
|
Slugforge.Configuration.update_with
|
train
|
def update_with(&blk)
self.class.options.each do |name, config|
value = yield(config)
@values[name] = value unless value.nil?
end
end
|
ruby
|
{
"resource": ""
}
|
q7789
|
Rack.WebProfiler::Collectors.add_collector
|
train
|
def add_collector(collector_class)
return collector_class.each { |c| add_collector(c) } if collector_class.is_a? Array
raise ArgumentError, "`collector_class' must be a class" unless collector_class.is_a? Class
unless collector_class.included_modules.include?(Rack::WebProfiler::Collector::DSL)
raise ArgumentError, "#{collector_class.class.name} must be an instance of \"Rack::WebProfiler::Collector::DSL\""
end
definition = collector_class.definition
if definition_by_identifier(definition.identifier)
raise ArgumentError, "A collector with identifier \“#{definition.identifier}\" already exists"
end
return false unless definition.is_enabled?
@collectors[collector_class] = definition
sort_collectors!
end
|
ruby
|
{
"resource": ""
}
|
q7790
|
Rack.WebProfiler::Collectors.sort_collectors!
|
train
|
def sort_collectors!
@sorted_collectors = {}
tmp = @collectors.sort_by { |_klass, definition| definition.position }
tmp.each { |_k, v| @sorted_collectors[v.identifier.to_sym] = v }
end
|
ruby
|
{
"resource": ""
}
|
q7791
|
Tvdbr.DataSet.normalize_value
|
train
|
def normalize_value(val)
if val.is_a?(Hash)
val = val["__content__"] if val.has_key?("__content__")
val = val.values.first if val.respond_to?(:values) && val.values.one?
val = val.join(" ") if val.respond_to?(:join)
val.to_s
else # any other value
val
end
end
|
ruby
|
{
"resource": ""
}
|
q7792
|
SysWatch.CLI.parse_options!
|
train
|
def parse_options!(args)
@options = {}
opts = ::OptionParser.new do |opts|
opts.banner = "Usage: syswatch [options]\n\n Options:"
opts.on("-f", "--foreground", "Do not daemonize, just run in foreground.") do |f|
@options[:foreground] = f
end
opts.on("-v", "--verbose", "Be verbose, print out some messages.") do |v|
@options[:verbose] = v
end
opts.on("-t", "--test", "Test notifications.") do |t|
@options[:test] = t
end
opts.on("-c", "--config [FILE]", "Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`") do |config|
@options[:config] = config
end
end
opts.parse! args
end
|
ruby
|
{
"resource": ""
}
|
q7793
|
Slugforge.SluginManager.locate_slugins
|
train
|
def locate_slugins
Gem.refresh
(Gem::Specification.respond_to?(:each) ? Gem::Specification : Gem.source_index.find_name('')).each do |gem|
next if gem.name !~ PREFIX
slugin_name = gem.name.split('-', 2).last
@slugins << Slugin.new(slugin_name, gem.name, gem, true) if !gem_located?(gem.name)
end
@slugins
end
|
ruby
|
{
"resource": ""
}
|
q7794
|
Gxapi.Ostruct.to_hash
|
train
|
def to_hash
ret = {}
@hash.dup.each_pair do |key, val|
ret[key] = self.convert_value_from_ostruct(val)
end
ret
end
|
ruby
|
{
"resource": ""
}
|
q7795
|
Gxapi.Ostruct.define_accessors
|
train
|
def define_accessors(field)
# add the generated method
self.generated_methods.module_eval do
define_method(field) do
@hash[field]
end
define_method("#{field}=") do |val|
@hash[field] = val
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7796
|
Gxapi.Ostruct.method_missing
|
train
|
def method_missing(meth, *args, &block)
if meth.to_s =~ /=$/
self.define_accessors(meth.to_s.gsub(/=$/,''))
return self.send(meth, *args, &block)
end
super
end
|
ruby
|
{
"resource": ""
}
|
q7797
|
Gxapi.Ostruct.underscore
|
train
|
def underscore(string)
string = string.to_s
string = string[0].downcase + string[1..-1].gsub(/([A-Z])/,'_\1')
string.downcase
end
|
ruby
|
{
"resource": ""
}
|
q7798
|
NitroApi.BatchCalls.handle_batch_multiple_actions
|
train
|
def handle_batch_multiple_actions
# TODO: improve handling of errors in the batch response
actions = []
@batch.each do |action|
actions << to_query(action[:params])
end
results = really_make_call({'method' => 'batch.run','methodFeed' => JSON.dump(actions)}, :post)
@batch = nil
extract_session_key results
results
end
|
ruby
|
{
"resource": ""
}
|
q7799
|
Cxxproject.StaticLibrary.convert_to_rake
|
train
|
def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
archiver = @tcs[:ARCHIVER]
res = typed_file_task Rake::Task::LIBRARY, get_task_name => object_multitask do
cmd = calc_command_line
aname = calc_archive_name
Dir.chdir(@project_dir) do
FileUtils.rm(aname) if File.exists?(aname)
# cmd.map! {|c| c.include?(' ') ? "\"#{c}\"" : c }
rd, wr = IO.pipe
cmd << {
:err => wr,
:out => wr
}
sp = spawn(*cmd)
cmd.pop
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmd, consoleOutput, @tcs[:ARCHIVER][:ERROR_PARSER], "Creating #{aname}")
check_config_file()
end
end
res.tags = tags
enhance_with_additional_files(res)
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
return res
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.