_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q27300 | Woodhouse::Worker.ClassMethods.method_missing | test | def method_missing(method, *args, &block)
if method.to_s =~ /^asynch?_(.*)/
if instance_methods(false).detect{|meth| meth.to_s == $1 }
Woodhouse.dispatch(@worker_name, $1, args.first)
else
super
end
else
super
end
end | ruby | {
"resource": ""
} |
q27301 | Woodhouse.Layout.add_node | test | def add_node(node)
if node.respond_to?(:to_sym)
node = Woodhouse::Layout::Node.new(node.to_sym)
end
expect_arg :node, Woodhouse::Layout::Node, node
@nodes << node
node
end | ruby | {
"resource": ""
} |
q27302 | Woodhouse.Layout.node | test | def node(name)
name = name.to_sym
@nodes.detect{|node|
node.name == name
}
end | ruby | {
"resource": ""
} |
q27303 | Scheherazade.CharacterBuilder.canonical | test | def canonical(attribute_list)
case attribute_list
when nil then {}
when Hash then attribute_list
when Array
attribute_list.map do |attributes|
case attributes
when Symbol
{attributes => AUTO}
when Hash
attributes
else
... | ruby | {
"resource": ""
} |
q27304 | Scheherazade.Story.imagine | test | def imagine(character_or_model, attributes = nil)
character = to_character(character_or_model)
prev, @building = @building, [] # because method might be re-entrant
CharacterBuilder.new(character).build(attributes) do |ar|
ar.save!
# While errors on records associated with :has_many wil... | ruby | {
"resource": ""
} |
q27305 | Scheherazade.Story.with | test | def with(temp_current)
keys = temp_current.keys.map{|k| to_character(k)}
previous_values = current.values_at(*keys)
current.merge!(Hash[keys.zip(temp_current.values)])
yield
ensure
current.merge!(Hash[keys.zip(previous_values)])
end | ruby | {
"resource": ""
} |
q27306 | DeferrableGratification.Primitives.failure | test | def failure(exception_class_or_message, message_or_nil = nil)
blank.tap do |d|
d.fail(
case exception_class_or_message
when Exception
raise ArgumentError, "can't specify both exception and message" if message_or_nil
exception_class_or_message
when Clas... | ruby | {
"resource": ""
} |
q27307 | FantasticRobot.Request::SendAudio.file_length | test | def file_length
if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE
self.errors.add :audio, "It's length is excesive. #{MAX_FILE_SIZE} is the limit."
return false
end
return true
end | ruby | {
"resource": ""
} |
q27308 | FantasticRobot.Connection.api_call | test | def api_call method, payload
raise ArgumentError, "API method not specified." if method.blank?
payload ||= {}
res = @conn.post method.to_s, payload
raise Faraday::Error, "Wrong response: #{res.inspect}" if (res.status != 200)
return res
end | ruby | {
"resource": ""
} |
q27309 | Oedipus.Index.multi_search | test | def multi_search(queries)
unless queries.kind_of?(Hash)
raise ArgumentError, "Argument must be a Hash of named queries (#{queries.class} given)"
end
stmts = []
bind_values = []
queries.each do |key, args|
str, *values = @builder.select(*extract_query_data(args))
... | ruby | {
"resource": ""
} |
q27310 | Whereabouts.ClassMethods.has_whereabouts | test | def has_whereabouts klass=:address, *args
options = args.extract_options!
# extend Address with class name if not defined.
unless klass == :address || Object.const_defined?(klass.to_s.camelize)
create_address_class(klass.to_s.camelize)
end
# Set the has_one relationship and accept... | ruby | {
"resource": ""
} |
q27311 | Whereabouts.ClassMethods.set_validators | test | def set_validators klass, fields=[]
_single = validate_singleton_for(klass)
klass.to_s.camelize.constantize.class_eval do
fields.each do |f|
validates_presence_of f,
:if => lambda {|a| a.addressable_type.constantize.send(_single).include?(f)}
end
end
end | ruby | {
"resource": ""
} |
q27312 | Whereabouts.ClassMethods.create_address_class | test | def create_address_class(class_name, &block)
klass = Class.new Address, &block
Object.const_set class_name, klass
end | ruby | {
"resource": ""
} |
q27313 | Qwirk.Worker.event_loop | test | def event_loop
Qwirk.logger.debug "#{self}: Starting receive loop"
@start_worker_time = Time.now
until @stopped || (config.stopped? && @impl.ready_to_stop?)
Qwirk.logger.debug "#{self}: Waiting for read"
@start_read_time = Time.now
msg = @impl.receive_message
if msg
... | ruby | {
"resource": ""
} |
q27314 | ActiveRecord.Base.arel_attributes_values | test | def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
attrs = {}
attribute_names.each do |name|
if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
if include_readonly_attributes || (!... | ruby | {
"resource": ""
} |
q27315 | Bugzilla.Bugzilla.requires_version | test | def requires_version(cmd, version_)
v = check_version(version_)
raise NoMethodError, format('%s is not supported in Bugzilla %s', cmd, v[1]) unless v[0]
end | ruby | {
"resource": ""
} |
q27316 | Clacks.Service.run | test | def run
begin
Clacks.logger.info "Clacks v#{Clacks::VERSION} started"
if Clacks.config[:pop3]
run_pop3
elsif Clacks.config[:imap]
run_imap
else
raise "Either a POP3 or an IMAP server must be configured"
end
rescue Exception => e
f... | ruby | {
"resource": ""
} |
q27317 | Clacks.Service.imap_validate_options | test | def imap_validate_options(options)
options ||= {}
options[:mailbox] ||= 'INBOX'
options[:count] ||= 5
options[:order] ||= :asc
options[:what] ||= :first
options[:keys] ||= 'ALL'
options[:delete_after_find] ||= false
options[:mailbox] = Net::IMAP.encode_utf7(opti... | ruby | {
"resource": ""
} |
q27318 | Clacks.Service.imap_find | test | def imap_find(imap)
options = Clacks.config[:find_options]
delete_after_find = options[:delete_after_find]
begin
break if stopping?
uids = imap.uid_search(options[:keys] || 'ALL')
uids.reverse! if options[:what].to_sym == :last
uids = uids.first(options[:count]) if opti... | ruby | {
"resource": ""
} |
q27319 | Ric.Colors.rainbow | test | def rainbow(str)
i=0
ret = ''
str=str.to_s
while(i < str.length)
ch = str[i]
palette = $color_db[0][i % $color_db[0].length ]
ret << (colora(palette,str[i,1]))
i += 1
end
ret
end | ruby | {
"resource": ""
} |
q27320 | SecretSharing.Prime.large_enough_prime | test | def large_enough_prime(input)
standard_primes.each do |prime|
return prime if prime > input
end
fail CannotFindLargeEnoughPrime, "Input too large"
end | ruby | {
"resource": ""
} |
q27321 | SentenceBuilder.SentenceNode.enhance_content | test | def enhance_content(value, separator = ', ')
value.is_a?(Array) ? value.join(separator) : value
end | ruby | {
"resource": ""
} |
q27322 | SecretSharing.Charset.i_to_s | test | def i_to_s(input)
if !input.is_a?(Integer) || input < 0
fail NotPositiveInteger, "input must be a non-negative integer"
end
output = ""
while input > 0
input, codepoint = input.divmod(charset.length)
output.prepend(codepoint_to_char(codepoint))
end
output
... | ruby | {
"resource": ""
} |
q27323 | SecretSharing.Charset.s_to_i | test | def s_to_i(string)
string.chars.reduce(0) do |output, char|
output * charset.length + char_to_codepoint(char)
end
end | ruby | {
"resource": ""
} |
q27324 | SecretSharing.Charset.char_to_codepoint | test | def char_to_codepoint(c)
codepoint = charset.index c
if codepoint.nil?
fail NotInCharset, "Char \"#{c}\" not part of the supported charset"
end
codepoint
end | ruby | {
"resource": ""
} |
q27325 | SecretSharing.Charset.subset? | test | def subset?(string)
(Set.new(string.chars) - Set.new(charset)).empty?
end | ruby | {
"resource": ""
} |
q27326 | SecretSharing.Polynomial.points | test | def points(num_points, prime)
intercept = @coefficients[0] # the first coefficient is the intercept
(1..num_points).map do |x|
y = intercept
(1...@coefficients.length).each do |i|
y = (y + @coefficients[i] * x ** i) % prime
end
Point.new(x, y)
end
end | ruby | {
"resource": ""
} |
q27327 | Mead.EadValidator.validate! | test | def validate!
files = Dir.glob(File.join(@directory, '*.xml')).sort
threads = []
files.map do |path|
threads << Thread.new(path) do |path_t|
eadid = File.basename(path_t, '.xml')
begin
ead = Mead::Ead.new({:file => File.open(path_t), :eadid => eadid})
... | ruby | {
"resource": ""
} |
q27328 | ActionCableNotifications.Model.notify_create | test | def notify_create
self.ChannelPublications.each do |publication, options|
if options[:actions].include? :create
# Checks if records is within scope before broadcasting
records = self.class.scoped_collection(options[:scope])
if options[:scope]==:all or record_within_scope(rec... | ruby | {
"resource": ""
} |
q27329 | ActionCableNotifications.Model.notify_update | test | def notify_update
# Get model changes
if self.respond_to?(:saved_changes) # For Rails >= 5.1
changes = self.saved_changes.transform_values(&:second)
else # For Rails < 5.1
changes = self.changes.transform_values(&:second)
end
# Checks if there are changes in the model
... | ruby | {
"resource": ""
} |
q27330 | ActionCableNotifications.Model.notify_destroy | test | def notify_destroy
self.ChannelPublications.each do |publication, options|
if options[:scope]==:all or options[:actions].include? :destroy
# Checks if record is within scope before broadcasting
if options[:scope]==:all or record_within_scope(self.class.scoped_collection(options[:scope]... | ruby | {
"resource": ""
} |
q27331 | Clacks.Configurator.logger | test | def logger(obj)
%w(debug info warn error fatal level).each do |m|
next if obj.respond_to?(m)
raise ArgumentError, "logger #{obj} does not respond to method #{m}"
end
map[:logger] = obj
end | ruby | {
"resource": ""
} |
q27332 | CurrencySpy.ScraperBase.fetch_rates | test | def fetch_rates
if self.class.superclass.eql?(Object)
raise Exception.new("This method should be invoked from CurrencySpy::Scraper sub class")
else
check_currency_code_validity
rate_results = {}
RATE_DATA.each do |rate|
symbol = rate.to_sym
if self.class.i... | ruby | {
"resource": ""
} |
q27333 | FormatEngine.SpecInfo.parse | test | def parse(target)
#Handle the width option if specified.
if (width = fmt.width) > 0
head, tail = src[0...width], src[width..-1] || ""
else
head, tail = src, ""
end
#Do the parse on the input string or regex.
@prematch, @match, @postmatch = head.partition(tar... | ruby | {
"resource": ""
} |
q27334 | FormatEngine.SpecInfo.grab | test | def grab
width = fmt.width
if width > 0
result, @src = src[0...width], src[width..-1] || ""
elsif width == 0
result, @src = src[0...1], src[1..-1] || ""
elsif width == -1
result, @src = src, ""
else
result, @src = src[0..width], src[(width+1)..-1]... | ruby | {
"resource": ""
} |
q27335 | Bugzilla.Bug.get_comments | test | def get_comments(bugs)
params = {}
# TODO
# this construction should be refactored to a method
params['ids'] = case bugs
when Array
bugs
when Integer || String
[bugs]
else
raise ArgumentError, format('Unknown type of arguments: %s', bugs.class)
e... | ruby | {
"resource": ""
} |
q27336 | Qwirk.Manager.save_persist_state | test | def save_persist_state
return unless @persist_file
new_persist_options = {}
BaseWorker.worker_classes.each do |worker_class|
worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options|
static_options = default... | ruby | {
"resource": ""
} |
q27337 | Caramelize.RedmineWiki.read_pages | test | def read_pages
# get all projects
results_projects = database.query("SELECT id, identifier, name FROM projects;")
results_projects.each do |row_project|
#collect all namespaces
namespaces << OpenStruct.new(identifier: row_project["identifier"], name: row_project["name"])
end
... | ruby | {
"resource": ""
} |
q27338 | Qwirk.PublishHandle.read_response | test | def read_response(timeout, &block)
raise "Invalid call to read_response for #{@producer}, not setup for responding" unless @producer.response_options
# Creates a block for reading the responses for a given message_id (adapter_info). The block will be passed an object
# that responds to timeout_read(t... | ruby | {
"resource": ""
} |
q27339 | RakeCommandFilter.CommandDefinition.add_filter | test | def add_filter(id, pattern, &block)
filter = LineFilter.new(id, pattern, block)
@filters << filter
end | ruby | {
"resource": ""
} |
q27340 | Mixml.Selection.write | test | def write(template = nil)
if not template.nil? then
template = template.to_mixml_template
end
each_node do |node|
if template.nil? then
node.write_xml_to($stdout)
puts
else
pu... | ruby | {
"resource": ""
} |
q27341 | Mixml.Selection.replace | test | def replace(template)
template = template.to_mixml_template
each_node do |node|
value = template.evaluate(node)
node.replace(value)
end
end | ruby | {
"resource": ""
} |
q27342 | Mixml.Selection.rename | test | def rename(template)
template = template.to_mixml_template
each_node do |node|
value = template.evaluate(node)
node.name = value
end
end | ruby | {
"resource": ""
} |
q27343 | Caramelize.GollumOutput.commit_revision | test | def commit_revision(page, markup)
gollum_page = gollum.page(page.title)
if gollum_page
gollum.update_page(gollum_page, gollum_page.name, gollum_page.format, page.body, build_commit(page))
else
gollum.write_page(page.title, markup, page.body, build_commit(page))
end
end | ruby | {
"resource": ""
} |
q27344 | Caramelize.GollumOutput.commit_history | test | def commit_history(revisions, options = {}, &block)
options[:markup] = :markdown if !options[:markup] # target markup
revisions.each_with_index do |page, index|
# call debug output from outside
block.call(page, index) if block_given?
commit_revision(page, options[:markup])
end
... | ruby | {
"resource": ""
} |
q27345 | FormatEngine.FormatSpec.scan_spec | test | def scan_spec(fmt_string)
until fmt_string.empty?
if (match_data = PARSE_REGEX.match(fmt_string))
mid = match_data.to_s
pre = match_data.pre_match
@specs << FormatLiteral.new(pre) unless pre.empty?
@specs << case
when match_data[:var] th... | ruby | {
"resource": ""
} |
q27346 | Caramelize.TracConverter.to_textile | test | def to_textile str
body = body.dup
body.gsub!(/\r/, '')
body.gsub!(/\{\{\{([^\n]+?)\}\}\}/, '@\1@')
body.gsub!(/\{\{\{\n#!([^\n]+?)(.+?)\}\}\}/m, '<pre><code class="\1">\2</code></pre>')
body.gsub!(/\{\{\{(.+?)\}\}\}/m, '<pre>\1</pre>')
# macro
body.gsub!(/\[\[BR\]\]/, '')
... | ruby | {
"resource": ""
} |
q27347 | Ric.Debug.debug2 | test | def debug2(s, opts = {} )
out = opts.fetch(:out, $stdout)
tag = opts.fetch(:tag, '_DFLT_')
really_write = opts.fetch(:really_write, true) # you can prevent ANY debug setting this to false
write_always = opts.fetch(:write_always, false)
raise "ERROR: ':tags' must be an array in debug(), maybe you ... | ruby | {
"resource": ""
} |
q27348 | BarkestSsh.SecureShell.exec | test | def exec(command, options={}, &block)
raise ConnectionClosed.new('Connection is closed.') unless @channel
options = {
on_non_zero_exit_code: :default
}.merge(options || {})
options[:on_non_zero_exit_code] = @options[:on_non_zero_exit_code] if options[:on_non_zero_exit_code] == :defau... | ruby | {
"resource": ""
} |
q27349 | BarkestSsh.SecureShell.upload | test | def upload(local_file, remote_file)
raise ConnectionClosed.new('Connection is closed.') unless @ssh
sftp.upload!(local_file, remote_file)
end | ruby | {
"resource": ""
} |
q27350 | BarkestSsh.SecureShell.download | test | def download(remote_file, local_file)
raise ConnectionClosed.new('Connection is closed.') unless @ssh
sftp.download!(remote_file, local_file)
end | ruby | {
"resource": ""
} |
q27351 | BarkestSsh.SecureShell.write_file | test | def write_file(remote_file, data)
raise ConnectionClosed.new('Connection is closed.') unless @ssh
sftp.file.open(remote_file, 'w') do |f|
f.write data
end
end | ruby | {
"resource": ""
} |
q27352 | GpsUtils.Point.distance | test | def distance(other)
unless other.is_a? Point
raise ArgumentError.new 'other must be a Point.'
end
dlng = GpsUtils::to_radians(other.lng - @lng)
dlat = GpsUtils::to_radians(other.lat - @lat)
x = dlng * Math.cos(dlat / 2)
y = GpsUtils::to_radians(other.lat - @lat)
Math.sqrt(x**2 + y**2) * GpsU... | ruby | {
"resource": ""
} |
q27353 | GpsUtils.BoundingBox.cover? | test | def cover?(point)
p = [point.lat - @nw.lat, point.lng - @se.lng]
p21x = p[0] * @p21
p41x = p[1] * @p41
0 < p21x and p21x < @p21ms and 0 <= p41x and p41x <= @p41ms
end | ruby | {
"resource": ""
} |
q27354 | MongoMapperExt.Paginator.send | test | def send(method, *args, &block)
if respond_to?(method)
super
else
subject.send(method, *args, &block)
end
end | ruby | {
"resource": ""
} |
q27355 | RakeCommandFilter.LineFilterResult.output | test | def output(elapsed)
case @result
when MATCH_SUCCESS
color = :green
header = 'OK'
when MATCH_FAILURE
color = :red
header = 'FAIL'
when MATCH_WARNING
color = :light_red
header = 'WARN'
end
header = header.ljust(12).colorize(color)
s... | ruby | {
"resource": ""
} |
q27356 | Bugzilla.User.get_userinfo | test | def get_userinfo(user)
p = {}
ids = []
names = []
if user.is_a?(Array)
user.each do |u|
names << u if u.is_a?(String)
id << u if u.is_a?(Integer)
end
elsif user.is_a?(String)
names << user
elsif user.is_a?(Integer)
ids << user
... | ruby | {
"resource": ""
} |
q27357 | Dreader.Engine.options | test | def options &block
options = Options.new
options.instance_eval(&block)
@options = options.to_hash
end | ruby | {
"resource": ""
} |
q27358 | Dreader.Engine.column | test | def column name, &block
column = Column.new
column.instance_eval(&block)
@colspec << column.to_hash.merge({name: name})
end | ruby | {
"resource": ""
} |
q27359 | Dreader.Engine.bulk_declare | test | def bulk_declare hash, &block
hash.keys.each do |key|
column = Column.new
column.colref hash[key]
if block
column.instance_eval(&block)
end
@colspec << column.to_hash.merge({name: key})
end
end | ruby | {
"resource": ""
} |
q27360 | Dreader.Engine.read | test | def read args = {}
if args.class == Hash
hash = @options.merge(args)
else
puts "dreader error at #{__callee__}: this function takes a Hash as input"
exit
end
spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename])
sheet = spreadsheet.sheet(hash[:sheet] || ... | ruby | {
"resource": ""
} |
q27361 | Omelette.Util.backtrace_lineno_for_config | test | def backtrace_lineno_for_config(file_path, exception)
# For a SyntaxError, we really need to grep it from the
# exception message, it really appears to be nowhere else. Ugh.
if exception.kind_of? SyntaxError
if m = /:(\d+):/.match(exception.message)
return m[1].to_i
end
... | ruby | {
"resource": ""
} |
q27362 | Omelette.Util.backtrace_from_config | test | def backtrace_from_config(file_path, exception)
filtered_trace = []
found = false
# MRI 2.1+ has exception.backtrace_locations which makes
# this a lot easier, but JRuby 1.7.x doesn't yet, so we
# need to do it both ways.
if (exception.respond_to?(:backtrace_locations) &&
... | ruby | {
"resource": ""
} |
q27363 | Omelette.Util.drain_queue | test | def drain_queue(queue)
result = []
queue_size = queue.size
begin
queue_size.times do
result << queue.deq(:raise_if_empty)
end
rescue ThreadError
# Need do nothing, queue was concurrently popped, no biggie
end
return result
end | ruby | {
"resource": ""
} |
q27364 | SentenceBuilder.Builder.get_hash | test | def get_hash(params = {}, sorted = true)
get_nodes(sorted).map{|n| n.to_hash(params[n.name])}
end | ruby | {
"resource": ""
} |
q27365 | SentenceBuilder.Builder.get_sentence | test | def get_sentence(params = {}, sorted = true, separator = ' ')
build_sentence_from_hash(get_hash(params, sorted)).select(&:present?).join(separator)
end | ruby | {
"resource": ""
} |
q27366 | SentenceBuilder.Builder.get_nodes | test | def get_nodes(sorted = true)
SentenceBuilder::Helper.to_boolean(sorted) ? @nodes.sort_by{|i| i.sort_by_value} : @nodes
end | ruby | {
"resource": ""
} |
q27367 | SentenceBuilder.Builder.build_sentence_from_hash | test | def build_sentence_from_hash(nodes)
result = []
nodes.each do |node|
# This node does not appear in params
if node[:current_value].nil?
if node[:always_use]
result << node[:sentence]
end
else
result << node[:sentence]
end
end
... | ruby | {
"resource": ""
} |
q27368 | Caramelize.WikkaWiki.read_pages | test | def read_pages
sql = "SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;"
results = database.query(sql)
results.each do |row|
titles << row["tag"]
author = authors[row["user"]]
page = Page.new({:id => row["id"],
:title => ... | ruby | {
"resource": ""
} |
q27369 | Filterable.ClassMethods.filter | test | def filter(params)
results = where(nil)
params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end | ruby | {
"resource": ""
} |
q27370 | Trimark.Client.sites | test | def sites
response = conn.get("#{base_url}/site", {}, query_headers)
body = JSON.parse(response.body)
body.map { |b| Site.new(b) }
rescue JSON::ParserError
fail QueryError, "Query Failed! HTTPStatus: #{response.status} - Response: #{body}"
end | ruby | {
"resource": ""
} |
q27371 | Trimark.Client.site_query | test | def site_query(*args)
response = conn.get(url_picker(*args), {}, query_headers)
if response.body['SiteId'] || response.body['PointId']
JSON.parse(response.body)
else
fail QueryError, "Query Failed! HTTPStatus: #{response.status}"
end
end | ruby | {
"resource": ""
} |
q27372 | CurrencySpy.Walutomat.rate_time | test | def rate_time
regexp = Regexp.new(currency_code)
page.search("//span[@name='pair']").each do |td|
if regexp.match(td.content)
hour = td.next_element.next_element.content
return DateTime.parse(hour)
end
end
end | ruby | {
"resource": ""
} |
q27373 | Logue.Logger.outfile= | test | def outfile= f
io = f.kind_of?(IO) ? f : File.new(f, "w")
@writer.output = io
end | ruby | {
"resource": ""
} |
q27374 | Logue.Logger.log | test | def log msg = "", obj = nil, level: Level::DEBUG, classname: nil, &blk
log_frames msg, obj, classname: classname, level: level, nframes: 0, &blk
end | ruby | {
"resource": ""
} |
q27375 | Watir.OptionGroup.options | test | def options
option_hash = {}
my_labels = option_names
my_inputs = option_fields
my_labels.count.times do |index|
option_hash[my_labels[index]] = my_inputs[index]
end
option_hash
end | ruby | {
"resource": ""
} |
q27376 | Watir.OptionGroup.selected_options | test | def selected_options
selected = []
my_labels = option_names
inputs.each_with_index do |field, index|
selected << my_labels[index] if field.checked?
end
selected
end | ruby | {
"resource": ""
} |
q27377 | ActionCableNotifications.Channel.transmit_packet | test | def transmit_packet(packet, options={})
# Default options
options = {
cache: false
}.merge(options)
packet = packet.as_json.deep_symbolize_keys
if validate_packet(packet, options)
if options[:cache]==true
if update_cache(packet)
transmit packet
... | ruby | {
"resource": ""
} |
q27378 | RBeautify.BlockStart.strict_ancestor_of? | test | def strict_ancestor_of?(block_start)
block_start && block_start.parent && (self == block_start.parent || strict_ancestor_of?(block_start.parent))
end | ruby | {
"resource": ""
} |
q27379 | BuiltInData.ClassMethods.built_in_object_ids | test | def built_in_object_ids
@built_in_object_ids ||= Hash.new do |hash, key|
hash[key] = where(built_in_key: key).pluck(:id).first
end
end | ruby | {
"resource": ""
} |
q27380 | Clacks.Command.daemonize | test | def daemonize(safe = true)
$stdin.reopen '/dev/null'
# Fork and have the parent exit.
# This makes the shell or boot script think the command is done.
# Also, the child process is guaranteed not to be a process group
# leader (a prerequisite for setsid next)
exit if fork
# Ca... | ruby | {
"resource": ""
} |
q27381 | Clacks.Command.reopen_io | test | def reopen_io(io, path)
io.reopen(::File.open(path, "ab")) if path
io.sync = true
end | ruby | {
"resource": ""
} |
q27382 | Clacks.Command.running? | test | def running?(path)
wpid = ::File.read(path).to_i
return if wpid <= 0
Process.kill(0, wpid)
wpid
rescue Errno::EPERM, Errno::ESRCH, Errno::ENOENT
# noop
end | ruby | {
"resource": ""
} |
q27383 | Clacks.Command.write_pid | test | def write_pid(pid)
::File.open(pid, 'w') { |f| f.write("#{Process.pid}") }
at_exit { ::File.delete(pid) if ::File.exist?(pid) rescue nil }
end | ruby | {
"resource": ""
} |
q27384 | Mead.Identifier.parse_mead | test | def parse_mead(*args)
parts = @mead.split('-')
args.each_with_index do |field, i|
instance_variable_set('@' + field, parts[i])
end
end | ruby | {
"resource": ""
} |
q27385 | Mixml.Tool.load | test | def load(*file_names)
file_names.flatten.each do |file_name|
xml = File.open(file_name, 'r') do |file|
Nokogiri::XML(file) do |config|
if @pretty then
config.default_xml.noblanks
end
... | ruby | {
"resource": ""
} |
q27386 | Mixml.Tool.save_all | test | def save_all
output_all do |document, options|
File.open(document.name, 'w') do |file|
document.xml.write_xml_to(file, options)
end
end
end | ruby | {
"resource": ""
} |
q27387 | Mixml.Tool.print_all | test | def print_all
output_all do |document, options|
if @documents.size > 1 then
puts '-' * document.name.length
puts document.name
puts '-' * document.name.length
end
puts document.xml.to_xml(options)
... | ruby | {
"resource": ""
} |
q27388 | Mixml.Tool.work | test | def work(*file_names, &block)
remove_all
file_names.each do |file_name|
load(file_name)
if not block.nil? then
execute(&block)
end
flush
remove_all
end
end | ruby | {
"resource": ""
} |
q27389 | Mixml.Tool.xpath | test | def xpath(*paths, &block)
nodesets = []
process do |xml|
nodesets << xml.xpath(*paths)
end
selection = Selection.new(nodesets)
if block_given? then
Docile.dsl_eval(selection, &block)
end
selection
... | ruby | {
"resource": ""
} |
q27390 | Mixml.Tool.css | test | def css(*selectors, &block)
nodesets = []
process do |xml|
nodesets << xml.css(*selectors)
end
selection = Selection.new(nodesets)
if block_given? then
Docile.dsl_eval(selection, &block)
end
selection
... | ruby | {
"resource": ""
} |
q27391 | Mixml.Tool.execute | test | def execute(program = nil, &block)
if not program.nil? then
instance_eval(program)
end
if not block.nil? then
Docile.dsl_eval(self, &block)
end
end | ruby | {
"resource": ""
} |
q27392 | Mixml.Tool.with_nodes | test | def with_nodes(selection)
selection.nodesets.each do |nodeset|
nodeset.each do |node|
yield node
end
end
end | ruby | {
"resource": ""
} |
q27393 | TagFormatter.Formatter.tagify | test | def tagify input
output = input.dup
raise StandardError, "@tags is empty!" if @tags.empty? #improve on this
@tags.each {|key,value| output.gsub!(tag_start.to_s+key.to_s+tag_end.to_s, value.to_s)}
return output
end | ruby | {
"resource": ""
} |
q27394 | Watir.Container.option_group | test | def option_group(*args)
selector = if args.first.respond_to?(:elements)
args.first
else
extract_selector(args)
end
OptionGroup.new(self, selector)
end | ruby | {
"resource": ""
} |
q27395 | Caramelize::CLI.CreateCommand.execute | test | def execute(args)
# create dummy config file
target_file = @config_file.nil? ? "caramel.rb" : @config_file
FileUtils.cp(File.dirname(__FILE__) +"/../caramel.rb", target_file)
if commandparser.verbosity == :normal
puts "Created new configuration file: #{target_file}"
end
end | ruby | {
"resource": ""
} |
q27396 | OscMacheteRails.Workflow.has_machete_workflow_of | test | def has_machete_workflow_of(jobs_active_record_relation_symbol)
# yes, this is magic mimicked from http://guides.rubyonrails.org/plugins.html
# and http://yehudakatz.com/2009/11/12/better-ruby-idioms/
cattr_accessor :jobs_active_record_relation_symbol
self.jobs_active_record_relation_symbol = j... | ruby | {
"resource": ""
} |
q27397 | Qwirk.Task.check_retry | test | def check_retry
if @finished_publishing && @pending_hash.empty? && @exception_count > 0 && (@retry || @auto_retry)
# If we're just doing auto_retry but nothing succeeded last time, then don't run again
return if !@retry && @auto_retry && @exception_count == @exceptions_per_run.last
Qwirk.l... | ruby | {
"resource": ""
} |
q27398 | Mixml.Application.run | test | def run
program :name, 'mixml'
program :version, Mixml::VERSION
program :description, 'XML helper tool'
$tool = Mixml::Tool.new
global_option('-p', '--pretty', 'Pretty print output') do |value|
$tool.pretty = value
end
... | ruby | {
"resource": ""
} |
q27399 | Koi.Command.list | test | def list entities = @db.list
out
entities = entities.is_a?(Fixnum) ? @db.list[0...entities] : entities
entities.reject {|e| e[:status] == :removed }.each_with_index do |e, i|
out " [#{i}]".blue +
"#{e.sticky?? " + ".bold : " "}" +
e[:title].under... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.