_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9000 | Redstruct.Factory.delete | train | def delete(options = {})
return each({ match: '*', count: 500, max_iterations: 1_000_000, batch_size: 500 }.merge(options)) do |keys|
@connection.del(*keys)
end
end | ruby | {
"resource": ""
} |
q9001 | Redstruct.Factory.script | train | def script(script, **options)
return Redstruct::Script.new(script: script, connection: @connection, **options)
end | ruby | {
"resource": ""
} |
q9002 | FocuspointRails.UploaderAdditions.crop_with_focuspoint | train | def crop_with_focuspoint(width = nil, height = nil)
if self.respond_to? "resize_to_limit"
begin
x = model.focus_x || 0
y = -(model.focus_y || 0)
manipulate! do |img|
orig_w = img['width']
orig_h = img['height']
ratio = width.to_f / height... | ruby | {
"resource": ""
} |
q9003 | Breeze.Veur.report | train | def report(title, columns, rows)
table = capture_table([columns] + rows)
title = "=== #{title} "
title << "=" * [(table.split($/).max{|a,b| a.size <=> b.size }.size - title.size), 3].max
puts title
puts table
end | ruby | {
"resource": ""
} |
q9004 | Breeze.Veur.capture_table | train | def capture_table(table)
return 'none' if table.size == 1 # the first row is for column titles
$stdout = StringIO.new # start capturing the output
print_table(table.map{ |row| row.map(&:to_s) })
output = $stdout
$stdout = STDOUT # restore normal output
return output.string
... | ruby | {
"resource": ""
} |
q9005 | AndFeathers.Archive.to_io | train | def to_io(package_type, traversal = :each)
package_type.open do |package|
package.add_directory(@initial_version)
send(traversal) do |child|
case child
when File
package.add_file(child)
when Directory
package.add_directory(child)
end... | ruby | {
"resource": ""
} |
q9006 | Truty.Conversion.czech_html | train | def czech_html(input)
coder = HTMLEntities.new
encoded = coder.encode(input, :named, :decimal)
czech_diacritics.each { |k, v| encoded.gsub!(k, v) }
encoded
end | ruby | {
"resource": ""
} |
q9007 | FreelingClient.Client.call | train | def call(text)
output = []
file = Tempfile.new('foo', encoding: 'utf-8')
begin
file.write(text)
file.close
stdin, stdout, stderr = Open3.popen3(command(file.path))
Timeout::timeout(@timeout) {
until (line = stdout.gets).nil?
output << line.chomp
... | ruby | {
"resource": ""
} |
q9008 | Cathode.Version.action? | train | def action?(resource, action)
resource = resource.to_sym
action = action.to_sym
return false unless resource?(resource)
_resources.find(resource).actions.names.include? action
end | ruby | {
"resource": ""
} |
q9009 | MARC.MARC4J.marc4j_to_rubymarc | train | def marc4j_to_rubymarc(marc4j)
rmarc = MARC::Record.new
rmarc.leader = marc4j.getLeader.marshal
marc4j.getControlFields.each do |marc4j_control|
rmarc.append( MARC::ControlField.new(marc4j_control.getTag(), marc4j_control.getData ) )
end
marc4j.getDataFields.each do |marc4j_data... | ruby | {
"resource": ""
} |
q9010 | MARC.MARC4J.rubymarc_to_marc4j | train | def rubymarc_to_marc4j(rmarc)
marc4j = @factory.newRecord(rmarc.leader)
rmarc.each do |f|
if f.is_a? MARC::ControlField
new_field = @factory.newControlField(f.tag, f.value)
else
new_field = @factory.new_data_field(f.tag, f.indicator1.ord, f.indicator2.ord)
f.eac... | ruby | {
"resource": ""
} |
q9011 | MARC.MARC4J.require_marc4j_jar | train | def require_marc4j_jar(jardir)
unless defined? JRUBY_VERSION
raise LoadError.new, "MARC::MARC4J requires the use of JRuby", nil
end
if jardir
Dir.glob("#{jardir}/*.jar") do |x|
require x
end
else
Dir.glob(File.join(DEFAULT_JAR_RELATIVE_DIR, "*.jar")) do ... | ruby | {
"resource": ""
} |
q9012 | Temppath.Generator.mkdir | train | def mkdir(option={})
mode = option[:mode] || 0700
path = create(option)
path.mkdir(mode)
return path
end | ruby | {
"resource": ""
} |
q9013 | Temppath.Generator.touch | train | def touch(option={})
mode = option[:mode] || 0600
path = create(option)
path.open("w", mode)
return path
end | ruby | {
"resource": ""
} |
q9014 | VoterLove.Voter.up_vote | train | def up_vote(votable)
is_votable?(votable)
vote = get_vote(votable)
if vote
if vote.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
vote.up_vote = true
votable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_v... | ruby | {
"resource": ""
} |
q9015 | VoterLove.Voter.up_vote! | train | def up_vote!(votable)
begin
up_vote(votable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end | ruby | {
"resource": ""
} |
q9016 | VoterLove.Voter.down_vote! | train | def down_vote!(votable)
begin
down_vote(votable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end | ruby | {
"resource": ""
} |
q9017 | VoterLove.Voter.up_voted? | train | def up_voted?(votable)
is_votable?(votable)
vote = get_vote(votable)
return false if vote.nil?
return true if vote.has_attribute?(:up_vote) && vote.up_vote
false
end | ruby | {
"resource": ""
} |
q9018 | Spirit.Manifest.check_types | train | def check_types(key='root', expected=TYPES, actual=self, opts={})
bad_type(key, expected, actual, opts) unless actual.is_a? expected.class
case actual
when Hash then actual.each { |k, v| check_types(k, expected[k], v) }
when Enumerable then actual.each { |v| check_types(key, expected.first, v, e... | ruby | {
"resource": ""
} |
q9019 | Cellula.WolframCodeRule.next_generation_cell | train | def next_generation_cell(left, middle, right)
case [left, middle, right]
when [1,1,1] then @binary_string[0].to_i
when [1,1,0] then @binary_string[1].to_i
when [1,0,1] then @binary_string[2].to_i
when [1,0,0] then @binary_string[3].to_i
when [0,1,1] then @binary_string[4].to_i
... | ruby | {
"resource": ""
} |
q9020 | JiraIssues.JiraIssueMapper.call | train | def call(issue)
status = decode_status(issue)
{
key: issue.key,
type: issue.issuetype.name,
priority: issue.priority.name,
status: status,
#description: i.description,
summary: issue.summary,
created_date: issue.created,
closed_... | ruby | {
"resource": ""
} |
q9021 | AndFeathers.Directory.path | train | def path
if @parent
::File.join(@parent.path, name)
else
if name != '.'
::File.join('.', name)
else
name
end
end
end | ruby | {
"resource": ""
} |
q9022 | AndFeathers.Directory.| | train | def |(other)
if !other.is_a?(Directory)
raise ArgumentError, "#{other} is not a Directory"
end
dup.tap do |directory|
other.files.each do |file|
directory.add_file(file.dup)
end
other.directories.each do |new_directory|
existing_directory = @direct... | ruby | {
"resource": ""
} |
q9023 | AndFeathers.Directory.each | train | def each(&block)
files.each(&block)
directories.each do |subdirectory|
block.call(subdirectory)
subdirectory.each(&block)
end
end | ruby | {
"resource": ""
} |
q9024 | Characterizable.BetterHash.slice | train | def slice(*keep)
inject(Characterizable::BetterHash.new) do |memo, ary|
if keep.include?(ary[0])
memo[ary[0]] = ary[1]
end
memo
end
end | ruby | {
"resource": ""
} |
q9025 | QueueToTheFuture.Job.method_missing | train | def method_missing(*args, &block)
Thread.pass until defined?(@result)
case @result
when Exception
def self.method_missing(*args, &block); raise @result; end
else
def self.method_missing(*args, &block); @result.send(*args, &block); end
end
self.method_mis... | ruby | {
"resource": ""
} |
q9026 | EnumerateBy.MacroMethods.enumerate_by | train | def enumerate_by(attribute = :name, options = {})
options.reverse_merge!(:cache => true)
options.assert_valid_keys(:cache)
extend EnumerateBy::ClassMethods
extend EnumerateBy::Bootstrapped
include EnumerateBy::InstanceMethods
# The attribute representing a record's enum... | ruby | {
"resource": ""
} |
q9027 | EnumerateBy.ClassMethods.typecast_enumerator | train | def typecast_enumerator(enumerator)
if enumerator.is_a?(Array)
enumerator.flatten!
enumerator.map! {|value| typecast_enumerator(value)}
enumerator
else
enumerator.is_a?(Symbol) ? enumerator.to_s : enumerator
end
end | ruby | {
"resource": ""
} |
q9028 | Humpyard.Page.root_elements | train | def root_elements(yield_name = 'main')
# my own elements
ret = elements.where('container_id IS NULL and page_yield_name = ?', yield_name.to_s).order('position ASC')
# sibling shared elements
unless siblings.empty?
ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) an... | ruby | {
"resource": ""
} |
q9029 | Humpyard.Page.child_pages | train | def child_pages options={}
if content_data.is_humpyard_dynamic_page?
content_data.child_pages
else
if options[:single_root] and is_root_page?
Page.where(["parent_id = ? or parent_id IS NULL and NOT id = ?", id, id])
else
children
end
end
end | ruby | {
"resource": ""
} |
q9030 | Humpyard.Page.last_modified | train | def last_modified options = {}
changed_at = [Time.zone.at(::File.new("#{Rails.root}").mtime), created_at, updated_at, modified_at]
if(options[:include_pages])
changed_at << Humpyard::Page.select('updated_at').order('updated_at DESC').first.updated_at
end
(changed_at - [nil]... | ruby | {
"resource": ""
} |
q9031 | Dragonfly.DropboxDataStore.url_for | train | def url_for(path, opts = {})
path = absolute(path)
(opts[:expires] ? storage.media(path) : storage.shares(path))['url']
end | ruby | {
"resource": ""
} |
q9032 | BoardGameGrid.Square.attribute_match? | train | def attribute_match?(attribute, value)
hash_obj_matcher = lambda do |obj, k, v|
value = obj.send(k)
if !value.nil? && v.is_a?(Hash)
v.all? { |k2,v2| hash_obj_matcher.call(value, k2, v2) }
else
value == v
end
end
hash_obj_matcher.call(self, attribute... | ruby | {
"resource": ""
} |
q9033 | Dio.ModuleBase.included | train | def included(base)
my_injector = injector
injector_holder = Module.new do
define_method :__dio_injector__ do
my_injector
end
end
base.extend(ClassMethods, injector_holder)
base.include(InstanceMethods)
end | ruby | {
"resource": ""
} |
q9034 | Smsified.OneAPI.send_sms | train | def send_sms(options)
raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash)
raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil?
raise ArgumentError, ':address is required' if options[:address].nil?
raise Argument... | ruby | {
"resource": ""
} |
q9035 | Smsified.OneAPI.method_missing | train | def method_missing(method, *args)
if method.to_s.match /subscription/
if args.size == 2
@subscriptions.send method, args[0], args[1]
else
@subscriptions.send method, args[0]
end
else
if method == :delivery_status || method == :retrieve_sms || method == :se... | ruby | {
"resource": ""
} |
q9036 | Aker::Authorities.AutomaticAccess.amplify! | train | def amplify!(user)
user.portals << @portal unless user.portals.include?(@portal)
user.default_portal = @portal unless user.default_portal
user
end | ruby | {
"resource": ""
} |
q9037 | SimpleMetarParser.Metar.decode | train | def decode
self.raw_splits.each do |split|
self.modules.each do |m|
m.decode_split(split)
end
end
end | ruby | {
"resource": ""
} |
q9038 | Domain.Factory.sbyc | train | def sbyc(super_domain = Object, &pred)
Class.new(super_domain){ extend SByC.new(super_domain, pred) }
end | ruby | {
"resource": ""
} |
q9039 | Wireless.SynchronizedStore.get_or_create | train | def get_or_create(key)
@lock.synchronize do
if @store.include?(key)
@store[key]
elsif block_given?
@store[key] = yield
else
# XXX don't expose the receiver as this class is an internal
# implementation detail
raise Wireless::KeyError.new(
... | ruby | {
"resource": ""
} |
q9040 | UnlockGateway.Controller.transition_state | train | def transition_state(state)
authorize @contribution
@initiative = @contribution.initiative
@user = @contribution.user
state = state.to_sym
transition = @contribution.transition_by_state(state)
initial_state = @contribution.state_name
resource_name = @contribution.class.model_na... | ruby | {
"resource": ""
} |
q9041 | Machined.CLI.rack_options | train | def rack_options # :nodoc:
symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options|
rack_options[:environment] = environment
rack_options[:Port] = rack_options.delete :port
rack_options[:Host] = rack_options.delete :host
rack_options[:app] = machined
... | ruby | {
"resource": ""
} |
q9042 | Machined.CLI.symbolized_options | train | def symbolized_options(*keys) # :nodoc:
@symbolized_options ||= begin
opts = {}.merge(options)
opts.merge! saved_options if saved_options?
opts.symbolize_keys
end
@symbolized_options.slice(*keys)
end | ruby | {
"resource": ""
} |
q9043 | LookUpTable.ClassMethods.look_up_table | train | def look_up_table(lut_key, options = {}, &block)
options = {
:batch_size => 10000,
:prefix => "#{self.name}/",
:read_on_init => false,
:use_cache => true,
:sql_mode => true,
:where => nil
}.merge(options)
self.lut_set_p... | ruby | {
"resource": ""
} |
q9044 | LookUpTable.ClassMethods.lut | train | def lut(lut_key = nil, lut_item_key = nil)
@lut ||= {}
if lut_key.nil?
hash = {}
self.lut_keys.each { |key| hash[key] = self.lut(key) } # CHECK: use .inject?
return hash
end
@lut[lut_key.intern] ||= lut_read(lut_key) || {} if lut_key.respond_to?(:intern)
self.lut... | ruby | {
"resource": ""
} |
q9045 | LookUpTable.ClassMethods.lut_reload | train | def lut_reload(lut_key = nil)
if lut_key
lut_reset(lut_key)
lut(lut_key)
else
lut_keys.each { |k| lut_reload(k) }
end
lut_keys
end | ruby | {
"resource": ""
} |
q9046 | LookUpTable.ClassMethods.lut_read | train | def lut_read(name)
return nil unless options = lut_options(name)# HACK
if options[:use_cache]
lut_read_from_cache(name)
else
lut_read_without_cache(name)
end
end | ruby | {
"resource": ""
} |
q9047 | ActiveHarmony.SynchronizerConfiguration.synchronizable_for_types | train | def synchronizable_for_types(types)
@synchronizable_fields.select do |field_description|
types.include?(field_description[:type])
end.collect do |field_description|
field_description[:field]
end
end | ruby | {
"resource": ""
} |
q9048 | Measurement.Base.to_s | train | def to_s(unit = nil, precision = 0)
if unit.to_s =~ /_and_/
units = unit.to_s.split('_and_').map do |unit|
self.class.fetch_scale(unit)
end
UnitGroup.new(units).format(@amount, precision)
else
unit = self.class.fetch_scale(unit)
unit.format(@amount,... | ruby | {
"resource": ""
} |
q9049 | MatchyMatchy.MatchList.<< | train | def <<(match)
if include?(match)
match.reject!
else
@matches << match
@matches.sort!
@matches.pop.reject! if @matches.size > @capacity
end
self
end | ruby | {
"resource": ""
} |
q9050 | MethodInfo.AncestorMethodStructure.method_owner | train | def method_owner(method_symbol)
# Under normal circumstances just calling @object.method(method_symbol) would work,
# but this will go wrong if the object has redefined the method method.
method = Object.instance_method(:method).bind(@object).call(method_symbol)
method.owner
rescue NameErro... | ruby | {
"resource": ""
} |
q9051 | PhpFpmDocker.Launcher.parse_config | train | def parse_config # rubocop:disable MethodLength
# Test for file usability
fail "Config file '#{@config_path}' not found"\
unless @config_path.file?
fail "Config file '#{@config_path}' not readable"\
unless @config_path.readable?
@ini_file = IniFile.load(@config_path)
begin
... | ruby | {
"resource": ""
} |
q9052 | PhpFpmDocker.Launcher.pools_config_content_from_file | train | def pools_config_content_from_file(config_path)
ini_file = IniFile.load(config_path)
ret_val = []
ini_file.each_section do |section|
ret_val << [section, ini_file[section]]
end
ret_val
end | ruby | {
"resource": ""
} |
q9053 | PhpFpmDocker.Launcher.pools_config_contents | train | def pools_config_contents
ret_val = []
# Loop over
Dir[@pools_directory.join('*.conf').to_s].each do |config_path|
ret_val += pools_config_content_from_file(config_path)
end
ret_val
end | ruby | {
"resource": ""
} |
q9054 | PhpFpmDocker.Launcher.pools_from_config | train | def pools_from_config
configs = {}
pools_config_contents.each do |section|
# Hash section name and content
d = Digest::SHA2.new(256)
hash = d.reset.update(section[0]).update(section[1].to_s).to_s
configs[hash] = {
name: section[0],
config: section[1]
... | ruby | {
"resource": ""
} |
q9055 | Tkar.Primitives.polybox | train | def polybox args, key_args
dx, dy = args
# return a proc to make the info needed to instantiate/update
proc do |tkaroid, cos_r, sin_r|
x = tkaroid.x
y = tkaroid.y
params = tkaroid.params
ex = dx[params] rescue dx
ey = dy[params] rescue dy
points... | ruby | {
"resource": ""
} |
q9056 | Redlander.ModelProxy.delete_all | train | def delete_all(pattern = {})
result = true
each(pattern) { |st| result &&= delete(st) }
result
end | ruby | {
"resource": ""
} |
q9057 | Redlander.ModelProxy.find | train | def find(scope, pattern = {})
case scope
when :first
each(pattern).first
when :all
each(pattern).to_a
else
raise RedlandError, "Invalid search scope '#{scope}' specified."
end
end | ruby | {
"resource": ""
} |
q9058 | CodeCache.Repo.location_in_cache | train | def location_in_cache( revision = nil )
begin
elements = [cache, repo_type, split_url, revision].flatten.compact.collect { |i| i.to_s }
File.join( elements )
rescue => e
raise CacheCalculationError.new(e.msg + e.backtrace.to_s)
end
end | ruby | {
"resource": ""
} |
q9059 | Mango.ContentPage.method_missing | train | def method_missing(method_name, *args, &block)
key = method_name.to_s
attributes.has_key?(key) ? attributes[key] : super
end | ruby | {
"resource": ""
} |
q9060 | Kawaii.ContentManager.load_image | train | def load_image(path, tileable = false)
if !@images[path]
@images[path] = Gosu::Image.new(@window, "#{@root}/#{path}", tileable)
end
@images[path]
end | ruby | {
"resource": ""
} |
q9061 | MustacheRender.Mustache.partial | train | def partial(name)
name = self.class.generate_template_name name, config.file_template_extension
# return self.read_template_from_media name, media
@_cached_partials ||= {}
(@_cached_partials[media] ||= {})[name] ||= self.read_template_from_media name, media
end | ruby | {
"resource": ""
} |
q9062 | HasPrice.HasPrice.has_price | train | def has_price(options = {}, &block)
attribute = options[:attribute] || :price
free = !block_given? && options[:free]
define_method attribute.to_sym do
builder = PriceBuilder.new self
builder.instance_eval &block unless free
builder.price
end
end | ruby | {
"resource": ""
} |
q9063 | Octo.Scheduler.schedule_counters | train | def schedule_counters
counter_classes = [
Octo::ProductHit,
Octo::CategoryHit,
Octo::TagHit,
Octo::ApiHit,
Octo::NewsfeedHit
]
counter_classes.each do |clazz|
clazz.send(:get_typecounters).each do |counter|
name = [clazz, counter].join('::')
... | ruby | {
"resource": ""
} |
q9064 | Hosties.HasAttributes.have_attributes | train | def have_attributes(attr, *more)
sum = (more << attr)
sum.each do |name|
raise ArgumentError, "Reserved attribute name #{name}" if @verbotten.include?(name)
end
@attributes += sum
end | ruby | {
"resource": ""
} |
q9065 | Hosties.HasAttributes.where | train | def where(name)
# Must define the attributes before constraining them
raise ArgumentError, "Unknown attribute: #{name}" unless @attributes.include? name
@constraints[name] = AttributeConstraint.new(name)
end | ruby | {
"resource": ""
} |
q9066 | Hosties.HasAttributes.valid? | train | def valid?(name, value)
if @constraints.include? name then
constraints[name].possible_vals.include? value
else true end
end | ruby | {
"resource": ""
} |
q9067 | XBeeRuby.XBee.open | train | def open
@serial ||= SerialPort.new @port, @rate
@serial_input = Enumerator.new { |y| loop do
y.yield @serial.readbyte
end }
@connected = true
end | ruby | {
"resource": ""
} |
q9068 | UseCaseValidations.ClassMethods.inherited | train | def inherited(base)
dup = _validators.dup
base._validators = dup.each { |k, v| dup[k] = v.dup }
super
end | ruby | {
"resource": ""
} |
q9069 | MaRuKu.Section.numerate | train | def numerate(a=[])
self.section_number = a
section_children.each_with_index do |c,i|
c.numerate(a.clone.push(i+1))
end
if h = self.header_element
h.attributes[:section_number] = self.section_number
end
end | ruby | {
"resource": ""
} |
q9070 | ActsAsFeatured.ClassMethods.acts_as_featured | train | def acts_as_featured(attribute, options = {})
cattr_accessor :featured_attribute
cattr_accessor :featured_attribute_scope
self.featured_attribute = attribute
self.featured_attribute_scope = options[:scope] || false
if scope_name = options[:create_scope]
scope_name = attribute if ... | ruby | {
"resource": ""
} |
q9071 | TodoLint.Judge.make_charge | train | def make_charge
if !todo.annotated?
"Missing due date annotation"
elsif todo.due_date.overdue? && todo.tag?
"Overdue due date #{todo.due_date.to_date} via tag"
elsif todo.due_date.overdue?
"Overdue due date"
end
end | ruby | {
"resource": ""
} |
q9072 | XivelyConnector.Datastream.<< | train | def <<(measurement)
# Make sure the value provided is a datapoint
datapoint = cast_to_datapoint(measurement)
# If only_save_changes is true, ignore datapoints whose value is the same as the current value
if only_save_changes and BigDecimal.new(datapoint.value) == BigDecimal.new(current_value)
... | ruby | {
"resource": ""
} |
q9073 | XivelyConnector.Datastream.cast_to_datapoint | train | def cast_to_datapoint(measurement, at=Time.now())
@logger.debug "cast_to_datapoint(#{measurement.inspect})"
if measurement.is_a?(Xively::Datapoint)
return measurement
elsif measurement.is_a?(Hash)
raise "The datapoint hash does not contain :at" unless measurement[:at]
raise "Th... | ruby | {
"resource": ""
} |
q9074 | XivelyConnector.Datastream.save_datapoints | train | def save_datapoints
@logger.debug "Saving #{datapoints.size} datapoints to the #{id} datastream"
response = XivelyConnector.connection.post("/v2/feeds/#{device.id}/datastreams/#{id}/datapoints",
:body => {:datapoints => datapoints}.to_json)
# If the re... | ruby | {
"resource": ""
} |
q9075 | Coach4rb.Client.put | train | def put(url, payload, options={}, &block)
http_options = options.merge(@basic_options)
if block_given?
RestClient.put(url, payload, http_options, &block)
else
RestClient.put(url, payload, http_options)
end
end | ruby | {
"resource": ""
} |
q9076 | Coach4rb.Client.delete | train | def delete(url, options={}, &block)
http_options = options.merge(@basic_options)
if block_given?
RestClient.delete(url, http_options, &block)
else
RestClient.delete(url, http_options)
end
end | ruby | {
"resource": ""
} |
q9077 | ObjectAttorney.ClassMethods.inherited | train | def inherited(base)
base.allegations = allegations.clone
base.defendant_options = defendant_options.clone
super
end | ruby | {
"resource": ""
} |
q9078 | Rexport.ExportMethods.to_s | train | def to_s
String.new.tap do |result|
result << header * '|' << "\n"
records.each do |record|
result << record * '|' << "\n"
end
end
end | ruby | {
"resource": ""
} |
q9079 | Rexport.ExportMethods.to_csv | train | def to_csv(objects = nil)
seed_records(objects) unless objects.nil?
CSV.generate do |csv|
csv << header
records.each do |record|
csv << record
end
end
end | ruby | {
"resource": ""
} |
q9080 | Rexport.ExportMethods.get_klass_from_path | train | def get_klass_from_path(path, klass = export_model)
return klass unless (association_name = path.shift)
get_klass_from_path(path, klass.reflect_on_association(association_name.to_sym).klass)
end | ruby | {
"resource": ""
} |
q9081 | Diffable.InstanceMethods.diff | train | def diff(other)
check_class_compatibility(self, other)
self_attribs = self.get_attributes(self.class.excluded_fields)
other_attribs = other.get_attributes(other.class.excluded_fields)
change = compare_objects(self_attribs, other_attribs, self, other)
#the last bit - no... | ruby | {
"resource": ""
} |
q9082 | Diffable.InstanceMethods.get_attributes | train | def get_attributes(excluded)
attribs = attributes.dup
attribs.delete_if { |key, value|
(!excluded.nil? and excluded.include?(key)) or key == "id" }
end | ruby | {
"resource": ""
} |
q9083 | Diffable.InstanceMethods.reflected_names | train | def reflected_names(obj)
classes = obj.reflections
class_names = []
classes.each do |key, cl|
if eval(cl.class_name).respond_to?("diffable") \
and cl.association_class != ActiveRecord::Associations::BelongsToAssociation
class_names << key
end
end
class_... | ruby | {
"resource": ""
} |
q9084 | PayuLatam.SubscriptionService.plan | train | def plan
# si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario
# recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el
# como variable de clase @plan_id
if @current_user.plan_id.nil?
if @plan_id.nil?
... | ruby | {
"resource": ""
} |
q9085 | PayuLatam.SubscriptionService.create_card | train | def create_card
raise StandardError, 'Cliente null' if @client.nil?
# la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta
card = PayuLatam::Card.new(@client)
# hay un metodo card_params que genera el objeto a enviar con los datos correctos
# se asignan ... | ruby | {
"resource": ""
} |
q9086 | PayuLatam.SubscriptionService.find_card | train | def find_card
@client.remove_cards
card = PayuLatam::Card.new(@client) # info de payu
card.load( PayuCard.find(@selected_card).token )
@client.add_card({token: card.resource['token']})
end | ruby | {
"resource": ""
} |
q9087 | DataMapper.Paginator.limit | train | def limit options = {}
# Remove this key if we come from limit_page method.
page = options.delete :page
query = options.dup
collection = new_collection scoped_query( options = {
:limit => options[:limit],
:offset => options[:offset],
:order => [options[:order]]
}.me... | ruby | {
"resource": ""
} |
q9088 | DataMapper.Paginator.limit_page | train | def limit_page page = nil, options = {}
if page.is_a?( Hash )
options = page
else
options[:page] = page.to_i
end
options[:page] = options[:page].to_i > 0 ? options[:page] : DataMapper::Paginator.default[:page]
options[:limit] = options[:limit].to_i || DataMapper::Paginator... | ruby | {
"resource": ""
} |
q9089 | DataMapper.Paginator.calculate_total_records | train | def calculate_total_records query
# Remove those keys from the query
query.delete :page
query.delete :limit
query.delete :offset
collection = new_collection scoped_query( query )
collection.count.to_i
end | ruby | {
"resource": ""
} |
q9090 | NetworkExecutive.ScheduledProgram.+ | train | def +( other_program )
raise ArgumentError if @program.class != other_program.class
additional_duration = other_program.duration + 1
program.duration += additional_duration
occurrence.duration += additional_duration
occurrence.end_time += additional_duration
self
end | ruby | {
"resource": ""
} |
q9091 | Kharon.Processor.before_all | train | def before_all(key, options)
required(key) if (options.has_key?(:required) and options[:required] == true)
if options.has_key?(:dependencies)
dependencies(key, options[:dependencies])
elsif options.has_key?(:dependency)
dependency(key, options[:dependency])
end
end | ruby | {
"resource": ""
} |
q9092 | Kharon.Processor.store | train | def store(key, process, options = {})
unless (options.has_key?(:extract) and options[:extract] == false)
if validator.datas.has_key?(key)
value = ((options.has_key?(:cast) and options[:cast] == false) ? validator.datas[key] : process.call(validator.datas[key]))
if(options.has_key?(:in)... | ruby | {
"resource": ""
} |
q9093 | Kharon.Processor.raise_type_error | train | def raise_type_error(key, type)
raise_error(type: "type", key: key, supposed: type, found: key.class)
end | ruby | {
"resource": ""
} |
q9094 | Kharon.Processor.required | train | def required(key)
raise_error(type: "required", key: key) unless validator.datas.has_key?(key)
end | ruby | {
"resource": ""
} |
q9095 | Kharon.Processor.dependency | train | def dependency(key, dependency)
raise_error(type: "dependency", key: "key", needed: dependency) unless validator.datas.has_key?(dependency)
end | ruby | {
"resource": ""
} |
q9096 | Kharon.Processor.is_typed? | train | def is_typed?(key, type)
return (!validator.datas.has_key?(key) or validator.datas[key].kind_of?(type))
end | ruby | {
"resource": ""
} |
q9097 | Kharon.Processor.in_array? | train | def in_array?(key, values)
raise_error(type: "array.in", key: key, supposed: values, value: validator.datas[key]) unless (values.empty? or values.include?(validator.datas[key]))
end | ruby | {
"resource": ""
} |
q9098 | Kharon.Processor.equals_to? | train | def equals_to?(key, value)
raise_error(type: "equals", key: key, supposed: value, found: validator.datas[key]) unless validator.datas[key] == value
end | ruby | {
"resource": ""
} |
q9099 | Kharon.Processor.match? | train | def match?(key, regex)
return (!validator.datas.has_key?(key) or validator.datas[key].to_s.match(regex))
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.