_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4500
|
CephRuby.Cluster.connect
|
train
|
def connect
log("connect")
ret = Lib::Rados.rados_connect(handle)
raise SystemCallError.new("connect to cluster failed", -ret) if ret < 0
end
|
ruby
|
{
"resource": ""
}
|
q4501
|
Jshintrb.JshintTask.define
|
train
|
def define # :nodoc:
actual_name = Hash === name ? name.keys.first : name
unless ::Rake.application.last_comment
desc "Run JShint"
end
task name do
unless js_file_list.empty?
result = Jshintrb::report(js_file_list, @options, @globals, STDERR)
if result.size > 0
abort("JSHint check failed") if fail_on_error
end
end
end
self
end
|
ruby
|
{
"resource": ""
}
|
q4502
|
SSSA.Utils.split_ints
|
train
|
def split_ints(secret)
result = []
secret.split('').map { |x|
data = x.unpack("H*")[0]
"0"*(data.size % 2) + data
}.join("").scan(/.{1,64}/) { |segment|
result.push (segment+"0"*(64-segment.size)).hex
}
return result
end
|
ruby
|
{
"resource": ""
}
|
q4503
|
Comable.Order.inherit!
|
train
|
def inherit!(order)
self.bill_address ||= order.bill_address
self.ship_address ||= order.ship_address
self.payment ||= order.payment
self.shipments = order.shipments if shipments.empty?
stated?(order.state) ? save! : next_state!
end
|
ruby
|
{
"resource": ""
}
|
q4504
|
Qe.Element.duplicate
|
train
|
def duplicate(page, parent = nil)
new_element = self.class.new(self.attributes)
case parent.class.to_s
when ChoiceField
new_element.conditional_id = parent.id
when QuestionGrid, QuestionGridWithTotal
new_element.question_grid_id = parent.id
end
new_element.save(:validate => false)
PageElement.create(:element => new_element, :page => page) unless parent
# duplicate children
if respond_to?(:elements) && elements.present?
elements.each {|e| e.duplicate(page, new_element)}
end
new_element
end
|
ruby
|
{
"resource": ""
}
|
q4505
|
REHTML.Tokenizer.decode
|
train
|
def decode(html)
html.gsub(ENTITIES::REGEXP){
if $1
if ENTITIES::MAP[$1]
ENTITIES::MAP[$1]
else
$&
end
elsif $2
[$2.to_i(10)].pack('U')
elsif $3
[$3.to_i(16)].pack('U')
else
$&
end
}
end
|
ruby
|
{
"resource": ""
}
|
q4506
|
Qe.Notifier.notification
|
train
|
def notification(p_recipients, p_from, template_name, template_params = {}, options = {})
email_template = EmailTemplate.find_by_name(template_name)
if email_template.nil?
raise "Email Template #{template_name} could not be found"
else
@recipients = p_recipients
@from = p_from
@subject = Liquid::Template.parse(email_template.subject).render(template_params)
@body = Liquid::Template.parse(email_template.content).render(template_params)
end
end
|
ruby
|
{
"resource": ""
}
|
q4507
|
VCloudSdk.Catalog.find_item
|
train
|
def find_item(name, item_type = nil)
link = find_item_link(name)
item = VCloudSdk::CatalogItem.new(@session, link)
check_item_type(item, item_type)
item
end
|
ruby
|
{
"resource": ""
}
|
q4508
|
GetnetApi.Configure.set_endpoint
|
train
|
def set_endpoint
if ambiente == :producao
return GetnetApi::Configure::URL[:producao]
elsif ambiente == :homologacao
return GetnetApi::Configure::URL[:homologacao]
else
return GetnetApi::Configure::URL[:sandbox]
end
end
|
ruby
|
{
"resource": ""
}
|
q4509
|
UriSigner.RequestSignature.signature
|
train
|
def signature
core_signature = [self.http_method, self.encoded_base_uri]
core_signature << self.encoded_query_params if self.query_params?
core_signature.join(self.separator)
end
|
ruby
|
{
"resource": ""
}
|
q4510
|
UriSigner.QueryHashParser.to_s
|
train
|
def to_s
parts = @query_hash.sort.inject([]) do |arr, (key,value)|
if value.kind_of?(Array)
value.each do |nested|
arr << "%s=%s" % [key, nested]
end
else
arr << "%s=%s" % [key, value]
end
arr
end
parts.join('&')
end
|
ruby
|
{
"resource": ""
}
|
q4511
|
Macros.Sexp.sfind
|
train
|
def sfind(sexp, specs)
specs.inject(sexp) do |node, spec|
return NotFound if node.nil?
if spec.is_a?(Symbol) && node.type == spec
node
elsif spec.is_a?(Integer) && node.children.length > spec
node.children[spec]
elsif spec.is_a?(Array)
node.children.grep(AST::Node)
.flat_map { |child| sfind(child, spec) }
.reject { |child| child == NotFound }
else
return NotFound
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4512
|
MiniSpec.ClassAPI.helper
|
train
|
def helper helper, opts = {}, &proc
proc || raise(ArgumentError, 'block is missing')
helpers[helper] = [proc, opts]
end
|
ruby
|
{
"resource": ""
}
|
q4513
|
MiniSpec.Utils.symbol_thrown?
|
train
|
def symbol_thrown? expected_symbol, expected_value, context, &block
thrown_symbol, thrown_value = catch_symbol(expected_symbol, &block)
if context[:right_proc]
expected_symbol && raise(ArgumentError, 'Both arguments and block given. Please use either one.')
return MiniSpec::ThrowInspector.thrown_as_expected_by_proc?(thrown_symbol, context)
end
MiniSpec::ThrowInspector.thrown_as_expected?(expected_symbol, expected_value, thrown_symbol, thrown_value, context)
end
|
ruby
|
{
"resource": ""
}
|
q4514
|
MiniSpec.Utils.catch_symbol
|
train
|
def catch_symbol expected_symbol, &block
thrown_symbol, thrown_value = nil
begin
if expected_symbol
thrown_value = catch :__ms__nothing_thrown do
catch expected_symbol do
block.call
throw :__ms__nothing_thrown, :__ms__nothing_thrown
end
end
thrown_symbol = expected_symbol unless thrown_value == :__ms__nothing_thrown
else
block.call
end
rescue => e
raise(e) unless thrown_symbol = extract_thrown_symbol(e)
end
[thrown_symbol, thrown_value]
end
|
ruby
|
{
"resource": ""
}
|
q4515
|
MiniSpec.Utils.extract_thrown_symbol
|
train
|
def extract_thrown_symbol exception
return unless exception.is_a?(Exception)
return unless s = exception.message.scan(/uncaught throw\W+(\w+)/).flatten[0]
s.to_sym
end
|
ruby
|
{
"resource": ""
}
|
q4516
|
BioTable.Table.find_fields
|
train
|
def find_fields rowname
row = row_by_name(rowname)
fields = (row ? row.fields : [])
# fill fields with nil to match header length
# say header=5 fields=2 fill=2 (skip rowname)
fields.fill(nil,fields.size,header.size-1-fields.size)
end
|
ruby
|
{
"resource": ""
}
|
q4517
|
Fibre.FiberPool.checkout
|
train
|
def checkout(&b)
spec = { block: b, parent: ::Fiber.current }
if @pool.empty?
raise "The fiber queue has been overflowed" if @queue.size > @pool_queue_size
@queue.push spec
return
end
@pool.shift.tap do |fiber|
@reserved[fiber.object_id] = spec
fiber.resume(spec)
end
self
end
|
ruby
|
{
"resource": ""
}
|
q4518
|
Fibre.FiberPool.fiber_entry
|
train
|
def fiber_entry(spec)
loop do
raise "wrong spec in fiber block" unless spec.is_a?(Hash)
begin
before!(spec)
spec[:block].call# *Fiber.current.args
after!(spec)
# catch ArgumentError, IOError, EOFError, IndexError, LocalJumpError, NameError, NoMethodError
# RangeError, FloatDomainError, RegexpError, RuntimeError, SecurityError, SystemCallError
# SystemStackError, ThreadError, TypeError, ZeroDivisionError
rescue StandardError => e
if error.empty?
raise Fibre::FiberError.new(e)
else
error!(e)
end
# catch NoMemoryError, ScriptError, SignalException, SystemExit, fatal etc
#rescue Exception
end
unless @queue.empty?
spec = @queue.shift
next
end
spec = checkin
end
end
|
ruby
|
{
"resource": ""
}
|
q4519
|
Fibre.FiberPool.checkin
|
train
|
def checkin(result=nil)
@reserved.delete ::Fiber.current.object_id
@pool.unshift ::Fiber.current
::Fiber.yield
end
|
ruby
|
{
"resource": ""
}
|
q4520
|
Less.Tree.anonymous_function
|
train
|
def anonymous_function(block)
lambda do |*args|
# args: (this, node) v8 >= 0.10, otherwise (node)
raise ArgumentError, "missing node" if args.empty?
@tree[:Anonymous].new block.call(@tree, args.last)
end
end
|
ruby
|
{
"resource": ""
}
|
q4521
|
Less.Tree.extend_js
|
train
|
def extend_js(mod)
extend mod
mod.public_instance_methods.each do |method_name|
add_function(sym_to_css(method_name)) { |tree, cxt|
send method_name.to_sym, unquote(cxt.toCSS())
}
end
end
|
ruby
|
{
"resource": ""
}
|
q4522
|
REHTML.REXMLBuilder.append
|
train
|
def append(node)
if node.is_a?(EndTag)
return if empty_tag?(node.name)
po = @pos
while po.parent and po.name != node.name
po = po.parent
end
if po.name == node.name
@pos = po.parent
end
else
rexml = to_rexml(node)
# if node is second root element, add root element wrap html tag
if rexml.is_a?(REXML::Element) and @pos == @doc and @doc.root
if @doc.root.name != 'html'
html = REXML::Element.new
html.name = "html"
i = @doc.root.index_in_parent-1
while pos = @doc.delete_at(i)
@doc.delete_element(pos) if pos.is_a?(REXML::Element)
html << pos
end
@doc << html
@pos = html
end
@pos = @doc.root
end
@pos << rexml
if rexml.is_a?(REXML::Element) and !empty_tag?(node.name) and !node.empty?
@pos = rexml
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4523
|
GetnetApi.Payment.to_request
|
train
|
def to_request obj, type
payment = {
seller_id: GetnetApi.seller_id.to_s,
amount: self.amount.to_i,
currency: self.currency.to_s,
order: self.order.to_request,
customer: self.customer.to_request(:payment),
}
if type == :boleto
payment.merge!({"boleto" => obj.to_request,})
elsif :credit
payment.merge!({"credit" => obj.to_request,})
end
return payment
end
|
ruby
|
{
"resource": ""
}
|
q4524
|
Svn.Revision.diff
|
train
|
def diff( path, options={} )
raise Svn::Error, "cannot diff directory #{path}@#{to_s}" if dir? path
other = options[:with] if options[:with].is_a? Root
other = repo.revision(options[:with]) if options[:with].is_a? Numeric
other ||= repo.revision(to_i - 1)
return other.diff( path, :with => self ) if other < self
content = ""
begin
content = file_content_stream( path ).to_counted_string
rescue Svn::Error => err
raise if options[:raise_errors]
end
other_content = ""
begin
other_content= other.file_content_stream( path ).to_counted_string
rescue Svn::Error => err
raise if options[:raise_errors]
end
Diff.string_diff( content, other_content ).unified(
:original_header => "#{path}@#{to_s}",
:modified_header => "#{path}@#{other}"
)
end
|
ruby
|
{
"resource": ""
}
|
q4525
|
RedditBot.Bot.resp_with_token
|
train
|
def resp_with_token mtd, path, form
fail unless path.start_with? ?/
timeout = 5
begin
reddit_resp mtd, "https://oauth.reddit.com" + path, form, {
"Authorization" => "bearer #{token}",
"User-Agent" => "bot/#{@user_agent || @name}/#{RedditBot::VERSION} by /u/nakilon",
}
rescue NetHTTPUtils::Error => e
sleep timeout
Module.nesting[1].logger.info "sleeping #{timeout} seconds because of #{e.code}"
timeout *= 2
raise unless e.code == 401
@token_cached = nil
retry
end
end
|
ruby
|
{
"resource": ""
}
|
q4526
|
Ideone.Client.languages
|
train
|
def languages
unless @languages_cache
response = call_request(:get_languages)
languages = response.to_hash[:get_languages_response][:return][:item][1][:value][:item]
# Create a sorted hash
@languages_cache = Hash[create_dict(languages).sort_by{|k,v| k.to_i}]
end
return @languages_cache
end
|
ruby
|
{
"resource": ""
}
|
q4527
|
GetnetApi.Boleto.to_request
|
train
|
def to_request
boleto = {
our_number: self.our_number,
document_number: self.document_number,
expiration_date: self.expiration_date,
instructions: self.instructions,
provider: self.provider
}
return boleto
end
|
ruby
|
{
"resource": ""
}
|
q4528
|
Diameter.Message.all_avps_by_name
|
train
|
def all_avps_by_name(name)
code, _type, vendor = Internals::AVPNames.get(name)
all_avps_by_code(code, vendor)
end
|
ruby
|
{
"resource": ""
}
|
q4529
|
WebPageParser.BaseRegexpParser.encode
|
train
|
def encode(s)
return s if s.nil?
return s if s.valid_encoding?
if s.force_encoding("iso-8859-1").valid_encoding?
return s.encode('utf-8', 'iso-8859-1')
end
s
end
|
ruby
|
{
"resource": ""
}
|
q4530
|
WebPageParser.BaseRegexpParser.retrieve_page
|
train
|
def retrieve_page(rurl = nil)
durl = rurl || url
return nil unless durl
durl = filter_url(durl) if self.respond_to?(:filter_url)
self.class.retrieve_session ||= WebPageParser::HTTP::Session.new
encode(self.class.retrieve_session.get(durl))
end
|
ruby
|
{
"resource": ""
}
|
q4531
|
WebPageParser.BaseRegexpParser.title
|
train
|
def title
return @title if @title
if matches = class_const(:TITLE_RE).match(page)
@title = matches[1].to_s.strip
title_processor
@title = decode_entities(@title)
end
end
|
ruby
|
{
"resource": ""
}
|
q4532
|
WebPageParser.BaseRegexpParser.content
|
train
|
def content
return @content if @content
matches = class_const(:CONTENT_RE).match(page)
if matches
@content = class_const(:KILL_CHARS_RE).gsub(matches[1].to_s, '')
content_processor
@content.collect! { |p| decode_entities(p.strip) }
@content.delete_if { |p| p == '' or p.nil? }
end
@content = [] if @content.nil?
@content
end
|
ruby
|
{
"resource": ""
}
|
q4533
|
NIFTI.NImage.[]
|
train
|
def [](index)
# Dealing with Ranges is useful when the image represents a tensor
if (index.is_a?(Fixnum) && index >= self.shape[0]) || (index.is_a?(Range) && index.last >= self.shape[0])
raise IndexError.new("Index over bounds")
elsif self.shape.count == 1
if index.is_a?(Range)
value = []
index.each { |i| value << self.array_image[get_index_value(i)] }
value
else
self.array_image[get_index_value(index)]
end
else
NImage.new(self.array_image, self.dim, self.previous_indexes.clone << index)
end
end
|
ruby
|
{
"resource": ""
}
|
q4534
|
NIFTI.NImage.[]=
|
train
|
def []=(index,value)
if self.shape.count != 1 or index >= self.shape[0]
raise IndexError.new("You can only set values for array values")
else
@array_image[get_index_value(index)] = value
end
end
|
ruby
|
{
"resource": ""
}
|
q4535
|
Qe.QuestionSet.post
|
train
|
def post(params, answer_sheet)
questions_indexed = @questions.index_by {|q| q.id}
# loop over form values
params ||= {}
params.each do |question_id, response|
next if questions_indexed[question_id.to_i].nil? # the rare case where a question was removed after the app was opened.
# update each question with the posted response
questions_indexed[question_id.to_i].set_response(posted_values(response), answer_sheet)
end
end
|
ruby
|
{
"resource": ""
}
|
q4536
|
Qe.QuestionSet.posted_values
|
train
|
def posted_values(param)
if param.kind_of?(Hash) and param.has_key?('year') and param.has_key?('month')
year = param['year']
month = param['month']
if month.blank? or year.blank?
values = ''
else
values = [Date.new(year.to_i, month.to_i, 1).strftime('%m/%d/%Y')] # for mm/yy drop downs
end
elsif param.kind_of?(Hash)
# from Hash with multiple answers per question
values = param.values.map {|v| CGI.unescape(v)}
elsif param.kind_of?(String)
values = [CGI.unescape(param)]
end
# Hash may contain empty string to force post for no checkboxes
# values = values.reject {|r| r == ''}
end
|
ruby
|
{
"resource": ""
}
|
q4537
|
MiniSpec.InstanceAPI.mock
|
train
|
def mock object, method, visibility = nil, &proc
if method.is_a?(Hash)
proc && raise(ArgumentError, 'Both Hash and block given. Please use either one.')
method.each_pair {|m,r| mock(object, m, visibility, &proc {r})}
return MiniSpec::Mocks::HashedStub
end
visibility ||= MiniSpec::Utils.method_visibility(object, method) || :public
# IMPORTANT! stub should be defined before expectation
stub = stub(object, method, visibility, &proc)
expect(object).to_receive(method)
stub
end
|
ruby
|
{
"resource": ""
}
|
q4538
|
MiniSpec.InstanceAPI.proxy
|
train
|
def proxy object, method_name
# do not proxify doubles
return if object.respond_to?(:__ms__double_instance)
# do not proxify stubs
return if (x = @__ms__stubs__originals) && (x = x[object]) && x[method_name]
proxies = (@__ms__proxies[object] ||= [])
return if proxies.include?(method_name)
proxies << method_name
# method exists and it is a singleton.
# `nil?` method can be overridden only through a singleton
if method_name == :nil? || object.singleton_methods.include?(method_name)
return __ms__mocks__define_singleton_proxy(object, method_name)
end
# method exists and it is not a singleton, define a regular proxy
if visibility = MiniSpec::Utils.method_visibility(object, method_name)
return __ms__mocks__define_regular_proxy(object, method_name, visibility)
end
raise(NoMethodError, '%s does not respond to %s. Can not proxify an un-existing method.' % [
object.inspect, method_name.inspect
])
end
|
ruby
|
{
"resource": ""
}
|
q4539
|
Qe.AnswerSheetsController.index
|
train
|
def index
# TODO dynamically reference this
# @answer_sheets = answer_sheet_type.find(:all, :order => 'created_at')
@answer_sheets = AnswerSheet.find(:all, :order => 'created_at')
# drop down of sheets to capture data for
@question_sheets = QuestionSheet.find(:all, :order => 'label').map {|s| [s.label, s.id]}
end
|
ruby
|
{
"resource": ""
}
|
q4540
|
TelestreamCloud::Qc.QcApi.create_job
|
train
|
def create_job(project_id, data, opts = {})
data, _status_code, _headers = create_job_with_http_info(project_id, data, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q4541
|
TelestreamCloud::Qc.QcApi.get_job
|
train
|
def get_job(project_id, job_id, opts = {})
data, _status_code, _headers = get_job_with_http_info(project_id, job_id, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q4542
|
TelestreamCloud::Qc.QcApi.get_project
|
train
|
def get_project(project_id, opts = {})
data, _status_code, _headers = get_project_with_http_info(project_id, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q4543
|
TelestreamCloud::Qc.QcApi.list_jobs
|
train
|
def list_jobs(project_id, opts = {})
data, _status_code, _headers = list_jobs_with_http_info(project_id, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q4544
|
AutomaticForeignKey::ActiveRecord::ConnectionAdapters.TableDefinition.belongs_to
|
train
|
def belongs_to(table, options = {})
options = options.merge(:references => table)
options[:on_delete] = options.delete(:dependent) if options.has_key?(:dependent)
column("#{table.to_s.singularize}_id".to_sym, :integer, options)
end
|
ruby
|
{
"resource": ""
}
|
q4545
|
Svn.Stream.read_all
|
train
|
def read_all
content = String.new
while bytes = read and !bytes.empty?
content << bytes
end
content
end
|
ruby
|
{
"resource": ""
}
|
q4546
|
Svn.Stream.to_string_io
|
train
|
def to_string_io
content = StringIO.new
while bytes = read and !bytes.empty?
content.write( bytes )
end
content.rewind
content
end
|
ruby
|
{
"resource": ""
}
|
q4547
|
NIFTI.Stream.decode
|
train
|
def decode(length, type)
# Check if values are valid:
if (@index + length) > @string.length
# The index number is bigger then the length of the binary string.
# We have reached the end and will return nil.
value = nil
else
if type == "AT"
value = decode_tag
else
# Decode the binary string and return value:
value = @string.slice(@index, length).unpack(vr_to_str(type))
# If the result is an array of one element, return the element instead of the array.
# If result is contained in a multi-element array, the original array is returned.
if value.length == 1
value = value[0]
# If value is a string, strip away possible trailing whitespace:
# Do this using gsub instead of ruby-core #strip to keep trailing carriage
# returns, etc., because that is valid whitespace that we want to have included
# (i.e. in extended header data, AFNI writes a \n at the end of it's xml info,
# and that must be kept in order to not change the file on writing back out).
value.gsub!(/\000*$/, "") if value.respond_to? :gsub!
end
# Update our position in the string:
skip(length)
end
end
return value
end
|
ruby
|
{
"resource": ""
}
|
q4548
|
NIFTI.Stream.encode
|
train
|
def encode(value, type)
value = [value] unless value.is_a?(Array)
return value.pack(vr_to_str(type))
end
|
ruby
|
{
"resource": ""
}
|
q4549
|
BioTable.TableApply.parse_row
|
train
|
def parse_row(line_num, line, header, column_idx, prev_fields, options)
fields = LineParser::parse(line, options[:in_format], options[:split_on])
return nil,nil if fields.compact == []
if options[:pad_fields] and fields.size < header.size
fields += [''] * (header.size - fields.size)
end
fields = Formatter::strip_quotes(fields) if @strip_quotes
fields = Formatter::transform_row_ids(@transform_ids, fields) if @transform_ids
fields = Filter::apply_column_filter(fields,column_idx)
return nil,nil if fields.compact == []
rowname = fields[0]
data_fields = fields[@first_column..-1]
if data_fields.size > 0
return nil,nil if not Validator::valid_row?(line_num, data_fields, prev_fields)
return nil,nil if not Filter::numeric(@num_filter,data_fields,header)
return nil,nil if not Filter::generic(@filter,data_fields,header)
(rowname, data_fields) = Rewrite::rewrite(@rewrite,rowname,data_fields)
end
return rowname, data_fields
end
|
ruby
|
{
"resource": ""
}
|
q4550
|
JSON.Lexer.nextclean
|
train
|
def nextclean
while true
c = self.nextchar()
if (c == '/')
case self.nextchar()
when '/'
c = self.nextchar()
while c != "\n" && c != "\r" && c != "\0"
c = self.nextchar()
end
when '*'
while true
c = self.nextchar()
raise "unclosed comment" if (c == "\0")
if (c == '*')
break if (self.nextchar() == '/')
self.back()
end
end
else
self.back()
return '/';
end
elsif c == "\0" || c[0] > " "[0]
return(c)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4551
|
JSON.Lexer.utf8str
|
train
|
def utf8str(code)
if (code & ~(0x7f)) == 0
# UCS-4 range 0x00000000 - 0x0000007F
return(code.chr)
end
buf = ""
if (code & ~(0x7ff)) == 0
# UCS-4 range 0x00000080 - 0x000007FF
buf << (0b11000000 | (code >> 6)).chr
buf << (0b10000000 | (code & 0b00111111)).chr
return(buf)
end
if (code & ~(0x000ffff)) == 0
# UCS-4 range 0x00000800 - 0x0000FFFF
buf << (0b11100000 | (code >> 12)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
# Not used -- JSON only has UCS-2, but for the sake
# of completeness
if (code & ~(0x1FFFFF)) == 0
# UCS-4 range 0x00010000 - 0x001FFFFF
buf << (0b11110000 | (code >> 18)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
if (code & ~(0x03FFFFFF)) == 0
# UCS-4 range 0x00200000 - 0x03FFFFFF
buf << (0b11110000 | (code >> 24)).chr
buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
# UCS-4 range 0x04000000 - 0x7FFFFFFF
buf << (0b11111000 | (code >> 30)).chr
buf << (0b10000000 | ((code >> 24) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
|
ruby
|
{
"resource": ""
}
|
q4552
|
JSON.Lexer.nextto
|
train
|
def nextto(regex)
buf = ""
while (true)
c = self.nextchar()
if !(regex =~ c).nil? || c == '\0' || c == '\n' || c == '\r'
self.back() if (c != '\0')
return(buf.chomp())
end
buf += c
end
end
|
ruby
|
{
"resource": ""
}
|
q4553
|
JSON.Lexer.nextvalue
|
train
|
def nextvalue
c = self.nextclean
s = ""
case c
when /\"|\'/
return(self.nextstring(c))
when '{'
self.back()
return(Hash.new.from_json(self))
when '['
self.back()
return(Array.new.from_json(self))
else
buf = ""
while ((c =~ /"| |:|,|\]|\}|\/|\0/).nil?)
buf += c
c = self.nextchar()
end
self.back()
s = buf.chomp
case s
when "true"
return(true)
when "false"
return(false)
when "null"
return(nil)
when /^[0-9]|\.|-|\+/
if s =~ /[.]/ then
return Float(s)
else
return Integer(s)
end
end
if (s == "")
s = nil
end
return(s)
end
end
|
ruby
|
{
"resource": ""
}
|
q4554
|
Bombshell.Completor.complete
|
train
|
def complete(fragment)
self.class.filter(shell.instance_methods).grep Regexp.new(Regexp.quote(fragment))
end
|
ruby
|
{
"resource": ""
}
|
q4555
|
Beaker.Openstack.flavor
|
train
|
def flavor f
@logger.debug "OpenStack: Looking up flavor '#{f}'"
@compute_client.flavors.find { |x| x.name == f } || raise("Couldn't find flavor: #{f}")
end
|
ruby
|
{
"resource": ""
}
|
q4556
|
Beaker.Openstack.image
|
train
|
def image i
@logger.debug "OpenStack: Looking up image '#{i}'"
@compute_client.images.find { |x| x.name == i } || raise("Couldn't find image: #{i}")
end
|
ruby
|
{
"resource": ""
}
|
q4557
|
Beaker.Openstack.network
|
train
|
def network n
@logger.debug "OpenStack: Looking up network '#{n}'"
@network_client.networks.find { |x| x.name == n } || raise("Couldn't find network: #{n}")
end
|
ruby
|
{
"resource": ""
}
|
q4558
|
Beaker.Openstack.security_groups
|
train
|
def security_groups sgs
for sg in sgs
@logger.debug "Openstack: Looking up security group '#{sg}'"
@compute_client.security_groups.find { |x| x.name == sg } || raise("Couldn't find security group: #{sg}")
sgs
end
end
|
ruby
|
{
"resource": ""
}
|
q4559
|
Beaker.Openstack.provision_storage
|
train
|
def provision_storage host, vm
volumes = get_volumes(host)
if !volumes.empty?
# Lazily create the volume client if needed
volume_client_create
volumes.keys.each_with_index do |volume, index|
@logger.debug "Creating volume #{volume} for OpenStack host #{host.name}"
# The node defintion file defines volume sizes in MB (due to precedent
# with the vagrant virtualbox implementation) however OpenStack requires
# this translating into GB
openstack_size = volumes[volume]['size'].to_i / 1000
# Set up the volume creation arguments
args = {
:size => openstack_size,
:description => "Beaker volume: host=#{host.name} volume=#{volume}",
}
# Between version 1 and subsequent versions the API was updated to
# rename 'display_name' to just 'name' for better consistency
if get_volume_api_version == 1
args[:display_name] = volume
else
args[:name] = volume
end
# Create the volume and wait for it to become available
vol = @volume_client.volumes.create(**args)
vol.wait_for { ready? }
# Fog needs a device name to attach as, so invent one. The guest
# doesn't pay any attention to this
device = "/dev/vd#{('b'.ord + index).chr}"
vm.attach_volume(vol.id, device)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4560
|
Beaker.Openstack.cleanup_storage
|
train
|
def cleanup_storage vm
vm.volumes.each do |vol|
@logger.debug "Deleting volume #{vol.name} for OpenStack host #{vm.name}"
vm.detach_volume(vol.id)
vol.wait_for { ready? }
vol.destroy
end
end
|
ruby
|
{
"resource": ""
}
|
q4561
|
Beaker.Openstack.get_ip
|
train
|
def get_ip
begin
@logger.debug "Creating IP"
ip = @compute_client.addresses.create
rescue Fog::Compute::OpenStack::NotFound
# If there are no more floating IP addresses, allocate a
# new one and try again.
@compute_client.allocate_address(@options[:floating_ip_pool])
ip = @compute_client.addresses.find { |ip| ip.instance_id.nil? }
end
raise 'Could not find or allocate an address' if not ip
ip
end
|
ruby
|
{
"resource": ""
}
|
q4562
|
Beaker.Openstack.provision
|
train
|
def provision
@logger.notify "Provisioning OpenStack"
@hosts.each do |host|
ip = get_ip
hostname = ip.ip.gsub('.','-')
host[:vmhostname] = hostname + '.rfc1918.puppetlabs.net'
create_or_associate_keypair(host, hostname)
@logger.debug "Provisioning #{host.name} (#{host[:vmhostname]})"
options = {
:flavor_ref => flavor(host[:flavor]).id,
:image_ref => image(host[:image]).id,
:nics => [ {'net_id' => network(@options[:openstack_network]).id } ],
:name => host[:vmhostname],
:hostname => host[:vmhostname],
:user_data => host[:user_data] || "#cloud-config\nmanage_etc_hosts: true\n",
:key_name => host[:keyname],
}
options[:security_groups] = security_groups(@options[:security_group]) unless @options[:security_group].nil?
vm = @compute_client.servers.create(options)
#wait for the new instance to start up
try = 1
attempts = @options[:timeout].to_i / SLEEPWAIT
while try <= attempts
begin
vm.wait_for(5) { ready? }
break
rescue Fog::Errors::TimeoutError => e
if try >= attempts
@logger.debug "Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})"
raise e
end
@logger.debug "Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again..."
end
sleep SLEEPWAIT
try += 1
end
# Associate a public IP to the server
ip.server = vm
host[:ip] = ip.ip
@logger.debug "OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}"
#set metadata
vm.metadata.update({:jenkins_build_url => @options[:jenkins_build_url].to_s,
:department => @options[:department].to_s,
:project => @options[:project].to_s })
@vms << vm
# Wait for the host to accept ssh logins
host.wait_for_port(22)
#enable root if user is not root
enable_root(host)
provision_storage(host, vm) if @options[:openstack_volume_support]
@logger.notify "OpenStack Volume Support Disabled, can't provision volumes" if not @options[:openstack_volume_support]
end
hack_etc_hosts @hosts, @options
end
|
ruby
|
{
"resource": ""
}
|
q4563
|
Beaker.Openstack.cleanup
|
train
|
def cleanup
@logger.notify "Cleaning up OpenStack"
@vms.each do |vm|
cleanup_storage(vm) if @options[:openstack_volume_support]
@logger.debug "Release floating IPs for OpenStack host #{vm.name}"
floating_ips = vm.all_addresses # fetch and release its floating IPs
floating_ips.each do |address|
@compute_client.disassociate_address(vm.id, address['ip'])
@compute_client.release_address(address['id'])
end
@logger.debug "Destroying OpenStack host #{vm.name}"
vm.destroy
if @options[:openstack_keyname].nil?
@logger.debug "Deleting random keypair"
@compute_client.delete_key_pair vm.key_name
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4564
|
Beaker.Openstack.create_or_associate_keypair
|
train
|
def create_or_associate_keypair(host, keyname)
if @options[:openstack_keyname]
@logger.debug "Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})"
keyname = @options[:openstack_keyname]
else
@logger.debug "Generate a new rsa key"
# There is apparently an error that can occur when generating RSA keys, probably
# due to some timing issue, probably similar to the issue described here:
# https://github.com/negativecode/vines/issues/34
# In order to mitigate this error, we will simply try again up to three times, and
# then fail if we continue to error out.
begin
retries ||= 0
key = OpenSSL::PKey::RSA.new 2048
rescue OpenSSL::PKey::RSAError => e
retries += 1
if retries > 2
@logger.notify "error generating RSA key #{retries} times, exiting"
raise e
end
retry
end
type = key.ssh_type
data = [ key.to_blob ].pack('m0')
@logger.debug "Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'"
@compute_client.create_key_pair keyname, "#{type} #{data}"
host['ssh'][:key_data] = [ key.to_pem ]
end
host[:keyname] = keyname
end
|
ruby
|
{
"resource": ""
}
|
q4565
|
Pinboard.Client.get
|
train
|
def get(params = {})
params[:dt] = params[:dt].to_date.to_s if params.is_a? Time
params[:meta] = params[:meta] ? 'yes' : 'no' if params.has_key?(:meta)
options = create_params(params)
posts = self.class.get('/posts/get', options)['posts']['post']
posts = [] if posts.nil?
posts = [posts] if posts.class != Array
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end
|
ruby
|
{
"resource": ""
}
|
q4566
|
Pinboard.Client.suggest
|
train
|
def suggest(url)
options = create_params({url: url})
suggested = self.class.get('/posts/suggest', options)['suggested']
popular = suggested['popular']
popular = [] if popular.nil?
popular = [popular] if popular.class != Array
recommended = suggested['recommended']
recommended = [] if recommended.nil?
recommended = [recommended] if recommended.class != Array
{:popular => popular, :recommended => recommended}
end
|
ruby
|
{
"resource": ""
}
|
q4567
|
Pinboard.Client.recent
|
train
|
def recent(params={})
options = create_params(params)
posts = self.class.get('/posts/recent', options)['posts']['post']
posts = [] if posts.nil?
posts = [*posts]
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end
|
ruby
|
{
"resource": ""
}
|
q4568
|
Pinboard.Client.dates
|
train
|
def dates(tag=nil)
params = {}
params[:tag] = tag if tag
options = create_params(params)
dates = self.class.get('/posts/dates', options)['dates']['date']
dates = [] if dates.nil?
dates = [*dates]
dates.each_with_object({}) { |value, hash|
hash[value["date"]] = value["count"].to_i
}
end
|
ruby
|
{
"resource": ""
}
|
q4569
|
Pinboard.Client.tags_get
|
train
|
def tags_get(params={})
options = create_params(params)
tags = self.class.get('/tags/get', options)['tags']['tag']
tags = [] if tags.nil?
tags = [*tags]
tags.map { |p| Tag.new(Util.symbolize_keys(p)) }
end
|
ruby
|
{
"resource": ""
}
|
q4570
|
Pinboard.Client.tags_rename
|
train
|
def tags_rename(old_tag, new_tag=nil)
params = {}
params[:old] = old_tag
params[:new] = new_tag if new_tag
options = create_params(params)
result_code = self.class.get('/tags/rename', options).parsed_response["result"]
raise Error.new(result_code) if result_code != "done"
result_code
end
|
ruby
|
{
"resource": ""
}
|
q4571
|
Pinboard.Client.tags_delete
|
train
|
def tags_delete(tag)
params = { tag: tag }
options = create_params(params)
self.class.get('/tags/delete', options)
nil
end
|
ruby
|
{
"resource": ""
}
|
q4572
|
Pinboard.Client.notes_list
|
train
|
def notes_list
options = create_params({})
notes = self.class.get('/notes/list', options)['notes']['note']
notes = [] if notes.nil?
notes = [*notes]
notes.map { |p| Note.new(Util.symbolize_keys(p)) }
end
|
ruby
|
{
"resource": ""
}
|
q4573
|
Pinboard.Client.notes_get
|
train
|
def notes_get(id)
options = create_params({})
note = self.class.get("/notes/#{id}", options)['note']
return nil unless note
# Complete hack, because the API is still broken
content = '__content__'
Note.new({
id: note['id'],
# Remove whitespace around the title,
# because of missing xml tag around
title: note[content].gsub(/\n| +/, ''),
length: note['length'][content].to_i,
text: note['text'][content]
})
end
|
ruby
|
{
"resource": ""
}
|
q4574
|
Pinboard.Client.create_params
|
train
|
def create_params params
options = {}
options[:query] = params
if @auth_token
options[:query].merge!(auth_token: @auth_token)
else
options[:basic_auth] = @auth
end
options
end
|
ruby
|
{
"resource": ""
}
|
q4575
|
VCloudSdk.VM.memory
|
train
|
def memory
m = entity_xml
.hardware_section
.memory
allocation_units = m.get_rasd_content(Xml::RASD_TYPES[:ALLOCATION_UNITS])
bytes = eval_memory_allocation_units(allocation_units)
virtual_quantity = m.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]).to_i
memory_mb = virtual_quantity * bytes / BYTES_PER_MEGABYTE
fail CloudError,
"Size of memory is less than 1 MB." if memory_mb == 0
memory_mb
end
|
ruby
|
{
"resource": ""
}
|
q4576
|
VCloudSdk.VM.memory=
|
train
|
def memory=(size)
fail(CloudError,
"Invalid vm memory size #{size}MB") if size <= 0
Config
.logger
.info "Changing the vm memory to #{size}MB."
payload = entity_xml
payload.change_memory(size)
task = connection.post(payload.reconfigure_link.href,
payload,
Xml::MEDIA_TYPE[:VM])
monitor_task(task)
self
end
|
ruby
|
{
"resource": ""
}
|
q4577
|
VCloudSdk.VM.vcpu
|
train
|
def vcpu
cpus = entity_xml
.hardware_section
.cpu
.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY])
fail CloudError,
"Uable to retrieve number of virtual cpus of VM #{name}" if cpus.nil?
cpus.to_i
end
|
ruby
|
{
"resource": ""
}
|
q4578
|
VCloudSdk.VM.vcpu=
|
train
|
def vcpu=(count)
fail(CloudError,
"Invalid virtual CPU count #{count}") if count <= 0
Config
.logger
.info "Changing the virtual CPU count to #{count}."
payload = entity_xml
payload.change_cpu_count(count)
task = connection.post(payload.reconfigure_link.href,
payload,
Xml::MEDIA_TYPE[:VM])
monitor_task(task)
self
end
|
ruby
|
{
"resource": ""
}
|
q4579
|
SimpleSearchFilter.Filter.get_order_dir_for_column
|
train
|
def get_order_dir_for_column(name)
name = name.to_s
current_column = get_order_column
return nil unless current_column==name
dir = get_order_dir
return nil if dir.nil?
dir
end
|
ruby
|
{
"resource": ""
}
|
q4580
|
ElFinderS3.Connector.run
|
train
|
def run(params)
@adapter = ElFinderS3::Adapter.new(@options[:server], @options[:cache_connector])
@root = ElFinderS3::Pathname.new(adapter, @options[:root]) #Change - Pass the root dir here
begin
@params = params.dup
@headers = {}
@response = {}
@response[:errorData] = {}
if VALID_COMMANDS.include?(@params[:cmd])
if @options[:thumbs]
@thumb_directory = @root + @options[:thumbs_directory]
@thumb_directory.mkdir unless @thumb_directory.exist?
raise(RuntimeError, "Unable to create thumbs directory") unless @thumb_directory.directory?
end
@current = @params[:current] ? from_hash(@params[:current]) : nil
@target = (@params[:target] and !@params[:target].empty?) ? from_hash(@params[:target]) : nil
if params[:targets]
@targets = @params[:targets].map { |t| from_hash(t) }
end
begin
send("_#{@params[:cmd]}")
rescue Exception => exception
puts exception.message
puts exception.backtrace.inspect
@response[:error] = 'Access Denied'
end
else
invalid_request
end
@response.delete(:errorData) if @response[:errorData].empty?
return @headers, @response
ensure
adapter.close
end
end
|
ruby
|
{
"resource": ""
}
|
q4581
|
Diameter.Stack.add_handler
|
train
|
def add_handler(app_id, opts={}, &blk)
vendor = opts.fetch(:vendor, 0)
auth = opts.fetch(:auth, false)
acct = opts.fetch(:acct, false)
raise ArgumentError.new("Must specify at least one of auth or acct") unless auth or acct
@acct_apps << [app_id, vendor] if acct
@auth_apps << [app_id, vendor] if auth
@handlers[app_id] = blk
end
|
ruby
|
{
"resource": ""
}
|
q4582
|
Diameter.Stack.connect_to_peer
|
train
|
def connect_to_peer(peer_uri, peer_host, realm)
peer = Peer.new(peer_host, realm)
@peer_table[peer_host] = peer
@peer_table[peer_host].state = :WAITING
# Will move to :UP when the CEA is received
uri = URI(peer_uri)
cxn = @tcp_helper.setup_new_connection(uri.host, uri.port)
@peer_table[peer_host].cxn = cxn
avps = [AVP.create('Origin-Host', @local_host),
AVP.create('Origin-Realm', @local_realm),
AVP.create('Host-IP-Address', IPAddr.new('127.0.0.1')),
AVP.create('Vendor-Id', 100),
AVP.create('Product-Name', 'ruby-diameter')
]
avps += app_avps
cer_bytes = Message.new(version: 1, command_code: 257, app_id: 0, request: true, proxyable: false, retransmitted: false, error: false, avps: avps).to_wire
@tcp_helper.send(cer_bytes, cxn)
peer
end
|
ruby
|
{
"resource": ""
}
|
q4583
|
GetnetApi.Credit.to_request
|
train
|
def to_request
credit = {
delayed: self.delayed,
authenticated: self.authenticated,
pre_authorization: self.pre_authorization,
save_card_data: self.save_card_data,
transaction_type: self.transaction_type,
number_installments: self.number_installments.to_i,
soft_descriptor: self.soft_descriptor,
dynamic_mcc: self.dynamic_mcc,
card: self.card.to_request,
}
return credit
end
|
ruby
|
{
"resource": ""
}
|
q4584
|
Newegg.Api.stores
|
train
|
def stores
return self._stores if not self._stores.empty?
response = api_get("Stores.egg")
stores = JSON.parse(response.body)
stores.each do |store|
self._stores << Newegg::Store.new(store['Title'], store['StoreDepa'], store['StoreID'], store['ShowSeeAllDeals'])
end
self._stores
end
|
ruby
|
{
"resource": ""
}
|
q4585
|
Newegg.Api.categories
|
train
|
def categories(store_id)
return [] if store_id.nil?
response = api_get("Stores.egg", "Categories", store_id)
categories = JSON.parse(response.body)
categories = categories.collect do |category|
Newegg::Category.new(category['Description'], category['CategoryType'], category['CategoryID'],
category['StoreID'], category['ShowSeeAllDeals'], category['NodeId'])
end
categories
end
|
ruby
|
{
"resource": ""
}
|
q4586
|
Newegg.Api.store_content
|
train
|
def store_content(store_id, category_id = -1, node_id = -1, store_type = 4, page_number = 1)
params = {
'storeId' => store_id,
'categoryId' => category_id,
'nodeId' => node_id,
'storeType' => store_type,
'pageNumber' => page_number
}
JSON.parse(api_get('Stores.egg', 'Content', nil, params).body)
end
|
ruby
|
{
"resource": ""
}
|
q4587
|
Newegg.Api.search
|
train
|
def search(options={})
options = {store_id: -1, category_id: -1, sub_category_id: -1, node_id: -1, page_number: 1, sort: "FEATURED",
keywords: ""}.merge(options)
request = {
'IsUPCCodeSearch' => false,
'IsSubCategorySearch' => options[:sub_category_id] > 0,
'isGuideAdvanceSearch' => false,
'StoreDepaId' => options[:store_id],
'CategoryId' => options[:category_id],
'SubCategoryId' => options[:sub_category_id],
'NodeId' => options[:node_id],
'BrandId' => -1,
'NValue' => "",
'Keyword' => options[:keywords],
'Sort' => options[:sort],
'PageNumber' => options[:page_number]
}
JSON.parse(api_post("Search.egg", "Advanced", request).body, {quirks_mode: true})
end
|
ruby
|
{
"resource": ""
}
|
q4588
|
Newegg.Api.combo_deals
|
train
|
def combo_deals(item_number, options={})
options = {sub_category: -1, sort_field: 0, page_number: 1}.merge(options)
params = {
'SubCategory' => options[:sub_category],
'SortField' => options[:sort_field],
'PageNumber' => options[:page_number]
}
JSON.parse(api_get('Products.egg', item_number, 'ComboDeals', params).body)
end
|
ruby
|
{
"resource": ""
}
|
q4589
|
Newegg.Api.reviews
|
train
|
def reviews(item_number, page_number = 1, options={})
options = {time: 'all', rating: 'All', sort: 'date posted'}.merge(options)
params = {
'filter.time' => options[:time],
'filter.rating' => options[:rating],
'sort' => options[:sort]
}
JSON.parse(api_get('Products.egg', item_number, "Reviewsinfo/#{page_number}", params).body)
end
|
ruby
|
{
"resource": ""
}
|
q4590
|
CamperVan.Channel.current_mode_string
|
train
|
def current_mode_string
n = room.membership_limit
s = room.open_to_guests? ? "" : "s"
i = room.locked? ? "i" : ""
"+#{i}l#{s}"
end
|
ruby
|
{
"resource": ""
}
|
q4591
|
CamperVan.Channel.user_for_message
|
train
|
def user_for_message(message)
if user = users[message.user_id]
yield message, user
else
message.user do |user|
yield message, user
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4592
|
MiniSpec.ClassAPI.around
|
train
|
def around *matchers, &proc
proc || raise(ArgumentError, 'block is missing')
matchers.flatten!
matchers = [:*] if matchers.empty?
return if around?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location}
around?.push([matchers, proc])
end
|
ruby
|
{
"resource": ""
}
|
q4593
|
QuestionproRails.EmailList.statistics
|
train
|
def statistics
extracted_statistics = []
unless self.qp_statistics.nil?
extracted_statistics.push(EmailListStatistic.new(qp_statistics))
end
return extracted_statistics
end
|
ruby
|
{
"resource": ""
}
|
q4594
|
CapIt.Capture.capture_command
|
train
|
def capture_command
cmd = "#{@cutycapt_path} --url='#{@url}'"
cmd += " --out='#{@folder}/#{@filename}'"
cmd += " --max-wait=#{@max_wait}"
cmd += " --delay=#{@delay}" if @delay
cmd += " --user-agent='#{@user_agent}'"
cmd += " --min-width='#{@min_width}'"
cmd += " --min-height='#{@min_height}'"
if determine_os == :linux and check_xvfb
xvfb = 'xvfb-run --server-args="-screen 0, 1024x768x24" '
xvfb.concat(cmd)
else
cmd
end
end
|
ruby
|
{
"resource": ""
}
|
q4595
|
Munin.Parser.parse_config
|
train
|
def parse_config(data)
config = {'graph' => {}, 'metrics' => {}}
data.each do |l|
if l =~ /^graph_/
key_name, value = l.scan(/^graph_([\w]+)\s(.*)/).flatten
config['graph'][key_name] = value
# according to http://munin-monitoring.org/wiki/notes_on_datasource_names
elsif l =~ /^[a-zA-Z_][a-zA-Z\d_]*\./
# according to http://munin-monitoring.org/wiki/fieldnames the second one
# can only be [a-z]
matches = l.scan(/^([a-zA-Z_][a-zA-Z\d_]*)\.([a-z]+)\s(.*)/).flatten
config['metrics'][matches[0]] ||= {}
config['metrics'][matches[0]][matches[1]] = matches[2]
end
end
# Now, lets process the args hash
if config['graph'].key?('args')
config['graph']['args'] = parse_config_args(config['graph']['args'])
end
config
end
|
ruby
|
{
"resource": ""
}
|
q4596
|
Munin.Parser.parse_error
|
train
|
def parse_error(lines)
if lines.size == 1
case lines.first
when '# Unknown service' then raise UnknownService
when '# Bad exit' then raise BadExit
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4597
|
Munin.Parser.parse_config_args
|
train
|
def parse_config_args(args)
result = {}
args.scan(/--?([a-z\-\_]+)\s([\d]+)\s?/).each do |arg|
result[arg.first] = arg.last
end
{'raw' => args, 'parsed' => result}
end
|
ruby
|
{
"resource": ""
}
|
q4598
|
DeviseOtt.Tokens.register
|
train
|
def register(token, email, granted_to_email, access_count, expire)
save_config(token, {email: email, granted_to_email: granted_to_email, access_count: access_count})
@redis.expire(token, expire)
token
end
|
ruby
|
{
"resource": ""
}
|
q4599
|
DeviseOtt.Tokens.access
|
train
|
def access(token, email)
config = load_config(token)
return false unless config
return false unless config[:email].to_s == email.to_s
return false unless config[:access_count] > 0
save_config(token, config.merge(access_count: config[:access_count] - 1))
true
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.