_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 >... | 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 ... | 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(:valid... | 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
}
... | 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_... | 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.g... | 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.t... | 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
... | 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.res... | 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
... | 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... | 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 =... | 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 =... | 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",
... | 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... | 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.... | 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)
... | 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.
... | 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/... | 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 ||= MiniSpe... | 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?(metho... | 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... | 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
... | 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... | 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")
... | 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)).... | 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... | 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}"
... | 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])... | 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} (#{hos... | 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... | 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"
#... | 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 = [pos... | 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 ... | 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["c... | 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"
re... | 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,... | 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
memor... | 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,
... | 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,
... | 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] ... | 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 <<... | 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)
@p... | 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_install... | 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
s... | 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['Categ... | 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
}
JS... | 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,
... | 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(... | 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(... | 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-h... | 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
... | 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.