_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q26200
|
NewRelicManagement.Client.get_server_name
|
validation
|
def get_server_name(server, exact = true)
ret = nr_api.get(url('servers'), 'filter[name]' => server).body
return ret['servers'] unless exact
ret['servers'].find {
|
ruby
|
{
"resource": ""
}
|
q26201
|
NewRelicManagement.Client.get_servers_labeled
|
validation
|
def get_servers_labeled(labels)
label_query = Array(labels).reject { |x| !x.include?(':') }.join(';')
|
ruby
|
{
"resource": ""
}
|
q26202
|
Isimud.EventObserver.observe_events
|
validation
|
def observe_events(client)
return unless enable_listener?
queue = create_queue(client)
client.subscribe(queue) do |message|
event
|
ruby
|
{
"resource": ""
}
|
q26203
|
Isimud.BunnyClient.bind
|
validation
|
def bind(queue_name, exchange_name, *routing_keys, &block)
queue = create_queue(queue_name, exchange_name,
queue_options: {durable: true},
|
ruby
|
{
"resource": ""
}
|
q26204
|
Isimud.BunnyClient.create_queue
|
validation
|
def create_queue(queue_name, exchange_name, options = {})
queue_options = options[:queue_options] || {durable: true}
routing_keys = options[:routing_keys] || []
log "Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}"
|
ruby
|
{
"resource": ""
}
|
q26205
|
Isimud.BunnyClient.subscribe
|
validation
|
def subscribe(queue, options = {}, &block)
queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload|
current_channel = delivery_info.channel
begin
log "Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}", :debug
Thread.current['isimud_queue_name'] = queue.name
Thread.current['isimud_delivery_info'] = delivery_info
Thread.current['isimud_properties'] = properties
block.call(payload)
if current_channel.open?
log "Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging", :debug
current_channel.ack(delivery_info.delivery_tag)
else
log "Isimud: queue #{queue.name}
|
ruby
|
{
"resource": ""
}
|
q26206
|
Isimud.BunnyClient.channel
|
validation
|
def channel
if (channel = Thread.current[CHANNEL_KEY]).try(:open?)
channel
else
new_channel = connection.channel
|
ruby
|
{
"resource": ""
}
|
q26207
|
Isimud.BunnyClient.publish
|
validation
|
def publish(exchange, routing_key, payload, options = {})
log "Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}", :debug
channel.topic(exchange,
|
ruby
|
{
"resource": ""
}
|
q26208
|
MrPoole.Commands.post
|
validation
|
def post(opts)
opts = @helper.ensure_open_struct(opts)
date = @helper.get_date_stamp
# still want to escape any garbage in the slug
slug = if opts.slug.nil? || opts.slug.empty?
opts.title
else
opts.slug
end
slug = @helper.get_slug_for(slug)
# put the metadata into the layout header
head, ext = @helper.get_layout(opts.layout)
head.sub!(/^title:\s*$/, "title: #{opts.title}")
|
ruby
|
{
"resource": ""
}
|
q26209
|
MrPoole.Commands.draft
|
validation
|
def draft(opts)
opts = @helper.ensure_open_struct(opts)
# the drafts folder might not exist yet...create it just in case
FileUtils.mkdir_p(DRAFTS_FOLDER)
slug = if opts.slug.nil? || opts.slug.empty?
opts.title
else
opts.slug
end
slug = @helper.get_slug_for(slug)
# put the metadata into the layout header
head, ext = @helper.get_layout(opts.layout)
head.sub!(/^title:\s*$/, "title: #{opts.title}")
|
ruby
|
{
"resource": ""
}
|
q26210
|
MrPoole.Commands.publish
|
validation
|
def publish(draftpath, opts={})
opts = @helper.ensure_open_struct(opts)
tail = File.basename(draftpath)
begin
infile = File.open(draftpath, "r")
rescue Errno::ENOENT
@helper.bad_path(draftpath)
end
date = @helper.get_date_stamp
time = @helper.get_time_stamp
outpath = File.join(POSTS_FOLDER, "#{date}-#{tail}")
outfile = File.open(outpath, "w")
|
ruby
|
{
"resource": ""
}
|
q26211
|
Luck.ANSIDriver.terminal_size
|
validation
|
def terminal_size
rows, cols = 25, 80
buf = [0, 0, 0, 0].pack("SSSS")
if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then
|
ruby
|
{
"resource": ""
}
|
q26212
|
Luck.ANSIDriver.prepare_modes
|
validation
|
def prepare_modes
buf = [0, 0, 0, 0, 0, 0, ''].pack("IIIICCA*")
$stdout.ioctl(TCGETS, buf)
@old_modes = buf.unpack("IIIICCA*")
new_modes = @old_modes.clone
new_modes[3] &= ~ECHO # echo off
new_modes[3] &= ~ICANON # one char @ a time
$stdout.ioctl(TCSETS, new_modes.pack("IIIICCA*"))
print "\e[2J" # clear screen
print "\e[H" # go home
|
ruby
|
{
"resource": ""
}
|
q26213
|
CanCanCan.Masquerade.extract_subjects
|
validation
|
def extract_subjects(subject)
return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance
|
ruby
|
{
"resource": ""
}
|
q26214
|
NewRelicManagement.Controller.daemon
|
validation
|
def daemon # rubocop: disable AbcSize, MethodLength
# => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)
ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ']
scheduler = Rufus::Scheduler.new
Notifier.msg('Daemonizing Process')
# => Alerts Management
alerts_interval = Config.alert_management_interval
|
ruby
|
{
"resource": ""
}
|
q26215
|
NewRelicManagement.Controller.run
|
validation
|
def run
daemon if Config.daemonize
# => Manage Alerts
Manager.manage_alerts
|
ruby
|
{
"resource": ""
}
|
q26216
|
MrPoole.Helper.ensure_jekyll_dir
|
validation
|
def ensure_jekyll_dir
@orig_dir = Dir.pwd
start_path = Pathname.new(@orig_dir)
ok = File.exists?('./_posts')
new_path = nil
# if it doesn't exist, check for a custom source dir in _config.yml
if !ok
check_custom_src_dir!
ok = File.exists?('./_posts')
new_path = Pathname.new(Dir.pwd)
end
|
ruby
|
{
"resource": ""
}
|
q26217
|
MrPoole.Helper.get_layout
|
validation
|
def get_layout(layout_path)
if layout_path.nil?
contents = "---\n"
contents << "title:\n"
contents << "layout: post\n"
contents << "date:\n"
contents << "---\n"
ext = nil
else
begin
|
ruby
|
{
"resource": ""
}
|
q26218
|
MrPoole.Helper.gen_usage
|
validation
|
def gen_usage
puts 'Usage:'
puts ' poole [ACTION] [ARG]'
puts ''
puts 'Actions:'
puts ' draft Create a new draft in _drafts with title SLUG'
puts ' post Create a new timestamped post in _posts with title SLUG'
puts ' publish
|
ruby
|
{
"resource": ""
}
|
q26219
|
NewRelicManagement.Notifier.msg
|
validation
|
def msg(message, subtitle = message, title = 'NewRelic Management')
# => Stdout Messages
terminal_notification(message, subtitle)
return if Config.silent
|
ruby
|
{
"resource": ""
}
|
q26220
|
NewRelicManagement.Notifier.osx_notification
|
validation
|
def osx_notification(message, subtitle, title)
|
ruby
|
{
"resource": ""
}
|
q26221
|
SFST.RegularTransducer.analyze
|
validation
|
def analyze(string, options = {})
x = []
@fst._analyze(string) do |a|
if options[:symbol_sequence]
x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym
|
ruby
|
{
"resource": ""
}
|
q26222
|
SFST.RegularTransducer.generate
|
validation
|
def generate(string)
x = []
|
ruby
|
{
"resource": ""
}
|
q26223
|
NewRelicManagement.CLI.configure
|
validation
|
def configure(argv = ARGV)
# => Parse CLI Configuration
cli = Options.new
cli.parse_options(argv)
# => Parse JSON Config File (If Specified and Exists)
json_config = Util.parse_json(cli.config[:config_file] || Config.config_file)
# => Merge Configuration (CLI Wins)
|
ruby
|
{
"resource": ""
}
|
q26224
|
Spectro.Compiler.missing_specs_from_file
|
validation
|
def missing_specs_from_file(path)
Spectro::Spec::Parser.parse(path).select do |spec|
index_spec = Spectro::Database.index[path] &&
|
ruby
|
{
"resource": ""
}
|
q26225
|
NewRelicManagement.Manager.remove_nonreporting_servers
|
validation
|
def remove_nonreporting_servers(keeptime = nil)
list_nonreporting_servers.each do |server|
next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)
|
ruby
|
{
"resource": ""
}
|
q26226
|
NewRelicManagement.Manager.find_excluded
|
validation
|
def find_excluded(excluded)
result = []
Array(excluded).each do |exclude|
if exclude.include?(':')
find_labeled(exclude).each { |x| result << x }
next
end
|
ruby
|
{
"resource": ""
}
|
q26227
|
TwilioContactable.Contactable.send_sms_confirmation!
|
validation
|
def send_sms_confirmation!
return false if _TC_sms_blocked
return true if sms_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :sms)
# Use this class' confirmation_message method if it
# exists, otherwise use the generic message
message = (self.class.respond_to?(:confirmation_message) ?
|
ruby
|
{
"resource": ""
}
|
q26228
|
TwilioContactable.Contactable.send_voice_confirmation!
|
validation
|
def send_voice_confirmation!
return false if _TC_voice_blocked
return true if voice_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :voice)
|
ruby
|
{
"resource": ""
}
|
q26229
|
TerminalHelpers.Validations.validate
|
validation
|
def validate(value, format, raise_error=false)
unless FORMATS.key?(format)
raise FormatError, "Invalid data format: #{format}"
|
ruby
|
{
"resource": ""
}
|
q26230
|
XFTP.Client.call
|
validation
|
def call(url, settings, &block)
uri = URI.parse(url)
klass = adapter_class(uri.scheme)
|
ruby
|
{
"resource": ""
}
|
q26231
|
MiamiDadeGeo.GeoAttributeClient.all_fields
|
validation
|
def all_fields(table, field_name, value)
body = savon.
call(:get_all_fields_records_given_a_field_name_and_value,
message: {
'strFeatureClassOrTableName' => table,
'strFieldNameToSearchOn' => field_name,
'strValueOfFieldToSearchOn' => value
}).
body
|
ruby
|
{
"resource": ""
}
|
q26232
|
Validation.Adjustment.WHEN
|
validation
|
def WHEN(condition, adjuster)
unless Validation.conditionable? condition
raise TypeError, 'wrong object for condition'
end
unless Validation.adjustable? adjuster
|
ruby
|
{
"resource": ""
}
|
q26233
|
Validation.Adjustment.INJECT
|
validation
|
def INJECT(adjuster1, adjuster2, *adjusters)
adjusters = [adjuster1, adjuster2, *adjusters]
unless adjusters.all?{|f|adjustable? f}
raise TypeError, 'wrong object for adjuster'
|
ruby
|
{
"resource": ""
}
|
q26234
|
Validation.Adjustment.PARSE
|
validation
|
def PARSE(parser)
if !::Integer.equal?(parser) and !parser.respond_to?(:parse)
raise TypeError, 'wrong object for parser'
end
->v{
if ::Integer.equal? parser
::Kernel.Integer v
else
parser.parse(
case v
when String
v
when ->_{v.respond_to? :to_str}
|
ruby
|
{
"resource": ""
}
|
q26235
|
RFormSpec.Window.get_class
|
validation
|
def get_class(name)
@class_list = get_class_list
|
ruby
|
{
"resource": ""
}
|
q26236
|
Megam.Scmmanager.connection
|
validation
|
def connection
@options[:path] =API_REST + @options[:path]
@options[:headers] = HEADERS.merge({
'X-Megam-Date' => Time.now.strftime("%Y-%m-%d %H:%M")
}).merge(@options[:headers])
|
ruby
|
{
"resource": ""
}
|
q26237
|
QuackConcurrency.SafeSleeper.wake_deadline
|
validation
|
def wake_deadline(start_time, timeout)
timeout =
|
ruby
|
{
"resource": ""
}
|
q26238
|
MirExtensions.HelperExtensions.crud_links
|
validation
|
def crud_links(model, instance_name, actions, args={})
_html = ""
_options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"
if use_crud_icons
if actions.include?(:show)
_html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}")
end
if actions.include?(:edit)
_html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}")
end
if actions.include?(:delete)
_html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}")
end
else
if actions.include?(:show)
_html
|
ruby
|
{
"resource": ""
}
|
q26239
|
MirExtensions.HelperExtensions.obfuscated_link_to
|
validation
|
def obfuscated_link_to(path, image, label, args={})
_html = %{<form action="#{path}" method="get" class="obfuscated_link">}
_html << %{ <fieldset><input alt="#{label}"
|
ruby
|
{
"resource": ""
}
|
q26240
|
MirExtensions.HelperExtensions.required_field_helper
|
validation
|
def required_field_helper( model, element, html )
if model && ! model.errors.empty? && element.is_required
|
ruby
|
{
"resource": ""
}
|
q26241
|
MirExtensions.HelperExtensions.select_tag_for_filter
|
validation
|
def select_tag_for_filter(model, nvpairs, params)
return unless model && nvpairs && ! nvpairs.empty?
options = { :query => params[:query] }
_url = url_for(eval("#{model}_url(options)"))
_html = %{<label for="show">Show:</label><br />}
_html << %{<select name="show" id="show" onchange="window.location='#{_url}' + '?show=' + this.value">}
nvpairs.each do |pair|
_html << %{<option value="#{pair[:scope]}"}
if
|
ruby
|
{
"resource": ""
}
|
q26242
|
MirExtensions.HelperExtensions.sort_link
|
validation
|
def sort_link(model, field, params, html_options={})
if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC"
classname = "arrow-asc"
dir = "DESC"
elsif (field.to_sym == params[:by] || field == params[:by])
classname = "arrow-desc"
dir = "ASC"
else
dir = "ASC"
end
options = {
:anchor => html_options[:anchor] || nil,
:by => field,
:dir => dir,
:query => params[:query],
:show => params[:show]
}
options[:show] = params[:show] unless params[:show].blank? || params[:show] == 'all'
html_options = {
:class => "#{classname} #{html_options[:class]}",
|
ruby
|
{
"resource": ""
}
|
q26243
|
MirExtensions.HelperExtensions.tag_for_label_with_inline_help
|
validation
|
def tag_for_label_with_inline_help( label_text, field_id, help_text )
_html = ""
_html << %{<label for="#{field_id}">#{label_text}}
_html << %{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />}
_html << %{</label><br />}
|
ruby
|
{
"resource": ""
}
|
q26244
|
RFormSpec.Driver.key_press
|
validation
|
def key_press(keys)
dump_caller_stack
if keys =~ /^Ctrl\+([A-Z])$/
filtered_keys = "^+#{$1}"
elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/
filtered_keys = "^+#{$1.downcase}"
elsif keys =~ /^Alt+([A-Z])$/
filtered_keys = "!+#{$1}"
elsif keys =~ /^Alt\+Shift\+([a-z])$/
filtered_keys = "!+#{$1.downcase}"
|
ruby
|
{
"resource": ""
}
|
q26245
|
RFormSpec.Driver.open_file_dialog
|
validation
|
def open_file_dialog(title, filepath, text="")
wait_and_focus_window(title)
dialog = RFormSpec::OpenFileDialog.new(title, text)
|
ruby
|
{
"resource": ""
}
|
q26246
|
ByebugCleaner.ArgumentParser.parse
|
validation
|
def parse(args)
# The options specified on the command line will be collected in
# *options*.
@options = Options.new
opt_parser = OptionParser.new do |parser|
|
ruby
|
{
"resource": ""
}
|
q26247
|
Rgc.GitAttributes.add
|
validation
|
def add(path)
str = "#{path} filter=rgc diff=rgc"
if content.include?(str)
abort "`#{str}\n` is already included in #{@location}."
end
File.open(@location, 'a') do |f|
f.write("#{str}\n")
end
rescue Errno::ENOENT
|
ruby
|
{
"resource": ""
}
|
q26248
|
ActiveMigration.Base.run
|
validation
|
def run
logger.info("#{self.class.to_s} is starting.")
count_options = self.class.legacy_find_options.dup
count_options.delete(:order)
count_options.delete(:group)
count_options.delete(:limit)
count_options.delete(:offset)
@num_of_records = self.class.legacy_model.count(count_options)
if self.class.legacy_find_options[:limit] &&
|
ruby
|
{
"resource": ""
}
|
q26249
|
Simplec.Page.parents
|
validation
|
def parents
page, parents = self, Array.new
while page.parent
page = page.parent
|
ruby
|
{
"resource": ""
}
|
q26250
|
Simplec.Page.extract_search_text
|
validation
|
def extract_search_text(*attributes)
Array(attributes).map { |meth|
Nokogiri::HTML(self.send(meth)).xpath("//text()").
|
ruby
|
{
"resource": ""
}
|
q26251
|
Simplec.Page.set_query_attributes!
|
validation
|
def set_query_attributes!
attr_names = self.class.search_query_attributes.map(&:to_s)
self.query = attr_names.inject({})
|
ruby
|
{
"resource": ""
}
|
q26252
|
Bixby.Agent.manager_ws_uri
|
validation
|
def manager_ws_uri
# convert manager uri to websocket
uri = URI.parse(manager_uri)
uri.scheme = (uri.scheme == "https"
|
ruby
|
{
"resource": ""
}
|
q26253
|
ForemanHook.HostRename.parse_config
|
validation
|
def parse_config(conffile = nil)
conffile ||= Dir.glob([
"/etc/foreman_hooks-host_rename/settings.yaml",
"#{confdir}/settings.yaml"])[0]
raise "Could not locate the configuration file" if conffile.nil?
# Parse the configuration file
config = {
hook_user: 'foreman',
database_path: '/var/tmp/foreman_hooks-host_rename.db',
log_path: '/var/tmp/foreman_hooks-host_rename.log',
log_level: 'warn',
rename_hook_command: '/bin/true',
}.merge(symbolize(YAML.load(File.read(conffile))))
config.each do |k,v|
instance_variable_set("@#{k}",v)
end
# Validate the schema
document = Kwalify::Yaml.load_file(conffile)
schema = Kwalify::Yaml.load_file("#{confdir}/schema.yaml")
|
ruby
|
{
"resource": ""
}
|
q26254
|
ForemanHook.HostRename.check_script
|
validation
|
def check_script(path)
binary=path.split(' ')[0]
raise "#{path} does not exist" unless File.exist? binary
|
ruby
|
{
"resource": ""
}
|
q26255
|
ForemanHook.HostRename.sync_host_table
|
validation
|
def sync_host_table
uri = foreman_uri('/hosts?per_page=9999999')
debug "Loading hosts from #{uri}"
json = RestClient.get uri
debug "Got JSON: #{json}"
JSON.parse(json)['results'].each do
|
ruby
|
{
"resource": ""
}
|
q26256
|
ForemanHook.HostRename.initialize_database
|
validation
|
def initialize_database
@db = SQLite3::Database.new @database_path
File.chmod 0600, @database_path
begin
@db.execute 'drop table if exists host;'
|
ruby
|
{
"resource": ""
}
|
q26257
|
ForemanHook.HostRename.execute_hook_action
|
validation
|
def execute_hook_action
@rename = false
name = @rec['host']['name']
id = @rec['host']['id']
case @action
when 'create'
sql = "insert into host (id, name) values (?, ?)"
params = [id, name]
when 'update'
# Check if we are renaming the host
@old_name = @db.get_first_row('select name from host where id = ?', id)
@old_name = @old_name[0] unless @old_name.nil?
if @old_name.nil?
warn 'received an update for a non-existent host'
else
@rename = @old_name != name
end
debug "checking for a
|
ruby
|
{
"resource": ""
}
|
q26258
|
RedisAssist.Base.read_list
|
validation
|
def read_list(name)
opts = self.class.persisted_attrs[name]
if !lists[name] && opts[:default]
opts[:default]
else
|
ruby
|
{
"resource": ""
}
|
q26259
|
RedisAssist.Base.read_hash
|
validation
|
def read_hash(name)
opts = self.class.persisted_attrs[name]
if !hashes[name] && opts[:default]
opts[:default]
else
|
ruby
|
{
"resource": ""
}
|
q26260
|
RedisAssist.Base.write_attribute
|
validation
|
def write_attribute(name, val)
if attributes.is_a?(Redis::Future)
value = attributes.value
self.attributes = value ? Hash[*self.class.fields.keys.zip(value).flatten]
|
ruby
|
{
"resource": ""
}
|
q26261
|
RedisAssist.Base.write_list
|
validation
|
def write_list(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as
|
ruby
|
{
"resource": ""
}
|
q26262
|
RedisAssist.Base.write_hash
|
validation
|
def write_hash(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as
|
ruby
|
{
"resource": ""
}
|
q26263
|
RedisAssist.Base.update_columns
|
validation
|
def update_columns(attrs)
redis.multi do
attrs.each do |attr, value|
if self.class.fields.has_key?(attr)
write_attribute(attr, value)
redis.hset(key_for(:attributes), attr, self.class.transform(:to, attr, value)) unless new_record?
end
if self.class.lists.has_key?(attr)
write_list(attr, value)
unless new_record?
redis.del(key_for(attr))
redis.rpush(key_for(attr), value) unless value.empty?
|
ruby
|
{
"resource": ""
}
|
q26264
|
Minican.ControllerAdditions.filter_authorized!
|
validation
|
def filter_authorized!(method, objects, user = current_user)
object_array = Array(objects)
object_array.select do |object|
|
ruby
|
{
"resource": ""
}
|
q26265
|
Minican.ControllerAdditions.can?
|
validation
|
def can?(method, object, user = current_user)
policy = policy_for(object)
|
ruby
|
{
"resource": ""
}
|
q26266
|
DogeCoin.Client.nethash
|
validation
|
def nethash interval = 500, start = 0, stop = false
suffixe = stop ? "/#{stop}"
|
ruby
|
{
"resource": ""
}
|
q26267
|
RedisAssist.Finders.last
|
validation
|
def last(limit=1, offset=0)
from = offset
to = from + limit - 1
members = redis.zrange(index_key_for(:id), (to * -1) + -1, (from *
|
ruby
|
{
"resource": ""
}
|
q26268
|
RedisAssist.Finders.find
|
validation
|
def find(ids, opts={})
ids.is_a?(Array)
|
ruby
|
{
"resource": ""
}
|
q26269
|
RedisAssist.Finders.find_in_batches
|
validation
|
def find_in_batches(options={})
start = options[:start] || 0
marker = start
batch_size = options[:batch_size] || 500
record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
|
ruby
|
{
"resource": ""
}
|
q26270
|
ActiveMigration.KeyMapper.load_keymap
|
validation
|
def load_keymap(map) #:nodoc:
@maps ||= Hash.new
if @maps[map].nil? && File.file?(File.join(self.storage_path, map.to_s + "_map.yml"))
@maps[map]
|
ruby
|
{
"resource": ""
}
|
q26271
|
ActiveMigration.KeyMapper.mapped_key
|
validation
|
def mapped_key(map, key)
load_keymap(map.to_s)
|
ruby
|
{
"resource": ""
}
|
q26272
|
Parallel.ProcessorCount.processor_count
|
validation
|
def processor_count
@processor_count ||= begin
os_name = RbConfig::CONFIG["target_os"]
if os_name =~ /mingw|mswin/
require 'win32ole'
result = WIN32OLE.connect("winmgmts://").ExecQuery(
"select NumberOfLogicalProcessors from Win32_Processor")
result.to_enum.collect(&:NumberOfLogicalProcessors).reduce(:+)
elsif File.readable?("/proc/cpuinfo")
IO.read("/proc/cpuinfo").scan(/^processor/).size
elsif File.executable?("/usr/bin/hwprefs")
IO.popen("/usr/bin/hwprefs thread_count").read.to_i
elsif File.executable?("/usr/sbin/psrinfo")
IO.popen("/usr/sbin/psrinfo").read.scan(/^.*on-*line/).size
elsif File.executable?("/usr/sbin/ioscan")
IO.popen("/usr/sbin/ioscan -kC processor") do |out|
out.read.scan(/^.*processor/).size
end
elsif File.executable?("/usr/sbin/pmcycles")
IO.popen("/usr/sbin/pmcycles -m").read.count("\n")
|
ruby
|
{
"resource": ""
}
|
q26273
|
Parallel.ProcessorCount.physical_processor_count
|
validation
|
def physical_processor_count
@physical_processor_count ||= begin
ppc = case RbConfig::CONFIG["target_os"]
when /darwin1/
IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i
when /linux/
cores = {} # unique physical ID / core ID combinations
phy = 0
IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
if ln.start_with?("physical")
|
ruby
|
{
"resource": ""
}
|
q26274
|
RubyReportable.Report.valid?
|
validation
|
def valid?(options = {})
options = {:input => {}}.merge(options)
errors = []
# initial sandbox
sandbox = _source(options)
# add in inputs
sandbox[:inputs] = options[:input]
validity = @filters.map do |filter_name, filter|
# find input for given filter
sandbox[:input] = options[:input][filter[:key]] if options[:input].is_a?(Hash)
filter_validity = filter[:valid].nil? || sandbox.instance_eval(&filter[:valid])
if filter_validity == false
# Ignore an empty filter unless it's required
if !sandbox[:input].to_s.blank?
errors << "#{filter_name} is invalid."
false
else
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
end
elsif filter_validity == true
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
|
ruby
|
{
"resource": ""
}
|
q26275
|
ElapsedWatch.EventCollection.reload
|
validation
|
def reload()
self.clear
self.concat
|
ruby
|
{
"resource": ""
}
|
q26276
|
Mongoid.Followable.followee_of?
|
validation
|
def followee_of?(model)
0 < self.followers.by_model(model).limit(1).count
|
ruby
|
{
"resource": ""
}
|
q26277
|
Mongoid.Followable.ever_followed
|
validation
|
def ever_followed
follow = []
self.followed_history.each do |h|
|
ruby
|
{
"resource": ""
}
|
q26278
|
QuackConcurrency.ConditionVariable.wait
|
validation
|
def wait(mutex, timeout = nil)
validate_mutex(mutex)
validate_timeout(timeout)
waitable = waitable_for_current_thread
@mutex.synchronize do
@waitables.push(waitable)
|
ruby
|
{
"resource": ""
}
|
q26279
|
QuackConcurrency.ConditionVariable.validate_timeout
|
validation
|
def validate_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil
|
ruby
|
{
"resource": ""
}
|
q26280
|
Deas::Erubis.TemplateEngine.render
|
validation
|
def render(template_name, view_handler, locals, &content)
self.erb_source.render(template_name,
|
ruby
|
{
"resource": ""
}
|
q26281
|
SpreadsheetAgent.Agent.run_entry
|
validation
|
def run_entry
entry = get_entry()
output = '';
@keys.keys.select { |k| @config['key_fields'][k] && @keys[k] }.each do |key|
output += [ key, @keys[key] ].join(' ') + " "
end
unless entry
$stderr.puts "#{ output } is not supported on #{ @page_name }" if @debug
return
end
unless entry['ready'] == "1"
$stderr.puts "#{ output } is not ready to run #{ @agent_name }" if @debug
return false, entry
end
if entry['complete'] == "1"
$stderr.puts "All goals are completed for #{ output }" if @debug
return false, entry
end
if entry[@agent_name]
(status, running_hostname) = entry[@agent_name].split(':')
case status
when 'r'
$stderr.puts " #{ output } is already running #{ @agent_name } on #{ running_hostname }" if @debug
return false, entry
when "1"
$stderr.puts " #{ output } has already run #{ @agent_name }" if @debug
return false,
|
ruby
|
{
"resource": ""
}
|
q26282
|
KevinsPropietaryBrain.Brain.pick
|
validation
|
def pick(number, *cards)
ordered = cards.flatten.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
|
ruby
|
{
"resource": ""
}
|
q26283
|
KevinsPropietaryBrain.Brain.discard
|
validation
|
def discard
ordered = player.hand.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
|
ruby
|
{
"resource": ""
}
|
q26284
|
KevinsPropietaryBrain.Brain.play
|
validation
|
def play
bangs_played = 0
while !player.hand.find_all(&:draws_cards?).empty?
player.hand.find_all(&:draws_cards?).each {|card| player.play_card(card)}
end
play_guns
player.hand.each do |card|
target = find_target(card)
|
ruby
|
{
"resource": ""
}
|
q26285
|
QuackConcurrency.Mutex.sleep
|
validation
|
def sleep(timeout = nil)
validate_timeout(timeout)
unlock do
if timeout == nil || timeout == Float::INFINITY
elapsed_time = (timer { Thread.stop }).round
|
ruby
|
{
"resource": ""
}
|
q26286
|
QuackConcurrency.Mutex.temporarily_release
|
validation
|
def temporarily_release(&block)
raise ArgumentError, 'no block given' unless block_given?
unlock
|
ruby
|
{
"resource": ""
}
|
q26287
|
QuackConcurrency.Mutex.timer
|
validation
|
def timer(&block)
start_time = Time.now
yield(start_time)
|
ruby
|
{
"resource": ""
}
|
q26288
|
CapybaraRails.Selenium.wait
|
validation
|
def wait
continue = false
trap "SIGINT" do
puts "Continuing..."
continue = true
end
puts "Waiting. Press
|
ruby
|
{
"resource": ""
}
|
q26289
|
Quickl.RubyTools.optional_args_block_call
|
validation
|
def optional_args_block_call(block, args)
if RUBY_VERSION >= "1.9.0"
if block.arity == 0
|
ruby
|
{
"resource": ""
}
|
q26290
|
Quickl.RubyTools.extract_file_rdoc
|
validation
|
def extract_file_rdoc(file, from = nil, reverse = false)
lines = File.readlines(file)
if from.nil? and reverse
lines = lines.reverse
elsif !reverse
lines = lines[(from || 0)..-1]
else
lines = lines[0...(from || -1)].reverse
end
doc, started = [], false
lines.each{|line|
if /^\s*[#]/ =~ line
doc << line
started = true
|
ruby
|
{
"resource": ""
}
|
q26291
|
ToughGuy.Query.select
|
validation
|
def select(fields)
if (fields == []) || (fields.nil?)
fields = [:_id]
end
|
ruby
|
{
"resource": ""
}
|
q26292
|
ToughGuy.Query.set_pagination_info
|
validation
|
def set_pagination_info(page_no, page_size, record_count)
@current_page = page_no
@per_page = page_size
@total_count = record_count
@total_pages =
|
ruby
|
{
"resource": ""
}
|
q26293
|
EchoUploads.Model.echo_uploads_data=
|
validation
|
def echo_uploads_data=(data)
parsed = JSON.parse Base64.decode64(data)
# parsed will look like:
# { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] }
unless parsed.is_a? Hash
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
parsed.each do |attr, attr_data|
# If the :map option was passed, there may be multiple variants of the uploaded
# file. Even if not, attr_data is still a one-element array.
unless attr_data.is_a? Array
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
attr_data.each do |variant_data|
unless variant_data.is_a? Hash
|
ruby
|
{
"resource": ""
}
|
q26294
|
Mongoid.Follower.follower_of?
|
validation
|
def follower_of?(model)
0 < self.followees.by_model(model).limit(1).count
|
ruby
|
{
"resource": ""
}
|
q26295
|
Mongoid.Follower.follow
|
validation
|
def follow(*models)
models.each do |model|
unless model == self or self.follower_of?(model) or model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.create!(:f_type => self.class.name, :f_id => self.id.to_s)
model.followed_history << self.class.name + '_' + self.id.to_s
model.save
|
ruby
|
{
"resource": ""
}
|
q26296
|
Mongoid.Follower.unfollow
|
validation
|
def unfollow(*models)
models.each do |model|
unless model == self or !self.follower_of?(model) or !model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
|
ruby
|
{
"resource": ""
}
|
q26297
|
Mongoid.Follower.ever_follow
|
validation
|
def ever_follow
follow = []
self.follow_history.each do |h|
follow
|
ruby
|
{
"resource": ""
}
|
q26298
|
QuackConcurrency.Queue.pop
|
validation
|
def pop(non_block = false)
@pop_mutex.lock do
@mutex.synchronize do
if empty?
return if closed?
raise ThreadError if non_block
@mutex.unlock
@waiter.wait
|
ruby
|
{
"resource": ""
}
|
q26299
|
Grenache.Base.lookup
|
validation
|
def lookup(key, opts={}, &block)
unless addr = cache.has?(key)
addr = link.send('lookup', key, opts, &block)
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.