repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.get_all_schedules
def get_all_schedules schedules = {} if SidekiqScheduler::RedisManager.schedule_exist? SidekiqScheduler::RedisManager.get_all_schedules.tap do |h| h.each do |name, config| schedules[name] = JSON.parse(config) end end end schedules end
ruby
def get_all_schedules schedules = {} if SidekiqScheduler::RedisManager.schedule_exist? SidekiqScheduler::RedisManager.get_all_schedules.tap do |h| h.each do |name, config| schedules[name] = JSON.parse(config) end end end schedules end
[ "def", "get_all_schedules", "schedules", "=", "{", "}", "if", "SidekiqScheduler", "::", "RedisManager", ".", "schedule_exist?", "SidekiqScheduler", "::", "RedisManager", ".", "get_all_schedules", ".", "tap", "do", "|", "h", "|", "h", ".", "each", "do", "|", "name", ",", "config", "|", "schedules", "[", "name", "]", "=", "JSON", ".", "parse", "(", "config", ")", "end", "end", "end", "schedules", "end" ]
gets the schedule as it exists in redis
[ "gets", "the", "schedule", "as", "it", "exists", "in", "redis" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L81-L93
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.set_schedule
def set_schedule(name, config) existing_config = get_schedule(name) unless existing_config && existing_config == config SidekiqScheduler::RedisManager.set_job_schedule(name, config) SidekiqScheduler::RedisManager.add_schedule_change(name) end config end
ruby
def set_schedule(name, config) existing_config = get_schedule(name) unless existing_config && existing_config == config SidekiqScheduler::RedisManager.set_job_schedule(name, config) SidekiqScheduler::RedisManager.add_schedule_change(name) end config end
[ "def", "set_schedule", "(", "name", ",", "config", ")", "existing_config", "=", "get_schedule", "(", "name", ")", "unless", "existing_config", "&&", "existing_config", "==", "config", "SidekiqScheduler", "::", "RedisManager", ".", "set_job_schedule", "(", "name", ",", "config", ")", "SidekiqScheduler", "::", "RedisManager", ".", "add_schedule_change", "(", "name", ")", "end", "config", "end" ]
Create or update a schedule with the provided name and configuration. Note: values for class and custom_job_class need to be strings, not constants. Sidekiq.set_schedule('some_job', { :class => 'SomeJob', :every => '15mins', :queue => 'high', :args => '/tmp/poop' })
[ "Create", "or", "update", "a", "schedule", "with", "the", "provided", "name", "and", "configuration", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L104-L111
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.remove_schedule
def remove_schedule(name) SidekiqScheduler::RedisManager.remove_job_schedule(name) SidekiqScheduler::RedisManager.add_schedule_change(name) end
ruby
def remove_schedule(name) SidekiqScheduler::RedisManager.remove_job_schedule(name) SidekiqScheduler::RedisManager.add_schedule_change(name) end
[ "def", "remove_schedule", "(", "name", ")", "SidekiqScheduler", "::", "RedisManager", ".", "remove_job_schedule", "(", "name", ")", "SidekiqScheduler", "::", "RedisManager", ".", "add_schedule_change", "(", "name", ")", "end" ]
remove a given schedule by name
[ "remove", "a", "given", "schedule", "by", "name" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L114-L117
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.load_schedule!
def load_schedule! if enabled Sidekiq.logger.info 'Loading Schedule' # Load schedule from redis for the first time if dynamic if dynamic Sidekiq.reload_schedule! @current_changed_score = Time.now.to_f rufus_scheduler.every(dynamic_every) do update_schedule end end Sidekiq.logger.info 'Schedule empty! Set Sidekiq.schedule' if Sidekiq.schedule.empty? @scheduled_jobs = {} queues = sidekiq_queues Sidekiq.schedule.each do |name, config| if !listened_queues_only || enabled_queue?(config['queue'].to_s, queues) load_schedule_job(name, config) else Sidekiq.logger.info { "Ignoring #{name}, job's queue is not enabled." } end end Sidekiq.logger.info 'Schedules Loaded' else Sidekiq.logger.info 'SidekiqScheduler is disabled' end end
ruby
def load_schedule! if enabled Sidekiq.logger.info 'Loading Schedule' # Load schedule from redis for the first time if dynamic if dynamic Sidekiq.reload_schedule! @current_changed_score = Time.now.to_f rufus_scheduler.every(dynamic_every) do update_schedule end end Sidekiq.logger.info 'Schedule empty! Set Sidekiq.schedule' if Sidekiq.schedule.empty? @scheduled_jobs = {} queues = sidekiq_queues Sidekiq.schedule.each do |name, config| if !listened_queues_only || enabled_queue?(config['queue'].to_s, queues) load_schedule_job(name, config) else Sidekiq.logger.info { "Ignoring #{name}, job's queue is not enabled." } end end Sidekiq.logger.info 'Schedules Loaded' else Sidekiq.logger.info 'SidekiqScheduler is disabled' end end
[ "def", "load_schedule!", "if", "enabled", "Sidekiq", ".", "logger", ".", "info", "'Loading Schedule'", "# Load schedule from redis for the first time if dynamic", "if", "dynamic", "Sidekiq", ".", "reload_schedule!", "@current_changed_score", "=", "Time", ".", "now", ".", "to_f", "rufus_scheduler", ".", "every", "(", "dynamic_every", ")", "do", "update_schedule", "end", "end", "Sidekiq", ".", "logger", ".", "info", "'Schedule empty! Set Sidekiq.schedule'", "if", "Sidekiq", ".", "schedule", ".", "empty?", "@scheduled_jobs", "=", "{", "}", "queues", "=", "sidekiq_queues", "Sidekiq", ".", "schedule", ".", "each", "do", "|", "name", ",", "config", "|", "if", "!", "listened_queues_only", "||", "enabled_queue?", "(", "config", "[", "'queue'", "]", ".", "to_s", ",", "queues", ")", "load_schedule_job", "(", "name", ",", "config", ")", "else", "Sidekiq", ".", "logger", ".", "info", "{", "\"Ignoring #{name}, job's queue is not enabled.\"", "}", "end", "end", "Sidekiq", ".", "logger", ".", "info", "'Schedules Loaded'", "else", "Sidekiq", ".", "logger", ".", "info", "'SidekiqScheduler is disabled'", "end", "end" ]
Pulls the schedule from Sidekiq.schedule and loads it into the rufus scheduler instance
[ "Pulls", "the", "schedule", "from", "Sidekiq", ".", "schedule", "and", "loads", "it", "into", "the", "rufus", "scheduler", "instance" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L70-L100
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.idempotent_job_enqueue
def idempotent_job_enqueue(job_name, time, config) registered = SidekiqScheduler::RedisManager.register_job_instance(job_name, time) if registered Sidekiq.logger.info "queueing #{config['class']} (#{job_name})" handle_errors { enqueue_job(config, time) } SidekiqScheduler::RedisManager.remove_elder_job_instances(job_name) else Sidekiq.logger.debug { "Ignoring #{job_name} job as it has been already enqueued" } end end
ruby
def idempotent_job_enqueue(job_name, time, config) registered = SidekiqScheduler::RedisManager.register_job_instance(job_name, time) if registered Sidekiq.logger.info "queueing #{config['class']} (#{job_name})" handle_errors { enqueue_job(config, time) } SidekiqScheduler::RedisManager.remove_elder_job_instances(job_name) else Sidekiq.logger.debug { "Ignoring #{job_name} job as it has been already enqueued" } end end
[ "def", "idempotent_job_enqueue", "(", "job_name", ",", "time", ",", "config", ")", "registered", "=", "SidekiqScheduler", "::", "RedisManager", ".", "register_job_instance", "(", "job_name", ",", "time", ")", "if", "registered", "Sidekiq", ".", "logger", ".", "info", "\"queueing #{config['class']} (#{job_name})\"", "handle_errors", "{", "enqueue_job", "(", "config", ",", "time", ")", "}", "SidekiqScheduler", "::", "RedisManager", ".", "remove_elder_job_instances", "(", "job_name", ")", "else", "Sidekiq", ".", "logger", ".", "debug", "{", "\"Ignoring #{job_name} job as it has been already enqueued\"", "}", "end", "end" ]
Pushes the job into Sidekiq if not already pushed for the given time @param [String] job_name The job's name @param [Time] time The time when the job got cleared for triggering @param [Hash] config Job's config hash
[ "Pushes", "the", "job", "into", "Sidekiq", "if", "not", "already", "pushed", "for", "the", "given", "time" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L140-L152
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.enqueue_job
def enqueue_job(job_config, time = Time.now) config = prepare_arguments(job_config.dup) if config.delete('include_metadata') config['args'] = arguments_with_metadata(config['args'], scheduled_at: time.to_f) end if active_job_enqueue?(config['class']) SidekiqScheduler::Utils.enqueue_with_active_job(config) else SidekiqScheduler::Utils.enqueue_with_sidekiq(config) end end
ruby
def enqueue_job(job_config, time = Time.now) config = prepare_arguments(job_config.dup) if config.delete('include_metadata') config['args'] = arguments_with_metadata(config['args'], scheduled_at: time.to_f) end if active_job_enqueue?(config['class']) SidekiqScheduler::Utils.enqueue_with_active_job(config) else SidekiqScheduler::Utils.enqueue_with_sidekiq(config) end end
[ "def", "enqueue_job", "(", "job_config", ",", "time", "=", "Time", ".", "now", ")", "config", "=", "prepare_arguments", "(", "job_config", ".", "dup", ")", "if", "config", ".", "delete", "(", "'include_metadata'", ")", "config", "[", "'args'", "]", "=", "arguments_with_metadata", "(", "config", "[", "'args'", "]", ",", "scheduled_at", ":", "time", ".", "to_f", ")", "end", "if", "active_job_enqueue?", "(", "config", "[", "'class'", "]", ")", "SidekiqScheduler", "::", "Utils", ".", "enqueue_with_active_job", "(", "config", ")", "else", "SidekiqScheduler", "::", "Utils", ".", "enqueue_with_sidekiq", "(", "config", ")", "end", "end" ]
Enqueue a job based on a config hash @param job_config [Hash] the job configuration @param time [Time] time the job is enqueued
[ "Enqueue", "a", "job", "based", "on", "a", "config", "hash" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L158-L170
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.schedule_state
def schedule_state(name) state = SidekiqScheduler::RedisManager.get_job_state(name) state ? JSON.parse(state) : {} end
ruby
def schedule_state(name) state = SidekiqScheduler::RedisManager.get_job_state(name) state ? JSON.parse(state) : {} end
[ "def", "schedule_state", "(", "name", ")", "state", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_state", "(", "name", ")", "state", "?", "JSON", ".", "parse", "(", "state", ")", ":", "{", "}", "end" ]
Retrieves a schedule state @param name [String] with the schedule's name @return [Hash] with the schedule's state
[ "Retrieves", "a", "schedule", "state" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L262-L266
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.arguments_with_metadata
def arguments_with_metadata(args, metadata) if args.is_a? Array [*args, metadata] else [args, metadata] end end
ruby
def arguments_with_metadata(args, metadata) if args.is_a? Array [*args, metadata] else [args, metadata] end end
[ "def", "arguments_with_metadata", "(", "args", ",", "metadata", ")", "if", "args", ".", "is_a?", "Array", "[", "args", ",", "metadata", "]", "else", "[", "args", ",", "metadata", "]", "end", "end" ]
Adds a Hash with schedule metadata as the last argument to call the worker. It currently returns the schedule time as a Float number representing the milisencods since epoch. @example with hash argument arguments_with_metadata({value: 1}, scheduled_at: Time.now) #=> [{value: 1}, {scheduled_at: <miliseconds since epoch>}] @param args [Array|Hash] @param metadata [Hash] @return [Array] arguments with added metadata
[ "Adds", "a", "Hash", "with", "schedule", "metadata", "as", "the", "last", "argument", "to", "call", "the", "worker", ".", "It", "currently", "returns", "the", "schedule", "time", "as", "a", "Float", "number", "representing", "the", "milisencods", "since", "epoch", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L287-L293
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.active_job_enqueue?
def active_job_enqueue?(klass) klass.is_a?(Class) && defined?(ActiveJob::Enqueuing) && klass.included_modules.include?(ActiveJob::Enqueuing) end
ruby
def active_job_enqueue?(klass) klass.is_a?(Class) && defined?(ActiveJob::Enqueuing) && klass.included_modules.include?(ActiveJob::Enqueuing) end
[ "def", "active_job_enqueue?", "(", "klass", ")", "klass", ".", "is_a?", "(", "Class", ")", "&&", "defined?", "(", "ActiveJob", "::", "Enqueuing", ")", "&&", "klass", ".", "included_modules", ".", "include?", "(", "ActiveJob", "::", "Enqueuing", ")", "end" ]
Returns true if the enqueuing needs to be done for an ActiveJob class false otherwise. @param [Class] klass the class to check is decendant from ActiveJob @return [Boolean]
[ "Returns", "true", "if", "the", "enqueuing", "needs", "to", "be", "done", "for", "an", "ActiveJob", "class", "false", "otherwise", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L317-L320
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.prepare_arguments
def prepare_arguments(config) config['class'] = SidekiqScheduler::Utils.try_to_constantize(config['class']) if config['args'].is_a?(Hash) config['args'].symbolize_keys! if config['args'].respond_to?(:symbolize_keys!) else config['args'] = Array(config['args']) end config end
ruby
def prepare_arguments(config) config['class'] = SidekiqScheduler::Utils.try_to_constantize(config['class']) if config['args'].is_a?(Hash) config['args'].symbolize_keys! if config['args'].respond_to?(:symbolize_keys!) else config['args'] = Array(config['args']) end config end
[ "def", "prepare_arguments", "(", "config", ")", "config", "[", "'class'", "]", "=", "SidekiqScheduler", "::", "Utils", ".", "try_to_constantize", "(", "config", "[", "'class'", "]", ")", "if", "config", "[", "'args'", "]", ".", "is_a?", "(", "Hash", ")", "config", "[", "'args'", "]", ".", "symbolize_keys!", "if", "config", "[", "'args'", "]", ".", "respond_to?", "(", ":symbolize_keys!", ")", "else", "config", "[", "'args'", "]", "=", "Array", "(", "config", "[", "'args'", "]", ")", "end", "config", "end" ]
Convert the given arguments in the format expected to be enqueued. @param [Hash] config the options to be converted @option config [String] class the job class @option config [Hash/Array] args the arguments to be passed to the job class @return [Hash]
[ "Convert", "the", "given", "arguments", "in", "the", "format", "expected", "to", "be", "enqueued", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L330-L340
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/job_presenter.rb
SidekiqScheduler.JobPresenter.next_time
def next_time execution_time = SidekiqScheduler::RedisManager.get_job_next_time(name) relative_time(Time.parse(execution_time)) if execution_time end
ruby
def next_time execution_time = SidekiqScheduler::RedisManager.get_job_next_time(name) relative_time(Time.parse(execution_time)) if execution_time end
[ "def", "next_time", "execution_time", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_next_time", "(", "name", ")", "relative_time", "(", "Time", ".", "parse", "(", "execution_time", ")", ")", "if", "execution_time", "end" ]
Returns the next time execution for the job @return [String] with the job's next time
[ "Returns", "the", "next", "time", "execution", "for", "the", "job" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/job_presenter.rb#L22-L26
train
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/job_presenter.rb
SidekiqScheduler.JobPresenter.last_time
def last_time execution_time = SidekiqScheduler::RedisManager.get_job_last_time(name) relative_time(Time.parse(execution_time)) if execution_time end
ruby
def last_time execution_time = SidekiqScheduler::RedisManager.get_job_last_time(name) relative_time(Time.parse(execution_time)) if execution_time end
[ "def", "last_time", "execution_time", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_last_time", "(", "name", ")", "relative_time", "(", "Time", ".", "parse", "(", "execution_time", ")", ")", "if", "execution_time", "end" ]
Returns the last execution time for the job @return [String] with the job's last time
[ "Returns", "the", "last", "execution", "time", "for", "the", "job" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/job_presenter.rb#L31-L35
train
stitchfix/stitches
lib/stitches/deprecation.rb
Stitches.Deprecation.deprecated
def deprecated(gone_on:,&block) response.set_header("Sunset",Date.parse(gone_on).in_time_zone("GMT").midnight.strftime("%a, %e %b %Y %H:%M:%S %Z")) Rails.logger.info("DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}") block.() end
ruby
def deprecated(gone_on:,&block) response.set_header("Sunset",Date.parse(gone_on).in_time_zone("GMT").midnight.strftime("%a, %e %b %Y %H:%M:%S %Z")) Rails.logger.info("DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}") block.() end
[ "def", "deprecated", "(", "gone_on", ":", ",", "&", "block", ")", "response", ".", "set_header", "(", "\"Sunset\"", ",", "Date", ".", "parse", "(", "gone_on", ")", ".", "in_time_zone", "(", "\"GMT\"", ")", ".", "midnight", ".", "strftime", "(", "\"%a, %e %b %Y %H:%M:%S %Z\"", ")", ")", "Rails", ".", "logger", ".", "info", "(", "\"DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}\"", ")", "block", ".", "(", ")", "end" ]
Indicate that this endpoint is deprecated and will go away on the given date. gon_on: - date, as a string, when this endpoint will go away block - the contents of the endpoint Example: def show deprecated gone_on: "2019-04-09" do render widgets: { Widget.find(params[:id]) } end end
[ "Indicate", "that", "this", "endpoint", "is", "deprecated", "and", "will", "go", "away", "on", "the", "given", "date", "." ]
80231b33db26b2e82d13e2794c448beb21169527
https://github.com/stitchfix/stitches/blob/80231b33db26b2e82d13e2794c448beb21169527/lib/stitches/deprecation.rb#L20-L24
train
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.align_column
def align_column n, alignment r = rows column(n).each_with_index do |col, i| cell = r[i][n] next unless cell cell.alignment = alignment unless cell.alignment? end end
ruby
def align_column n, alignment r = rows column(n).each_with_index do |col, i| cell = r[i][n] next unless cell cell.alignment = alignment unless cell.alignment? end end
[ "def", "align_column", "n", ",", "alignment", "r", "=", "rows", "column", "(", "n", ")", ".", "each_with_index", "do", "|", "col", ",", "i", "|", "cell", "=", "r", "[", "i", "]", "[", "n", "]", "next", "unless", "cell", "cell", ".", "alignment", "=", "alignment", "unless", "cell", ".", "alignment?", "end", "end" ]
Generates a ASCII table with the given _options_. Align column _n_ to the given _alignment_ of :center, :left, or :right.
[ "Generates", "a", "ASCII", "table", "with", "the", "given", "_options_", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L28-L35
train
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.add_row
def add_row array row = array == :separator ? Separator.new(self) : Row.new(self, array) @rows << row require_column_widths_recalc unless row.is_a?(Separator) end
ruby
def add_row array row = array == :separator ? Separator.new(self) : Row.new(self, array) @rows << row require_column_widths_recalc unless row.is_a?(Separator) end
[ "def", "add_row", "array", "row", "=", "array", "==", ":separator", "?", "Separator", ".", "new", "(", "self", ")", ":", "Row", ".", "new", "(", "self", ",", "array", ")", "@rows", "<<", "row", "require_column_widths_recalc", "unless", "row", ".", "is_a?", "(", "Separator", ")", "end" ]
Add a row.
[ "Add", "a", "row", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L40-L44
train
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.column
def column n, method = :value, array = rows array.map { |row| # for each cells in a row, find the column with index # just greater than the required one, and go back one. index = col = 0 row.cells.each do |cell| break if index > n index += cell.colspan col += 1 end cell = row[col - 1] cell && method ? cell.__send__(method) : cell }.compact end
ruby
def column n, method = :value, array = rows array.map { |row| # for each cells in a row, find the column with index # just greater than the required one, and go back one. index = col = 0 row.cells.each do |cell| break if index > n index += cell.colspan col += 1 end cell = row[col - 1] cell && method ? cell.__send__(method) : cell }.compact end
[ "def", "column", "n", ",", "method", "=", ":value", ",", "array", "=", "rows", "array", ".", "map", "{", "|", "row", "|", "# for each cells in a row, find the column with index", "# just greater than the required one, and go back one.", "index", "=", "col", "=", "0", "row", ".", "cells", ".", "each", "do", "|", "cell", "|", "break", "if", "index", ">", "n", "index", "+=", "cell", ".", "colspan", "col", "+=", "1", "end", "cell", "=", "row", "[", "col", "-", "1", "]", "cell", "&&", "method", "?", "cell", ".", "__send__", "(", "method", ")", ":", "cell", "}", ".", "compact", "end" ]
Return column _n_.
[ "Return", "column", "_n_", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L65-L78
train
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.headings=
def headings= arrays arrays = [arrays] unless arrays.first.is_a?(Array) @headings = arrays.map do |array| row = Row.new(self, array) require_column_widths_recalc row end end
ruby
def headings= arrays arrays = [arrays] unless arrays.first.is_a?(Array) @headings = arrays.map do |array| row = Row.new(self, array) require_column_widths_recalc row end end
[ "def", "headings", "=", "arrays", "arrays", "=", "[", "arrays", "]", "unless", "arrays", ".", "first", ".", "is_a?", "(", "Array", ")", "@headings", "=", "arrays", ".", "map", "do", "|", "array", "|", "row", "=", "Row", ".", "new", "(", "self", ",", "array", ")", "require_column_widths_recalc", "row", "end", "end" ]
Set the headings
[ "Set", "the", "headings" ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L112-L119
train
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.render
def render separator = Separator.new(self) buffer = style.border_top ? [separator] : [] unless @title.nil? buffer << Row.new(self, [title_cell_options]) buffer << separator end @headings.each do |row| unless row.cells.empty? buffer << row buffer << separator end end if style.all_separators buffer += @rows.product([separator]).flatten else buffer += @rows buffer << separator if style.border_bottom end buffer.map { |r| style.margin_left + r.render.rstrip }.join("\n") end
ruby
def render separator = Separator.new(self) buffer = style.border_top ? [separator] : [] unless @title.nil? buffer << Row.new(self, [title_cell_options]) buffer << separator end @headings.each do |row| unless row.cells.empty? buffer << row buffer << separator end end if style.all_separators buffer += @rows.product([separator]).flatten else buffer += @rows buffer << separator if style.border_bottom end buffer.map { |r| style.margin_left + r.render.rstrip }.join("\n") end
[ "def", "render", "separator", "=", "Separator", ".", "new", "(", "self", ")", "buffer", "=", "style", ".", "border_top", "?", "[", "separator", "]", ":", "[", "]", "unless", "@title", ".", "nil?", "buffer", "<<", "Row", ".", "new", "(", "self", ",", "[", "title_cell_options", "]", ")", "buffer", "<<", "separator", "end", "@headings", ".", "each", "do", "|", "row", "|", "unless", "row", ".", "cells", ".", "empty?", "buffer", "<<", "row", "buffer", "<<", "separator", "end", "end", "if", "style", ".", "all_separators", "buffer", "+=", "@rows", ".", "product", "(", "[", "separator", "]", ")", ".", "flatten", "else", "buffer", "+=", "@rows", "buffer", "<<", "separator", "if", "style", ".", "border_bottom", "end", "buffer", ".", "map", "{", "|", "r", "|", "style", ".", "margin_left", "+", "r", ".", "render", ".", "rstrip", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Render the table.
[ "Render", "the", "table", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L124-L144
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.analyze
def analyze Core::Runner.base_path = @path Core::Runner.config_path = @options['config'] @runner = Core::Runner.new analyze_source_codes analyze_vcs end
ruby
def analyze Core::Runner.base_path = @path Core::Runner.config_path = @options['config'] @runner = Core::Runner.new analyze_source_codes analyze_vcs end
[ "def", "analyze", "Core", "::", "Runner", ".", "base_path", "=", "@path", "Core", "::", "Runner", ".", "config_path", "=", "@options", "[", "'config'", "]", "@runner", "=", "Core", "::", "Runner", ".", "new", "analyze_source_codes", "analyze_vcs", "end" ]
Analyze rails codes. there are two steps to check rails codes, 1. prepare process, check all model and mailer files. 2. review process, check all files. if there are violations to rails best practices, output them. @param [String] path the directory of rails project @param [Hash] options
[ "Analyze", "rails", "codes", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L52-L59
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.process
def process(process) parse_files.each do |file| begin puts file if @options['debug'] @runner.send(process, file, File.read(file)) rescue StandardError if @options['debug'] warning = "#{file} looks like it's not a valid Ruby file. Skipping..." plain_output(warning, 'red') end end @bar.increment if display_bar? end @runner.send("after_#{process}") end
ruby
def process(process) parse_files.each do |file| begin puts file if @options['debug'] @runner.send(process, file, File.read(file)) rescue StandardError if @options['debug'] warning = "#{file} looks like it's not a valid Ruby file. Skipping..." plain_output(warning, 'red') end end @bar.increment if display_bar? end @runner.send("after_#{process}") end
[ "def", "process", "(", "process", ")", "parse_files", ".", "each", "do", "|", "file", "|", "begin", "puts", "file", "if", "@options", "[", "'debug'", "]", "@runner", ".", "send", "(", "process", ",", "file", ",", "File", ".", "read", "(", "file", ")", ")", "rescue", "StandardError", "if", "@options", "[", "'debug'", "]", "warning", "=", "\"#{file} looks like it's not a valid Ruby file. Skipping...\"", "plain_output", "(", "warning", ",", "'red'", ")", "end", "end", "@bar", ".", "increment", "if", "display_bar?", "end", "@runner", ".", "send", "(", "\"after_#{process}\"", ")", "end" ]
process lexical, prepare or reivew. get all files for the process, analyze each file, and increment progress bar unless debug. @param [String] process the process name, lexical, prepare or review.
[ "process", "lexical", "prepare", "or", "reivew", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L87-L101
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.parse_files
def parse_files @parse_files ||= begin files = expand_dirs_to_files(@path) files = file_sort(files) if @options['only'].present? files = file_accept(files, @options['only']) end # By default, tmp, vender, spec, test, features are ignored. %w[vendor spec test features tmp].each do |dir| files = file_ignore(files, File.join(@path, dir)) unless @options[dir] end # Exclude files based on exclude regexes if the option is set. @options['exclude'].each do |pattern| files = file_ignore(files, pattern) end %w[Capfile Gemfile Gemfile.lock].each do |file| files.unshift File.join(@path, file) end files.compact end end
ruby
def parse_files @parse_files ||= begin files = expand_dirs_to_files(@path) files = file_sort(files) if @options['only'].present? files = file_accept(files, @options['only']) end # By default, tmp, vender, spec, test, features are ignored. %w[vendor spec test features tmp].each do |dir| files = file_ignore(files, File.join(@path, dir)) unless @options[dir] end # Exclude files based on exclude regexes if the option is set. @options['exclude'].each do |pattern| files = file_ignore(files, pattern) end %w[Capfile Gemfile Gemfile.lock].each do |file| files.unshift File.join(@path, file) end files.compact end end
[ "def", "parse_files", "@parse_files", "||=", "begin", "files", "=", "expand_dirs_to_files", "(", "@path", ")", "files", "=", "file_sort", "(", "files", ")", "if", "@options", "[", "'only'", "]", ".", "present?", "files", "=", "file_accept", "(", "files", ",", "@options", "[", "'only'", "]", ")", "end", "# By default, tmp, vender, spec, test, features are ignored.", "%w[", "vendor", "spec", "test", "features", "tmp", "]", ".", "each", "do", "|", "dir", "|", "files", "=", "file_ignore", "(", "files", ",", "File", ".", "join", "(", "@path", ",", "dir", ")", ")", "unless", "@options", "[", "dir", "]", "end", "# Exclude files based on exclude regexes if the option is set.", "@options", "[", "'exclude'", "]", ".", "each", "do", "|", "pattern", "|", "files", "=", "file_ignore", "(", "files", ",", "pattern", ")", "end", "%w[", "Capfile", "Gemfile", "Gemfile.lock", "]", ".", "each", "do", "|", "file", "|", "files", ".", "unshift", "File", ".", "join", "(", "@path", ",", "file", ")", "end", "files", ".", "compact", "end", "end" ]
get all files for parsing. @return [Array] all files for parsing
[ "get", "all", "files", "for", "parsing", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L106-L131
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.expand_dirs_to_files
def expand_dirs_to_files(*dirs) extensions = %w[rb erb rake rhtml haml slim builder rxml rabl] dirs.flatten.map do |entry| next unless File.exist? entry if File.directory? entry Dir[File.join(entry, '**', "*.{#{extensions.join(',')}}")] else entry end end.flatten end
ruby
def expand_dirs_to_files(*dirs) extensions = %w[rb erb rake rhtml haml slim builder rxml rabl] dirs.flatten.map do |entry| next unless File.exist? entry if File.directory? entry Dir[File.join(entry, '**', "*.{#{extensions.join(',')}}")] else entry end end.flatten end
[ "def", "expand_dirs_to_files", "(", "*", "dirs", ")", "extensions", "=", "%w[", "rb", "erb", "rake", "rhtml", "haml", "slim", "builder", "rxml", "rabl", "]", "dirs", ".", "flatten", ".", "map", "do", "|", "entry", "|", "next", "unless", "File", ".", "exist?", "entry", "if", "File", ".", "directory?", "entry", "Dir", "[", "File", ".", "join", "(", "entry", ",", "'**'", ",", "\"*.{#{extensions.join(',')}}\"", ")", "]", "else", "entry", "end", "end", ".", "flatten", "end" ]
expand all files with extenstion rb, erb, haml, slim, builder and rxml under the dirs @param [Array] dirs what directories to expand @return [Array] all files expanded
[ "expand", "all", "files", "with", "extenstion", "rb", "erb", "haml", "slim", "builder", "and", "rxml", "under", "the", "dirs" ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L137-L149
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.file_sort
def file_sort(files) models = files.find_all { |file| file =~ Core::Check::MODEL_FILES } mailers = files.find_all { |file| file =~ Core::Check::MAILER_FILES } helpers = files.find_all { |file| file =~ Core::Check::HELPER_FILES } others = files.find_all { |file| file !~ Core::Check::MAILER_FILES && file !~ Core::Check::MODEL_FILES && file !~ Core::Check::HELPER_FILES } models + mailers + helpers + others end
ruby
def file_sort(files) models = files.find_all { |file| file =~ Core::Check::MODEL_FILES } mailers = files.find_all { |file| file =~ Core::Check::MAILER_FILES } helpers = files.find_all { |file| file =~ Core::Check::HELPER_FILES } others = files.find_all { |file| file !~ Core::Check::MAILER_FILES && file !~ Core::Check::MODEL_FILES && file !~ Core::Check::HELPER_FILES } models + mailers + helpers + others end
[ "def", "file_sort", "(", "files", ")", "models", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "=~", "Core", "::", "Check", "::", "MODEL_FILES", "}", "mailers", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "=~", "Core", "::", "Check", "::", "MAILER_FILES", "}", "helpers", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "=~", "Core", "::", "Check", "::", "HELPER_FILES", "}", "others", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "!~", "Core", "::", "Check", "::", "MAILER_FILES", "&&", "file", "!~", "Core", "::", "Check", "::", "MODEL_FILES", "&&", "file", "!~", "Core", "::", "Check", "::", "HELPER_FILES", "}", "models", "+", "mailers", "+", "helpers", "+", "others", "end" ]
sort files, models first, mailers, helpers, and then sort other files by characters. models and mailers first as for prepare process. @param [Array] files @return [Array] sorted files
[ "sort", "files", "models", "first", "mailers", "helpers", "and", "then", "sort", "other", "files", "by", "characters", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L157-L163
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.file_accept
def file_accept(files, patterns) files.select { |file| patterns.any? { |pattern| file =~ pattern } } end
ruby
def file_accept(files, patterns) files.select { |file| patterns.any? { |pattern| file =~ pattern } } end
[ "def", "file_accept", "(", "files", ",", "patterns", ")", "files", ".", "select", "{", "|", "file", "|", "patterns", ".", "any?", "{", "|", "pattern", "|", "file", "=~", "pattern", "}", "}", "end" ]
accept specific files. @param [Array] files @param [Regexp] patterns, files match any pattern will be accepted
[ "accept", "specific", "files", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L178-L180
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.output_json_errors
def output_json_errors errors_as_hashes = errors.map do |err| { filename: err.filename, line_number: err.line_number, message: err.message } end File.open(@options['output-file'], 'w+') do |file| file.write JSON.dump(errors_as_hashes) end end
ruby
def output_json_errors errors_as_hashes = errors.map do |err| { filename: err.filename, line_number: err.line_number, message: err.message } end File.open(@options['output-file'], 'w+') do |file| file.write JSON.dump(errors_as_hashes) end end
[ "def", "output_json_errors", "errors_as_hashes", "=", "errors", ".", "map", "do", "|", "err", "|", "{", "filename", ":", "err", ".", "filename", ",", "line_number", ":", "err", ".", "line_number", ",", "message", ":", "err", ".", "message", "}", "end", "File", ".", "open", "(", "@options", "[", "'output-file'", "]", ",", "'w+'", ")", "do", "|", "file", "|", "file", ".", "write", "JSON", ".", "dump", "(", "errors_as_hashes", ")", "end", "end" ]
output errors with json format.
[ "output", "errors", "with", "json", "format", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L290-L302
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.plain_output
def plain_output(message, color) if @options['without-color'] puts message else puts Colorize.send(color, message) end end
ruby
def plain_output(message, color) if @options['without-color'] puts message else puts Colorize.send(color, message) end end
[ "def", "plain_output", "(", "message", ",", "color", ")", "if", "@options", "[", "'without-color'", "]", "puts", "message", "else", "puts", "Colorize", ".", "send", "(", "color", ",", "message", ")", "end", "end" ]
plain output with color. @param [String] message to output @param [String] color
[ "plain", "output", "with", "color", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L308-L314
train
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.analyze_source_codes
def analyze_source_codes @bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 3) if display_bar? %w[lexical prepare review].each { |process| send(:process, process) } @bar.finish if display_bar? end
ruby
def analyze_source_codes @bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 3) if display_bar? %w[lexical prepare review].each { |process| send(:process, process) } @bar.finish if display_bar? end
[ "def", "analyze_source_codes", "@bar", "=", "ProgressBar", ".", "create", "(", "title", ":", "'Source Code'", ",", "total", ":", "parse_files", ".", "size", "*", "3", ")", "if", "display_bar?", "%w[", "lexical", "prepare", "review", "]", ".", "each", "{", "|", "process", "|", "send", "(", ":process", ",", "process", ")", "}", "@bar", ".", "finish", "if", "display_bar?", "end" ]
analyze source codes.
[ "analyze", "source", "codes", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L317-L321
train
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks._run_callbacks
def _run_callbacks(kind, *args) #:nodoc: options = args.last # Last callback arg MUST be a Hash send("_#{kind}").each do |callback, conditions| invalid = conditions.find do |key, value| value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key]) end callback.call(*args) unless invalid end end
ruby
def _run_callbacks(kind, *args) #:nodoc: options = args.last # Last callback arg MUST be a Hash send("_#{kind}").each do |callback, conditions| invalid = conditions.find do |key, value| value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key]) end callback.call(*args) unless invalid end end
[ "def", "_run_callbacks", "(", "kind", ",", "*", "args", ")", "#:nodoc:", "options", "=", "args", ".", "last", "# Last callback arg MUST be a Hash", "send", "(", "\"_#{kind}\"", ")", ".", "each", "do", "|", "callback", ",", "conditions", "|", "invalid", "=", "conditions", ".", "find", "do", "|", "key", ",", "value", "|", "value", ".", "is_a?", "(", "Array", ")", "?", "!", "value", ".", "include?", "(", "options", "[", "key", "]", ")", ":", "(", "value", "!=", "options", "[", "key", "]", ")", "end", "callback", ".", "call", "(", "args", ")", "unless", "invalid", "end", "end" ]
Hook to _run_callbacks asserting for conditions.
[ "Hook", "to", "_run_callbacks", "asserting", "for", "conditions", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L7-L17
train
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.after_failed_fetch
def after_failed_fetch(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _after_failed_fetch.send(method, [block, options]) end
ruby
def after_failed_fetch(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _after_failed_fetch.send(method, [block, options]) end
[ "def", "after_failed_fetch", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_after_failed_fetch", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs if no user could be fetched, meaning there is now no user logged in. Parameters: <options> Some options which specify when the callback should be executed scope - Executes the callback only if it matches the scope(s) given <block> A block to contain logic for the callback Block Parameters: |user, auth, scope| user - The authenticated user for the current scope auth - The warden proxy object opts - any options passed into the authenticate call including :scope Example: Warden::Manager.after_failed_fetch do |user, auth, opts| I18n.locale = :en end :api: public
[ "A", "callback", "that", "runs", "if", "no", "user", "could", "be", "fetched", "meaning", "there", "is", "now", "no", "user", "logged", "in", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L138-L141
train
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.before_logout
def before_logout(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _before_logout.send(method, [block, options]) end
ruby
def before_logout(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _before_logout.send(method, [block, options]) end
[ "def", "before_logout", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_before_logout", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs just prior to the logout of each scope. Parameters: <options> Some options which specify when the callback should be executed scope - Executes the callback only if it matches the scope(s) given <block> A block to contain logic for the callback Block Parameters: |user, auth, scope| user - The authenticated user for the current scope auth - The warden proxy object opts - any options passed into the authenticate call including :scope Example: Warden::Manager.before_logout do |user, auth, opts| user.forget_me! end :api: public
[ "A", "callback", "that", "runs", "just", "prior", "to", "the", "logout", "of", "each", "scope", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L166-L169
train
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.on_request
def on_request(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _on_request.send(method, [block, options]) end
ruby
def on_request(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _on_request.send(method, [block, options]) end
[ "def", "on_request", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_on_request", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs on each request, just after the proxy is initialized Parameters: <block> A block to contain logic for the callback Block Parameters: |proxy| proxy - The warden proxy object for the request Example: user = "A User" Warden::Manager.on_request do |proxy| proxy.set_user = user end :api: public
[ "A", "callback", "that", "runs", "on", "each", "request", "just", "after", "the", "proxy", "is", "initialized" ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L191-L194
train
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy.user
def user(argument = {}) opts = argument.is_a?(Hash) ? argument : { :scope => argument } scope = (opts[:scope] ||= @config.default_scope) if @users.has_key?(scope) @users[scope] else unless user = session_serializer.fetch(scope) run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_failed_fetch, user, self, :scope => scope) if run_callbacks end @users[scope] = user ? set_user(user, opts.merge(:event => :fetch)) : nil end end
ruby
def user(argument = {}) opts = argument.is_a?(Hash) ? argument : { :scope => argument } scope = (opts[:scope] ||= @config.default_scope) if @users.has_key?(scope) @users[scope] else unless user = session_serializer.fetch(scope) run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_failed_fetch, user, self, :scope => scope) if run_callbacks end @users[scope] = user ? set_user(user, opts.merge(:event => :fetch)) : nil end end
[ "def", "user", "(", "argument", "=", "{", "}", ")", "opts", "=", "argument", ".", "is_a?", "(", "Hash", ")", "?", "argument", ":", "{", ":scope", "=>", "argument", "}", "scope", "=", "(", "opts", "[", ":scope", "]", "||=", "@config", ".", "default_scope", ")", "if", "@users", ".", "has_key?", "(", "scope", ")", "@users", "[", "scope", "]", "else", "unless", "user", "=", "session_serializer", ".", "fetch", "(", "scope", ")", "run_callbacks", "=", "opts", ".", "fetch", "(", ":run_callbacks", ",", "true", ")", "manager", ".", "_run_callbacks", "(", ":after_failed_fetch", ",", "user", ",", "self", ",", ":scope", "=>", "scope", ")", "if", "run_callbacks", "end", "@users", "[", "scope", "]", "=", "user", "?", "set_user", "(", "user", ",", "opts", ".", "merge", "(", ":event", "=>", ":fetch", ")", ")", ":", "nil", "end", "end" ]
Provides access to the user object in a given scope for a request. Will be nil if not logged in. Please notice that this method does not perform strategies. Example: # without scope (default user) env['warden'].user # with scope env['warden'].user(:admin) # as a Hash env['warden'].user(:scope => :admin) # with default scope and run_callbacks option env['warden'].user(:run_callbacks => false) # with a scope and run_callbacks option env['warden'].user(:scope => :admin, :run_callbacks => true) :api: public
[ "Provides", "access", "to", "the", "user", "object", "in", "a", "given", "scope", "for", "a", "request", ".", "Will", "be", "nil", "if", "not", "logged", "in", ".", "Please", "notice", "that", "this", "method", "does", "not", "perform", "strategies", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L217-L231
train
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy.logout
def logout(*scopes) if scopes.empty? scopes = @users.keys reset_session = true end scopes.each do |scope| user = @users.delete(scope) manager._run_callbacks(:before_logout, user, self, :scope => scope) raw_session.delete("warden.user.#{scope}.session") unless raw_session.nil? session_serializer.delete(scope, user) end reset_session! if reset_session end
ruby
def logout(*scopes) if scopes.empty? scopes = @users.keys reset_session = true end scopes.each do |scope| user = @users.delete(scope) manager._run_callbacks(:before_logout, user, self, :scope => scope) raw_session.delete("warden.user.#{scope}.session") unless raw_session.nil? session_serializer.delete(scope, user) end reset_session! if reset_session end
[ "def", "logout", "(", "*", "scopes", ")", "if", "scopes", ".", "empty?", "scopes", "=", "@users", ".", "keys", "reset_session", "=", "true", "end", "scopes", ".", "each", "do", "|", "scope", "|", "user", "=", "@users", ".", "delete", "(", "scope", ")", "manager", ".", "_run_callbacks", "(", ":before_logout", ",", "user", ",", "self", ",", ":scope", "=>", "scope", ")", "raw_session", ".", "delete", "(", "\"warden.user.#{scope}.session\"", ")", "unless", "raw_session", ".", "nil?", "session_serializer", ".", "delete", "(", "scope", ",", "user", ")", "end", "reset_session!", "if", "reset_session", "end" ]
Provides logout functionality. The logout also manages any authenticated data storage and clears it when a user logs out. Parameters: scopes - a list of scopes to logout Example: # Logout everyone and clear the session env['warden'].logout # Logout the default user but leave the rest of the session alone env['warden'].logout(:default) # Logout the :publisher and :admin user env['warden'].logout(:publisher, :admin) :api: public
[ "Provides", "logout", "functionality", ".", "The", "logout", "also", "manages", "any", "authenticated", "data", "storage", "and", "clears", "it", "when", "a", "user", "logs", "out", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L266-L281
train
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy._run_strategies_for
def _run_strategies_for(scope, args) #:nodoc: self.winning_strategy = @winning_strategies[scope] return if winning_strategy && winning_strategy.halted? # Do not run any strategy if locked return if @locked if args.empty? defaults = @config[:default_strategies] strategies = defaults[scope] || defaults[:_all] end (strategies || args).each do |name| strategy = _fetch_strategy(name, scope) next unless strategy && !strategy.performed? && strategy.valid? strategy._run! self.winning_strategy = @winning_strategies[scope] = strategy break if strategy.halted? end end
ruby
def _run_strategies_for(scope, args) #:nodoc: self.winning_strategy = @winning_strategies[scope] return if winning_strategy && winning_strategy.halted? # Do not run any strategy if locked return if @locked if args.empty? defaults = @config[:default_strategies] strategies = defaults[scope] || defaults[:_all] end (strategies || args).each do |name| strategy = _fetch_strategy(name, scope) next unless strategy && !strategy.performed? && strategy.valid? strategy._run! self.winning_strategy = @winning_strategies[scope] = strategy break if strategy.halted? end end
[ "def", "_run_strategies_for", "(", "scope", ",", "args", ")", "#:nodoc:", "self", ".", "winning_strategy", "=", "@winning_strategies", "[", "scope", "]", "return", "if", "winning_strategy", "&&", "winning_strategy", ".", "halted?", "# Do not run any strategy if locked", "return", "if", "@locked", "if", "args", ".", "empty?", "defaults", "=", "@config", "[", ":default_strategies", "]", "strategies", "=", "defaults", "[", "scope", "]", "||", "defaults", "[", ":_all", "]", "end", "(", "strategies", "||", "args", ")", ".", "each", "do", "|", "name", "|", "strategy", "=", "_fetch_strategy", "(", "name", ",", "scope", ")", "next", "unless", "strategy", "&&", "!", "strategy", ".", "performed?", "&&", "strategy", ".", "valid?", "strategy", ".", "_run!", "self", ".", "winning_strategy", "=", "@winning_strategies", "[", "scope", "]", "=", "strategy", "break", "if", "strategy", ".", "halted?", "end", "end" ]
Run the strategies for a given scope
[ "Run", "the", "strategies", "for", "a", "given", "scope" ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L353-L373
train
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy._fetch_strategy
def _fetch_strategy(name, scope) @strategies[scope][name] ||= if klass = Warden::Strategies[name] klass.new(@env, scope) elsif @config.silence_missing_strategies? nil else raise "Invalid strategy #{name}" end end
ruby
def _fetch_strategy(name, scope) @strategies[scope][name] ||= if klass = Warden::Strategies[name] klass.new(@env, scope) elsif @config.silence_missing_strategies? nil else raise "Invalid strategy #{name}" end end
[ "def", "_fetch_strategy", "(", "name", ",", "scope", ")", "@strategies", "[", "scope", "]", "[", "name", "]", "||=", "if", "klass", "=", "Warden", "::", "Strategies", "[", "name", "]", "klass", ".", "new", "(", "@env", ",", "scope", ")", "elsif", "@config", ".", "silence_missing_strategies?", "nil", "else", "raise", "\"Invalid strategy #{name}\"", "end", "end" ]
Fetches strategies and keep them in a hash cache.
[ "Fetches", "strategies", "and", "keep", "them", "in", "a", "hash", "cache", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L376-L384
train
qpowell/google_places
lib/google_places/request.rb
GooglePlaces.Request.parsed_response
def parsed_response return @response.headers["location"] if @response.code >= 300 && @response.code < 400 raise APIConnectionError.new(@response) if @response.code >= 500 && @response.code < 600 case @response.parsed_response['status'] when 'OK', 'ZERO_RESULTS' @response.parsed_response when 'OVER_QUERY_LIMIT' raise OverQueryLimitError.new(@response) when 'REQUEST_DENIED' raise RequestDeniedError.new(@response) when 'INVALID_REQUEST' raise InvalidRequestError.new(@response) when 'UNKNOWN_ERROR' raise UnknownError.new(@response) when 'NOT_FOUND' raise NotFoundError.new(@response) end end
ruby
def parsed_response return @response.headers["location"] if @response.code >= 300 && @response.code < 400 raise APIConnectionError.new(@response) if @response.code >= 500 && @response.code < 600 case @response.parsed_response['status'] when 'OK', 'ZERO_RESULTS' @response.parsed_response when 'OVER_QUERY_LIMIT' raise OverQueryLimitError.new(@response) when 'REQUEST_DENIED' raise RequestDeniedError.new(@response) when 'INVALID_REQUEST' raise InvalidRequestError.new(@response) when 'UNKNOWN_ERROR' raise UnknownError.new(@response) when 'NOT_FOUND' raise NotFoundError.new(@response) end end
[ "def", "parsed_response", "return", "@response", ".", "headers", "[", "\"location\"", "]", "if", "@response", ".", "code", ">=", "300", "&&", "@response", ".", "code", "<", "400", "raise", "APIConnectionError", ".", "new", "(", "@response", ")", "if", "@response", ".", "code", ">=", "500", "&&", "@response", ".", "code", "<", "600", "case", "@response", ".", "parsed_response", "[", "'status'", "]", "when", "'OK'", ",", "'ZERO_RESULTS'", "@response", ".", "parsed_response", "when", "'OVER_QUERY_LIMIT'", "raise", "OverQueryLimitError", ".", "new", "(", "@response", ")", "when", "'REQUEST_DENIED'", "raise", "RequestDeniedError", ".", "new", "(", "@response", ")", "when", "'INVALID_REQUEST'", "raise", "InvalidRequestError", ".", "new", "(", "@response", ")", "when", "'UNKNOWN_ERROR'", "raise", "UnknownError", ".", "new", "(", "@response", ")", "when", "'NOT_FOUND'", "raise", "NotFoundError", ".", "new", "(", "@response", ")", "end", "end" ]
Parse errors from the server respons, if any @raise [OverQueryLimitError] when server response object includes status 'OVER_QUERY_LIMIT' @raise [RequestDeniedError] when server response object includes 'REQUEST_DENIED' @raise [InvalidRequestError] when server response object includes 'INVALID_REQUEST' @raise [UnknownError] when server response object includes 'UNKNOWN_ERROR' @raise [NotFoundError] when server response object includes 'NOT_FOUND' @return [String] the response from the server as JSON
[ "Parse", "errors", "from", "the", "server", "respons", "if", "any" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/request.rb#L361-L378
train
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots
def spots(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list(lat, lng, @api_key, options), detail ) end
ruby
def spots(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list(lat, lng, @api_key, options), detail ) end
[ "def", "spots", "(", "lat", ",", "lng", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list", "(", "lat", ",", "lng", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Creates a new Client instance which proxies the requests to the certain classes @param [String] api_key The api key to use for the requests @param [Hash] options An options hash for requests. Is used as the query parameters on server requests @option options [String,Integer] lat the latitude for the search @option options [String,Integer] lng the longitude for the search @option options [Integer] :radius Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. Note that radius must not be included if <b>:rankby</b> is specified @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :name A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. @option options [String] :keyword A term to be matched against all content that Google has indexed for this Spot, including but not limited to name, type, and address, as well as customer reviews and other third-party content. @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options A Hash containing parameters for search retries @option options [Object] :retry_options[:status] @option options [Integer] :retry_options[:max] the maximum retries @option options [Integer] :retry_options[:delay] the delay between each retry in seconds @see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 List of supported languages @see https://developers.google.com/maps/documentation/places/supported_types List of supported types Search for Spots at the provided location @return [Array<Spot>] @param [String,Integer] lat the latitude for the search @param [String,Integer] lng the longitude for the search @param [Hash] options @option options [Integer] :radius (1000) Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. Note that radius must not be included if :rankby => 'distance' (described below) is specified. <b>Note that this is a mandatory parameter</b> @option options [String] :rankby Specifies the order in which results are listed. Possible values are: - prominence (default). This option sorts results based on their importance. Ranking will favor prominent places within the specified area. Prominence can be affected by a Place's ranking in Google's index, the number of check-ins from your application, global popularity, and other factors. - distance. This option sorts results in ascending order by their distance from the specified location. Ranking results by distance will set a fixed search radius of 50km. One or more of keyword, name, or types is required. @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :name A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. @option options [String] :keyword A term to be matched against all content that Google has indexed for this Spot, including but not limited to name, type, and address, as well as customer reviews and other third-party content. @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 List of supported languages @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Creates", "a", "new", "Client", "instance", "which", "proxies", "the", "requests", "to", "the", "certain", "classes" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L95-L102
train
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_query
def spots_by_query(query, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_query(query, @api_key, options), detail ) end
ruby
def spots_by_query(query, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_query(query, @api_key, options), detail ) end
[ "def", "spots_by_query", "(", "query", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_query", "(", "query", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Search for Spots with a query @return [Array<Spot>] @param [String] query the query to search for @param [Hash] options @option options [String,Integer] lat the latitude for the search @option options [String,Integer] lng the longitude for the search @option options [Integer] :radius (1000) Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. Note that radius must not be included if :rankby => 'distance' (described below) is specified. <b>Note that this is a mandatory parameter</b> @option options [String] :rankby Specifies the order in which results are listed. Possible values are: - prominence (default). This option sorts results based on their importance. Ranking will favor prominent places within the specified area. Prominence can be affected by a Place's ranking in Google's index, the number of check-ins from your application, global popularity, and other factors. - distance. This option sorts results in ascending order by their distance from the specified location. Ranking results by distance will set a fixed search radius of 50km. One or more of keyword, name, or types is required. distance. This option sorts results in ascending order by their distance from the specified location. Ranking results by distance will set a fixed search radius of 50km. One or more of keyword, name, or types is required. @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 List of supported languages @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Search", "for", "Spots", "with", "a", "query" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L160-L167
train
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_bounds
def spots_by_bounds(bounds, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_bounds(bounds, @api_key, options), detail ) end
ruby
def spots_by_bounds(bounds, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_bounds(bounds, @api_key, options), detail ) end
[ "def", "spots_by_bounds", "(", "bounds", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_bounds", "(", "bounds", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Search for Spots within a give SW|NE bounds with query @return [Array<Spot>] @param [Hash] bounds @param [String] api_key the provided api key @param [Hash] options @option bounds [String, Array] :start_point An array that contains the lat/lng pair for the first point in the bounds (rectangle) @option bounds [:start_point][String, Integer] :lat The starting point coordinates latitude value @option bounds [:start_point][String, Integer] :lng The starting point coordinates longitude value @option bounds [String, Array] :end_point An array that contains the lat/lng pair for the end point in the bounds (rectangle) @option bounds [:end_point][String, Integer] :lat The end point coordinates latitude value @option bounds [:end_point][String, Integer] :lng The end point coordinates longitude value @option options [String,Array] :query Restricts the results to Spots matching term(s) in the specified query @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Search", "for", "Spots", "within", "a", "give", "SW|NE", "bounds", "with", "query" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L204-L211
train
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_pagetoken
def spots_by_pagetoken(pagetoken, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_pagetoken(pagetoken, @api_key, options), detail ) end
ruby
def spots_by_pagetoken(pagetoken, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_pagetoken(pagetoken, @api_key, options), detail ) end
[ "def", "spots_by_pagetoken", "(", "pagetoken", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_pagetoken", "(", "pagetoken", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Search for Spots with a pagetoken @return [Array<Spot>] @param [String] pagetoken the next page token to search for @param [Hash] options @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Search", "for", "Spots", "with", "a", "pagetoken" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L229-L236
train
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_radar
def spots_by_radar(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_radar(lat, lng, @api_key, options), detail ) end
ruby
def spots_by_radar(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_radar(lat, lng, @api_key, options), detail ) end
[ "def", "spots_by_radar", "(", "lat", ",", "lng", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_radar", "(", "lat", ",", "lng", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Radar Search Service allows you to search for up to 200 Places at once, but with less detail than is typically returned from a Text Search or Nearby Search request. The search response will include up to 200 Places, identified only by their geographic coordinates and reference. You can send a Place Details request for more information about any of them. @return [Array<Spot>] @param [String,Integer] lat the latitude for the search @param [String,Integer] lng the longitude for the search @param [Hash] options @option options [Integer] :radius (1000) Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. <b>Note that this is a mandatory parameter</b> @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :name A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. @option options [String] :keyword A term to be matched against all content that Google has indexed for this Spot, including but not limited to name, type, and address, as well as customer reviews and other third-party content. @option options [Integer] :minprice Restricts results to only those places within the specified price range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. @option options [Integer] :maxprice Restricts results to only those places within the specified price range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. @option options [Boolean] :opennow Retricts results to those Places that are open for business at the time the query is sent. Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. Setting openNow to false has no effect. @option options [Boolean] :zagatselected Restrict your search to only those locations that are Zagat selected businesses. This parameter does not require a true or false value, simply including the parameter in the request is sufficient to restrict your search. The zagatselected parameter is experimental, and only available to Places API enterprise customers. @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see https://developers.google.com/places/documentation/search#RadarSearchRequests
[ "Radar", "Search", "Service", "allows", "you", "to", "search", "for", "up", "to", "200", "Places", "at", "once", "but", "with", "less", "detail", "than", "is", "typically", "returned", "from", "a", "Text", "Search", "or", "Nearby", "Search", "request", ".", "The", "search", "response", "will", "include", "up", "to", "200", "Places", "identified", "only", "by", "their", "geographic", "coordinates", "and", "reference", ".", "You", "can", "send", "a", "Place", "Details", "request", "for", "more", "information", "about", "any", "of", "them", "." ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L274-L281
train
qpowell/google_places
lib/google_places/photo.rb
GooglePlaces.Photo.fetch_url
def fetch_url(maxwidth, options = {}) language = options.delete(:language) retry_options = options.delete(:retry_options) || {} unless @fetched_url @fetched_url = Request.photo_url( :maxwidth => maxwidth, :photoreference => @photo_reference, :key => @api_key, :retry_options => retry_options ) end @fetched_url end
ruby
def fetch_url(maxwidth, options = {}) language = options.delete(:language) retry_options = options.delete(:retry_options) || {} unless @fetched_url @fetched_url = Request.photo_url( :maxwidth => maxwidth, :photoreference => @photo_reference, :key => @api_key, :retry_options => retry_options ) end @fetched_url end
[ "def", "fetch_url", "(", "maxwidth", ",", "options", "=", "{", "}", ")", "language", "=", "options", ".", "delete", "(", ":language", ")", "retry_options", "=", "options", ".", "delete", "(", ":retry_options", ")", "||", "{", "}", "unless", "@fetched_url", "@fetched_url", "=", "Request", ".", "photo_url", "(", ":maxwidth", "=>", "maxwidth", ",", ":photoreference", "=>", "@photo_reference", ",", ":key", "=>", "@api_key", ",", ":retry_options", "=>", "retry_options", ")", "end", "@fetched_url", "end" ]
Search for a Photo's url with its reference key @return [URL] @param [String] api_key the provided api key @param [Hash] options @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds
[ "Search", "for", "a", "Photo", "s", "url", "with", "its", "reference", "key" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/photo.rb#L23-L36
train
solnic/virtus
lib/virtus/const_missing_extensions.rb
Virtus.ConstMissingExtensions.const_missing
def const_missing(name) Attribute::Builder.determine_type(name) or Axiom::Types.const_defined?(name) && Axiom::Types.const_get(name) or super end
ruby
def const_missing(name) Attribute::Builder.determine_type(name) or Axiom::Types.const_defined?(name) && Axiom::Types.const_get(name) or super end
[ "def", "const_missing", "(", "name", ")", "Attribute", "::", "Builder", ".", "determine_type", "(", "name", ")", "or", "Axiom", "::", "Types", ".", "const_defined?", "(", "name", ")", "&&", "Axiom", "::", "Types", ".", "const_get", "(", "name", ")", "or", "super", "end" ]
Hooks into const missing process to determine types of attributes @param [String] name @return [Class] @api private
[ "Hooks", "into", "const", "missing", "process", "to", "determine", "types", "of", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/const_missing_extensions.rb#L11-L15
train
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.each
def each return to_enum unless block_given? @index.each { |name, attribute| yield attribute if name.kind_of?(Symbol) } self end
ruby
def each return to_enum unless block_given? @index.each { |name, attribute| yield attribute if name.kind_of?(Symbol) } self end
[ "def", "each", "return", "to_enum", "unless", "block_given?", "@index", ".", "each", "{", "|", "name", ",", "attribute", "|", "yield", "attribute", "if", "name", ".", "kind_of?", "(", "Symbol", ")", "}", "self", "end" ]
Initialize an AttributeSet @param [AttributeSet] parent @param [Array] attributes @return [undefined] @api private Iterate over each attribute in the set @example attribute_set = AttributeSet.new(attributes, parent) attribute_set.each { |attribute| ... } @yield [attribute] @yieldparam [Attribute] attribute each attribute in the set @return [self] @api public
[ "Initialize", "an", "AttributeSet" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L44-L48
train
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.define_reader_method
def define_reader_method(attribute, method_name, visibility) define_method(method_name) { attribute.get(self) } send(visibility, method_name) end
ruby
def define_reader_method(attribute, method_name, visibility) define_method(method_name) { attribute.get(self) } send(visibility, method_name) end
[ "def", "define_reader_method", "(", "attribute", ",", "method_name", ",", "visibility", ")", "define_method", "(", "method_name", ")", "{", "attribute", ".", "get", "(", "self", ")", "}", "send", "(", "visibility", ",", "method_name", ")", "end" ]
Defines an attribute reader method @param [Attribute] attribute @param [Symbol] method_name @param [Symbol] visibility @return [undefined] @api private
[ "Defines", "an", "attribute", "reader", "method" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L131-L134
train
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.define_writer_method
def define_writer_method(attribute, method_name, visibility) define_method(method_name) { |value| attribute.set(self, value) } send(visibility, method_name) end
ruby
def define_writer_method(attribute, method_name, visibility) define_method(method_name) { |value| attribute.set(self, value) } send(visibility, method_name) end
[ "def", "define_writer_method", "(", "attribute", ",", "method_name", ",", "visibility", ")", "define_method", "(", "method_name", ")", "{", "|", "value", "|", "attribute", ".", "set", "(", "self", ",", "value", ")", "}", "send", "(", "visibility", ",", "method_name", ")", "end" ]
Defines an attribute writer method @param [Attribute] attribute @param [Symbol] method_name @param [Symbol] visibility @return [undefined] @api private
[ "Defines", "an", "attribute", "writer", "method" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L145-L148
train
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.get
def get(object) each_with_object({}) do |attribute, attributes| name = attribute.name attributes[name] = object.__send__(name) if attribute.public_reader? end end
ruby
def get(object) each_with_object({}) do |attribute, attributes| name = attribute.name attributes[name] = object.__send__(name) if attribute.public_reader? end end
[ "def", "get", "(", "object", ")", "each_with_object", "(", "{", "}", ")", "do", "|", "attribute", ",", "attributes", "|", "name", "=", "attribute", ".", "name", "attributes", "[", "name", "]", "=", "object", ".", "__send__", "(", "name", ")", "if", "attribute", ".", "public_reader?", "end", "end" ]
Get values of all attributes defined for this class, ignoring privacy @return [Hash] @api private
[ "Get", "values", "of", "all", "attributes", "defined", "for", "this", "class", "ignoring", "privacy" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L155-L160
train
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.set
def set(object, attributes) coerce(attributes).each do |name, value| writer_name = "#{name}=" if object.allowed_writer_methods.include?(writer_name) object.__send__(writer_name, value) end end end
ruby
def set(object, attributes) coerce(attributes).each do |name, value| writer_name = "#{name}=" if object.allowed_writer_methods.include?(writer_name) object.__send__(writer_name, value) end end end
[ "def", "set", "(", "object", ",", "attributes", ")", "coerce", "(", "attributes", ")", ".", "each", "do", "|", "name", ",", "value", "|", "writer_name", "=", "\"#{name}=\"", "if", "object", ".", "allowed_writer_methods", ".", "include?", "(", "writer_name", ")", "object", ".", "__send__", "(", "writer_name", ",", "value", ")", "end", "end", "end" ]
Mass-assign attribute values @see Virtus::InstanceMethods#attributes= @return [Hash] @api private
[ "Mass", "-", "assign", "attribute", "values" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L169-L176
train
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.set_defaults
def set_defaults(object, filter = method(:skip_default?)) each do |attribute| next if filter.call(object, attribute) attribute.set_default_value(object) end end
ruby
def set_defaults(object, filter = method(:skip_default?)) each do |attribute| next if filter.call(object, attribute) attribute.set_default_value(object) end end
[ "def", "set_defaults", "(", "object", ",", "filter", "=", "method", "(", ":skip_default?", ")", ")", "each", "do", "|", "attribute", "|", "next", "if", "filter", ".", "call", "(", "object", ",", "attribute", ")", "attribute", ".", "set_default_value", "(", "object", ")", "end", "end" ]
Set default attributes @return [self] @api private
[ "Set", "default", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L183-L188
train
solnic/virtus
lib/virtus/support/type_lookup.rb
Virtus.TypeLookup.determine_type_from_primitive
def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive end type end
ruby
def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive end type end
[ "def", "determine_type_from_primitive", "(", "primitive", ")", "type", "=", "nil", "descendants", ".", "select", "(", ":primitive", ")", ".", "reverse_each", "do", "|", "descendant", "|", "descendant_primitive", "=", "descendant", ".", "primitive", "next", "unless", "primitive", "<=", "descendant_primitive", "type", "=", "descendant", "if", "type", ".", "nil?", "or", "type", ".", "primitive", ">", "descendant_primitive", "end", "type", "end" ]
Return the class given a primitive @param [Class] primitive @return [Class] @return [nil] nil if the type cannot be determined by the primitive @api private
[ "Return", "the", "class", "given", "a", "primitive" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/type_lookup.rb#L82-L90
train
solnic/virtus
lib/virtus/support/type_lookup.rb
Virtus.TypeLookup.determine_type_from_string
def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end
ruby
def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end
[ "def", "determine_type_from_string", "(", "string", ")", "if", "string", "=~", "TYPE_FORMAT", "and", "const_defined?", "(", "string", ",", "EXTRA_CONST_ARGS", ")", "const_get", "(", "string", ",", "EXTRA_CONST_ARGS", ")", "end", "end" ]
Return the class given a string @param [String] string @return [Class] @return [nil] nil if the type cannot be determined by the string @api private
[ "Return", "the", "class", "given", "a", "string" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/type_lookup.rb#L102-L106
train
solnic/virtus
lib/virtus/module_extensions.rb
Virtus.ModuleExtensions.extended
def extended(object) super @inclusions.each { |mod| object.extend(mod) } define_attributes(object) object.set_default_attributes end
ruby
def extended(object) super @inclusions.each { |mod| object.extend(mod) } define_attributes(object) object.set_default_attributes end
[ "def", "extended", "(", "object", ")", "super", "@inclusions", ".", "each", "{", "|", "mod", "|", "object", ".", "extend", "(", "mod", ")", "}", "define_attributes", "(", "object", ")", "object", ".", "set_default_attributes", "end" ]
Extend an object with Virtus methods and define attributes @param [Object] object @return [undefined] @api private
[ "Extend", "an", "object", "with", "Virtus", "methods", "and", "define", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/module_extensions.rb#L44-L49
train
solnic/virtus
lib/virtus/module_extensions.rb
Virtus.ModuleExtensions.included
def included(object) super if Class === object @inclusions.reject do |mod| object.ancestors.include?(mod) end.each do |mod| object.send(:include, mod) end define_attributes(object) else object.extend(ModuleExtensions) ModuleExtensions.setup(object, @inclusions, @attribute_definitions) end end
ruby
def included(object) super if Class === object @inclusions.reject do |mod| object.ancestors.include?(mod) end.each do |mod| object.send(:include, mod) end define_attributes(object) else object.extend(ModuleExtensions) ModuleExtensions.setup(object, @inclusions, @attribute_definitions) end end
[ "def", "included", "(", "object", ")", "super", "if", "Class", "===", "object", "@inclusions", ".", "reject", "do", "|", "mod", "|", "object", ".", "ancestors", ".", "include?", "(", "mod", ")", "end", ".", "each", "do", "|", "mod", "|", "object", ".", "send", "(", ":include", ",", "mod", ")", "end", "define_attributes", "(", "object", ")", "else", "object", ".", "extend", "(", "ModuleExtensions", ")", "ModuleExtensions", ".", "setup", "(", "object", ",", "@inclusions", ",", "@attribute_definitions", ")", "end", "end" ]
Extend a class with Virtus methods and define attributes @param [Object] object @return [undefined] @api private
[ "Extend", "a", "class", "with", "Virtus", "methods", "and", "define", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/module_extensions.rb#L58-L72
train
solnic/virtus
lib/virtus/builder.rb
Virtus.Builder.add_included_hook
def add_included_hook with_hook_context do |context| mod.define_singleton_method :included do |object| Builder.pending << object unless context.finalize? context.modules.each { |mod| object.send(:include, mod) } object.define_singleton_method(:attribute, context.attribute_method) end end end
ruby
def add_included_hook with_hook_context do |context| mod.define_singleton_method :included do |object| Builder.pending << object unless context.finalize? context.modules.each { |mod| object.send(:include, mod) } object.define_singleton_method(:attribute, context.attribute_method) end end end
[ "def", "add_included_hook", "with_hook_context", "do", "|", "context", "|", "mod", ".", "define_singleton_method", ":included", "do", "|", "object", "|", "Builder", ".", "pending", "<<", "object", "unless", "context", ".", "finalize?", "context", ".", "modules", ".", "each", "{", "|", "mod", "|", "object", ".", "send", "(", ":include", ",", "mod", ")", "}", "object", ".", "define_singleton_method", "(", ":attribute", ",", "context", ".", "attribute_method", ")", "end", "end", "end" ]
Adds the .included hook to the anonymous module which then defines the .attribute method to override the default. @return [Module] @api private
[ "Adds", "the", ".", "included", "hook", "to", "the", "anonymous", "module", "which", "then", "defines", "the", ".", "attribute", "method", "to", "override", "the", "default", "." ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/builder.rb#L68-L76
train
solnic/virtus
lib/virtus/support/options.rb
Virtus.Options.options
def options accepted_options.each_with_object({}) do |option_name, options| option_value = send(option_name) options[option_name] = option_value unless option_value.nil? end end
ruby
def options accepted_options.each_with_object({}) do |option_name, options| option_value = send(option_name) options[option_name] = option_value unless option_value.nil? end end
[ "def", "options", "accepted_options", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "option_name", ",", "options", "|", "option_value", "=", "send", "(", "option_name", ")", "options", "[", "option_name", "]", "=", "option_value", "unless", "option_value", ".", "nil?", "end", "end" ]
Returns default options hash for a given attribute class @example Virtus::Attribute::String.options # => {:primitive => String} @return [Hash] a hash of default option values @api public
[ "Returns", "default", "options", "hash", "for", "a", "given", "attribute", "class" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/options.rb#L16-L21
train
solnic/virtus
lib/virtus/support/options.rb
Virtus.Options.accept_options
def accept_options(*new_options) add_accepted_options(new_options) new_options.each { |option| define_option_method(option) } descendants.each { |descendant| descendant.add_accepted_options(new_options) } self end
ruby
def accept_options(*new_options) add_accepted_options(new_options) new_options.each { |option| define_option_method(option) } descendants.each { |descendant| descendant.add_accepted_options(new_options) } self end
[ "def", "accept_options", "(", "*", "new_options", ")", "add_accepted_options", "(", "new_options", ")", "new_options", ".", "each", "{", "|", "option", "|", "define_option_method", "(", "option", ")", "}", "descendants", ".", "each", "{", "|", "descendant", "|", "descendant", ".", "add_accepted_options", "(", "new_options", ")", "}", "self", "end" ]
Defines which options are valid for a given attribute class @example class MyAttribute < Virtus::Attribute accept_options :foo, :bar end @return [self] @api public
[ "Defines", "which", "options", "are", "valid", "for", "a", "given", "attribute", "class" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/options.rb#L47-L52
train
mdp/rotp
lib/rotp/totp.rb
ROTP.TOTP.verify
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now) timecodes = get_timecodes(at, drift_behind, drift_ahead) timecodes = timecodes.select { |t| t > timecode(after) } if after result = nil timecodes.each do |t| result = t * interval if super(otp, generate_otp(t)) end result end
ruby
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now) timecodes = get_timecodes(at, drift_behind, drift_ahead) timecodes = timecodes.select { |t| t > timecode(after) } if after result = nil timecodes.each do |t| result = t * interval if super(otp, generate_otp(t)) end result end
[ "def", "verify", "(", "otp", ",", "drift_ahead", ":", "0", ",", "drift_behind", ":", "0", ",", "after", ":", "nil", ",", "at", ":", "Time", ".", "now", ")", "timecodes", "=", "get_timecodes", "(", "at", ",", "drift_behind", ",", "drift_ahead", ")", "timecodes", "=", "timecodes", ".", "select", "{", "|", "t", "|", "t", ">", "timecode", "(", "after", ")", "}", "if", "after", "result", "=", "nil", "timecodes", ".", "each", "do", "|", "t", "|", "result", "=", "t", "*", "interval", "if", "super", "(", "otp", ",", "generate_otp", "(", "t", ")", ")", "end", "result", "end" ]
Verifies the OTP passed in against the current time OTP and adjacent intervals up to +drift+. Excludes OTPs from `after` and earlier. Returns time value of matching OTP code for use in subsequent call. @param otp [String] the one time password to verify @param drift_behind [Integer] how many seconds to look back @param drift_ahead [Integer] how many seconds to look ahead @param after [Integer] prevent token reuse, last login timestamp @param at [Time] time at which to generate and verify a particular otp. default Time.now @return [Integer, nil] the last successful timestamp interval
[ "Verifies", "the", "OTP", "passed", "in", "against", "the", "current", "time", "OTP", "and", "adjacent", "intervals", "up", "to", "+", "drift", "+", ".", "Excludes", "OTPs", "from", "after", "and", "earlier", ".", "Returns", "time", "value", "of", "matching", "OTP", "code", "for", "use", "in", "subsequent", "call", "." ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/totp.rb#L39-L49
train
mdp/rotp
lib/rotp/totp.rb
ROTP.TOTP.get_timecodes
def get_timecodes(at, drift_behind, drift_ahead) now = timeint(at) timecode_start = timecode(now - drift_behind) timecode_end = timecode(now + drift_ahead) (timecode_start..timecode_end).step(1).to_a end
ruby
def get_timecodes(at, drift_behind, drift_ahead) now = timeint(at) timecode_start = timecode(now - drift_behind) timecode_end = timecode(now + drift_ahead) (timecode_start..timecode_end).step(1).to_a end
[ "def", "get_timecodes", "(", "at", ",", "drift_behind", ",", "drift_ahead", ")", "now", "=", "timeint", "(", "at", ")", "timecode_start", "=", "timecode", "(", "now", "-", "drift_behind", ")", "timecode_end", "=", "timecode", "(", "now", "+", "drift_ahead", ")", "(", "timecode_start", "..", "timecode_end", ")", ".", "step", "(", "1", ")", ".", "to_a", "end" ]
Get back an array of timecodes for a period
[ "Get", "back", "an", "array", "of", "timecodes", "for", "a", "period" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/totp.rb#L75-L80
train
mdp/rotp
lib/rotp/otp.rb
ROTP.OTP.encode_params
def encode_params(uri, params) params_str = String.new('?') params.each do |k, v| params_str << "#{k}=#{CGI.escape(v.to_s)}&" if v end params_str.chop! uri + params_str end
ruby
def encode_params(uri, params) params_str = String.new('?') params.each do |k, v| params_str << "#{k}=#{CGI.escape(v.to_s)}&" if v end params_str.chop! uri + params_str end
[ "def", "encode_params", "(", "uri", ",", "params", ")", "params_str", "=", "String", ".", "new", "(", "'?'", ")", "params", ".", "each", "do", "|", "k", ",", "v", "|", "params_str", "<<", "\"#{k}=#{CGI.escape(v.to_s)}&\"", "if", "v", "end", "params_str", ".", "chop!", "uri", "+", "params_str", "end" ]
A very simple param encoder
[ "A", "very", "simple", "param", "encoder" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/otp.rb#L70-L77
train
mdp/rotp
lib/rotp/otp.rb
ROTP.OTP.time_constant_compare
def time_constant_compare(a, b) return false if a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end
ruby
def time_constant_compare(a, b) return false if a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end
[ "def", "time_constant_compare", "(", "a", ",", "b", ")", "return", "false", "if", "a", ".", "empty?", "||", "b", ".", "empty?", "||", "a", ".", "bytesize", "!=", "b", ".", "bytesize", "l", "=", "a", ".", "unpack", "\"C#{a.bytesize}\"", "res", "=", "0", "b", ".", "each_byte", "{", "|", "byte", "|", "res", "|=", "byte", "^", "l", ".", "shift", "}", "res", "==", "0", "end" ]
constant-time compare the strings
[ "constant", "-", "time", "compare", "the", "strings" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/otp.rb#L80-L87
train
mdp/rotp
lib/rotp/hotp.rb
ROTP.HOTP.verify
def verify(otp, counter, retries: 0) counters = (counter..counter + retries).to_a counters.find do |c| super(otp, at(c)) end end
ruby
def verify(otp, counter, retries: 0) counters = (counter..counter + retries).to_a counters.find do |c| super(otp, at(c)) end end
[ "def", "verify", "(", "otp", ",", "counter", ",", "retries", ":", "0", ")", "counters", "=", "(", "counter", "..", "counter", "+", "retries", ")", ".", "to_a", "counters", ".", "find", "do", "|", "c", "|", "super", "(", "otp", ",", "at", "(", "c", ")", ")", "end", "end" ]
Verifies the OTP passed in against the current time OTP @param otp [String/Integer] the OTP to check against @param counter [Integer] the counter of the OTP @param retries [Integer] number of counters to incrementally retry
[ "Verifies", "the", "OTP", "passed", "in", "against", "the", "current", "time", "OTP" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/hotp.rb#L14-L19
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.ec2_metadata
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform::EC2 unless @ec2_metadata # See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html open('http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/instance-identity/document') do |f| contents = f.read @ec2_metadata = JSON.parse(contents) end end @ec2_metadata end
ruby
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform::EC2 unless @ec2_metadata # See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html open('http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/instance-identity/document') do |f| contents = f.read @ec2_metadata = JSON.parse(contents) end end @ec2_metadata end
[ "def", "ec2_metadata", "raise", "\"Called ec2_metadata with platform=#{@platform}\"", "unless", "@platform", "==", "Platform", "::", "EC2", "unless", "@ec2_metadata", "# See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html", "open", "(", "'http://'", "+", "METADATA_SERVICE_ADDR", "+", "'/latest/dynamic/instance-identity/document'", ")", "do", "|", "f", "|", "contents", "=", "f", ".", "read", "@ec2_metadata", "=", "JSON", ".", "parse", "(", "contents", ")", "end", "end", "@ec2_metadata", "end" ]
EC2 Metadata server returns everything in one call. Store it after the first fetch to avoid making multiple calls.
[ "EC2", "Metadata", "server", "returns", "everything", "in", "one", "call", ".", "Store", "it", "after", "the", "first", "fetch", "to", "avoid", "making", "multiple", "calls", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1081-L1094
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_required_metadata_variables
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location # All metadata parameters must now be set. missing = [] missing << 'project_id' unless @project_id if @platform != Platform::OTHER missing << 'zone' unless @zone missing << 'vm_id' unless @vm_id end return if missing.empty? raise Fluent::ConfigError, "Unable to obtain metadata parameters: #{missing.join(' ')}" end
ruby
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location # All metadata parameters must now be set. missing = [] missing << 'project_id' unless @project_id if @platform != Platform::OTHER missing << 'zone' unless @zone missing << 'vm_id' unless @vm_id end return if missing.empty? raise Fluent::ConfigError, "Unable to obtain metadata parameters: #{missing.join(' ')}" end
[ "def", "set_required_metadata_variables", "set_project_id", "set_vm_id", "set_vm_name", "set_location", "# All metadata parameters must now be set.", "missing", "=", "[", "]", "missing", "<<", "'project_id'", "unless", "@project_id", "if", "@platform", "!=", "Platform", "::", "OTHER", "missing", "<<", "'zone'", "unless", "@zone", "missing", "<<", "'vm_id'", "unless", "@vm_id", "end", "return", "if", "missing", ".", "empty?", "raise", "Fluent", "::", "ConfigError", ",", "\"Unable to obtain metadata parameters: #{missing.join(' ')}\"", "end" ]
Set required variables like @project_id, @vm_id, @vm_name and @zone.
[ "Set", "required", "variables", "like" ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1114-L1130
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_vm_id
def set_vm_id @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2 rescue StandardError => e @log.error 'Failed to obtain vm_id: ', error: e end
ruby
def set_vm_id @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2 rescue StandardError => e @log.error 'Failed to obtain vm_id: ', error: e end
[ "def", "set_vm_id", "@vm_id", "||=", "fetch_gce_metadata", "(", "'instance/id'", ")", "if", "@platform", "==", "Platform", "::", "GCE", "@vm_id", "||=", "ec2_metadata", "[", "'instanceId'", "]", "if", "@platform", "==", "Platform", "::", "EC2", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to obtain vm_id: '", ",", "error", ":", "e", "end" ]
1. Return the value if it is explicitly set in the config already. 2. If not, try to retrieve it by calling metadata servers directly.
[ "1", ".", "Return", "the", "value", "if", "it", "is", "explicitly", "set", "in", "the", "config", "already", ".", "2", ".", "If", "not", "try", "to", "retrieve", "it", "by", "calling", "metadata", "servers", "directly", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1143-L1148
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_location
def set_location # Response format: "projects/<number>/zones/<zone>" @zone ||= fetch_gce_metadata('instance/zone').rpartition('/')[2] if @platform == Platform::GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else 'region' end @zone ||= 'aws:' + ec2_metadata[aws_location_key] if @platform == Platform::EC2 && ec2_metadata.key?(aws_location_key) rescue StandardError => e @log.error 'Failed to obtain location: ', error: e end
ruby
def set_location # Response format: "projects/<number>/zones/<zone>" @zone ||= fetch_gce_metadata('instance/zone').rpartition('/')[2] if @platform == Platform::GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else 'region' end @zone ||= 'aws:' + ec2_metadata[aws_location_key] if @platform == Platform::EC2 && ec2_metadata.key?(aws_location_key) rescue StandardError => e @log.error 'Failed to obtain location: ', error: e end
[ "def", "set_location", "# Response format: \"projects/<number>/zones/<zone>\"", "@zone", "||=", "fetch_gce_metadata", "(", "'instance/zone'", ")", ".", "rpartition", "(", "'/'", ")", "[", "2", "]", "if", "@platform", "==", "Platform", "::", "GCE", "aws_location_key", "=", "if", "@use_aws_availability_zone", "'availabilityZone'", "else", "'region'", "end", "@zone", "||=", "'aws:'", "+", "ec2_metadata", "[", "aws_location_key", "]", "if", "@platform", "==", "Platform", "::", "EC2", "&&", "ec2_metadata", ".", "key?", "(", "aws_location_key", ")", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to obtain location: '", ",", "error", ":", "e", "end" ]
1. Return the value if it is explicitly set in the config already. 2. If not, try to retrieve it locally.
[ "1", ".", "Return", "the", "value", "if", "it", "is", "explicitly", "set", "in", "the", "config", "already", ".", "2", ".", "If", "not", "try", "to", "retrieve", "it", "locally", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1160-L1173
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_via_legacy
def determine_agent_level_monitored_resource_via_legacy resource = Google::Apis::LoggingV2::MonitoredResource.new( labels: {}) resource.type = determine_agent_level_monitored_resource_type resource.labels = determine_agent_level_monitored_resource_labels( resource.type) resource end
ruby
def determine_agent_level_monitored_resource_via_legacy resource = Google::Apis::LoggingV2::MonitoredResource.new( labels: {}) resource.type = determine_agent_level_monitored_resource_type resource.labels = determine_agent_level_monitored_resource_labels( resource.type) resource end
[ "def", "determine_agent_level_monitored_resource_via_legacy", "resource", "=", "Google", "::", "Apis", "::", "LoggingV2", "::", "MonitoredResource", ".", "new", "(", "labels", ":", "{", "}", ")", "resource", ".", "type", "=", "determine_agent_level_monitored_resource_type", "resource", ".", "labels", "=", "determine_agent_level_monitored_resource_labels", "(", "resource", ".", "type", ")", "resource", "end" ]
Retrieve monitored resource via the legacy way. Note: This is just a failover plan if we fail to get metadata from Metadata Agent. Thus it should be equivalent to what Metadata Agent returns.
[ "Retrieve", "monitored", "resource", "via", "the", "legacy", "way", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1180-L1187
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_type
def determine_agent_level_monitored_resource_type case @platform when Platform::OTHER # Unknown platform will be defaulted to GCE instance. return COMPUTE_CONSTANTS[:resource_type] when Platform::EC2 return EC2_CONSTANTS[:resource_type] when Platform::GCE # Resource types determined by @subservice_name config. return SUBSERVICE_MAP[@subservice_name] if @subservice_name # Resource types determined by @detect_subservice config. if @detect_subservice begin attributes = fetch_gce_metadata('instance/attributes/').split.to_set SUBSERVICE_METADATA_ATTRIBUTES.each do |resource_type, expected| return resource_type if attributes.superset?(expected) end rescue StandardError => e @log.error 'Failed to detect subservice: ', error: e end end # GCE instance. return COMPUTE_CONSTANTS[:resource_type] end end
ruby
def determine_agent_level_monitored_resource_type case @platform when Platform::OTHER # Unknown platform will be defaulted to GCE instance. return COMPUTE_CONSTANTS[:resource_type] when Platform::EC2 return EC2_CONSTANTS[:resource_type] when Platform::GCE # Resource types determined by @subservice_name config. return SUBSERVICE_MAP[@subservice_name] if @subservice_name # Resource types determined by @detect_subservice config. if @detect_subservice begin attributes = fetch_gce_metadata('instance/attributes/').split.to_set SUBSERVICE_METADATA_ATTRIBUTES.each do |resource_type, expected| return resource_type if attributes.superset?(expected) end rescue StandardError => e @log.error 'Failed to detect subservice: ', error: e end end # GCE instance. return COMPUTE_CONSTANTS[:resource_type] end end
[ "def", "determine_agent_level_monitored_resource_type", "case", "@platform", "when", "Platform", "::", "OTHER", "# Unknown platform will be defaulted to GCE instance.", "return", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "when", "Platform", "::", "EC2", "return", "EC2_CONSTANTS", "[", ":resource_type", "]", "when", "Platform", "::", "GCE", "# Resource types determined by @subservice_name config.", "return", "SUBSERVICE_MAP", "[", "@subservice_name", "]", "if", "@subservice_name", "# Resource types determined by @detect_subservice config.", "if", "@detect_subservice", "begin", "attributes", "=", "fetch_gce_metadata", "(", "'instance/attributes/'", ")", ".", "split", ".", "to_set", "SUBSERVICE_METADATA_ATTRIBUTES", ".", "each", "do", "|", "resource_type", ",", "expected", "|", "return", "resource_type", "if", "attributes", ".", "superset?", "(", "expected", ")", "end", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to detect subservice: '", ",", "error", ":", "e", "end", "end", "# GCE instance.", "return", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "end", "end" ]
Determine agent level monitored resource type.
[ "Determine", "agent", "level", "monitored", "resource", "type", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1190-L1218
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_labels
def determine_agent_level_monitored_resource_labels(type) case type # GAE app. when APPENGINE_CONSTANTS[:resource_type] return { 'module_id' => fetch_gce_metadata('instance/attributes/gae_backend_name'), 'version_id' => fetch_gce_metadata('instance/attributes/gae_backend_version') } # GCE. when COMPUTE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone } # GKE container. when GKE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone, 'cluster_name' => fetch_gce_metadata('instance/attributes/cluster-name') } # Cloud Dataproc. when DATAPROC_CONSTANTS[:resource_type] return { 'cluster_uuid' => fetch_gce_metadata('instance/attributes/dataproc-cluster-uuid'), 'cluster_name' => fetch_gce_metadata('instance/attributes/dataproc-cluster-name'), 'region' => fetch_gce_metadata('instance/attributes/dataproc-region') } # EC2. when EC2_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone labels = { 'instance_id' => @vm_id, 'region' => @zone } labels['aws_account'] = ec2_metadata['accountId'] if ec2_metadata.key?('accountId') return labels end {} rescue StandardError => e @log.error "Failed to set monitored resource labels for #{type}: ", error: e {} end
ruby
def determine_agent_level_monitored_resource_labels(type) case type # GAE app. when APPENGINE_CONSTANTS[:resource_type] return { 'module_id' => fetch_gce_metadata('instance/attributes/gae_backend_name'), 'version_id' => fetch_gce_metadata('instance/attributes/gae_backend_version') } # GCE. when COMPUTE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone } # GKE container. when GKE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone, 'cluster_name' => fetch_gce_metadata('instance/attributes/cluster-name') } # Cloud Dataproc. when DATAPROC_CONSTANTS[:resource_type] return { 'cluster_uuid' => fetch_gce_metadata('instance/attributes/dataproc-cluster-uuid'), 'cluster_name' => fetch_gce_metadata('instance/attributes/dataproc-cluster-name'), 'region' => fetch_gce_metadata('instance/attributes/dataproc-region') } # EC2. when EC2_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone labels = { 'instance_id' => @vm_id, 'region' => @zone } labels['aws_account'] = ec2_metadata['accountId'] if ec2_metadata.key?('accountId') return labels end {} rescue StandardError => e @log.error "Failed to set monitored resource labels for #{type}: ", error: e {} end
[ "def", "determine_agent_level_monitored_resource_labels", "(", "type", ")", "case", "type", "# GAE app.", "when", "APPENGINE_CONSTANTS", "[", ":resource_type", "]", "return", "{", "'module_id'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/gae_backend_name'", ")", ",", "'version_id'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/gae_backend_version'", ")", "}", "# GCE.", "when", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "raise", "\"Cannot construct a #{type} resource without vm_id and zone\"", "unless", "@vm_id", "&&", "@zone", "return", "{", "'instance_id'", "=>", "@vm_id", ",", "'zone'", "=>", "@zone", "}", "# GKE container.", "when", "GKE_CONSTANTS", "[", ":resource_type", "]", "raise", "\"Cannot construct a #{type} resource without vm_id and zone\"", "unless", "@vm_id", "&&", "@zone", "return", "{", "'instance_id'", "=>", "@vm_id", ",", "'zone'", "=>", "@zone", ",", "'cluster_name'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/cluster-name'", ")", "}", "# Cloud Dataproc.", "when", "DATAPROC_CONSTANTS", "[", ":resource_type", "]", "return", "{", "'cluster_uuid'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/dataproc-cluster-uuid'", ")", ",", "'cluster_name'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/dataproc-cluster-name'", ")", ",", "'region'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/dataproc-region'", ")", "}", "# EC2.", "when", "EC2_CONSTANTS", "[", ":resource_type", "]", "raise", "\"Cannot construct a #{type} resource without vm_id and zone\"", "unless", "@vm_id", "&&", "@zone", "labels", "=", "{", "'instance_id'", "=>", "@vm_id", ",", "'region'", "=>", "@zone", "}", "labels", "[", "'aws_account'", "]", "=", "ec2_metadata", "[", "'accountId'", "]", "if", "ec2_metadata", ".", "key?", "(", "'accountId'", ")", "return", "labels", "end", "{", "}", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "\"Failed to set monitored resource labels for #{type}: \"", ",", "error", ":", "e", "{", "}", "end" ]
Determine agent level monitored resource labels based on the resource type. Each resource type has its own labels that need to be filled in.
[ "Determine", "agent", "level", "monitored", "resource", "labels", "based", "on", "the", "resource", "type", ".", "Each", "resource", "type", "has", "its", "own", "labels", "that", "need", "to", "be", "filled", "in", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1222-L1282
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_common_labels
def determine_agent_level_common_labels labels = {} # User can specify labels via config. We want to capture those as well. labels.merge!(@labels) if @labels case @resource.type # GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML. when APPENGINE_CONSTANTS[:resource_type], DATAFLOW_CONSTANTS[:resource_type], DATAPROC_CONSTANTS[:resource_type], ML_CONSTANTS[:resource_type] labels.merge!( "#{COMPUTE_CONSTANTS[:service]}/resource_id" => @vm_id, "#{COMPUTE_CONSTANTS[:service]}/resource_name" => @vm_name, "#{COMPUTE_CONSTANTS[:service]}/zone" => @zone ) # GCE instance and GKE container. when COMPUTE_CONSTANTS[:resource_type], GKE_CONSTANTS[:resource_type] labels["#{COMPUTE_CONSTANTS[:service]}/resource_name"] = @vm_name # EC2. when EC2_CONSTANTS[:resource_type] labels["#{EC2_CONSTANTS[:service]}/resource_name"] = @vm_name end labels end
ruby
def determine_agent_level_common_labels labels = {} # User can specify labels via config. We want to capture those as well. labels.merge!(@labels) if @labels case @resource.type # GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML. when APPENGINE_CONSTANTS[:resource_type], DATAFLOW_CONSTANTS[:resource_type], DATAPROC_CONSTANTS[:resource_type], ML_CONSTANTS[:resource_type] labels.merge!( "#{COMPUTE_CONSTANTS[:service]}/resource_id" => @vm_id, "#{COMPUTE_CONSTANTS[:service]}/resource_name" => @vm_name, "#{COMPUTE_CONSTANTS[:service]}/zone" => @zone ) # GCE instance and GKE container. when COMPUTE_CONSTANTS[:resource_type], GKE_CONSTANTS[:resource_type] labels["#{COMPUTE_CONSTANTS[:service]}/resource_name"] = @vm_name # EC2. when EC2_CONSTANTS[:resource_type] labels["#{EC2_CONSTANTS[:service]}/resource_name"] = @vm_name end labels end
[ "def", "determine_agent_level_common_labels", "labels", "=", "{", "}", "# User can specify labels via config. We want to capture those as well.", "labels", ".", "merge!", "(", "@labels", ")", "if", "@labels", "case", "@resource", ".", "type", "# GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML.", "when", "APPENGINE_CONSTANTS", "[", ":resource_type", "]", ",", "DATAFLOW_CONSTANTS", "[", ":resource_type", "]", ",", "DATAPROC_CONSTANTS", "[", ":resource_type", "]", ",", "ML_CONSTANTS", "[", ":resource_type", "]", "labels", ".", "merge!", "(", "\"#{COMPUTE_CONSTANTS[:service]}/resource_id\"", "=>", "@vm_id", ",", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", "=>", "@vm_name", ",", "\"#{COMPUTE_CONSTANTS[:service]}/zone\"", "=>", "@zone", ")", "# GCE instance and GKE container.", "when", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", ",", "GKE_CONSTANTS", "[", ":resource_type", "]", "labels", "[", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", "]", "=", "@vm_name", "# EC2.", "when", "EC2_CONSTANTS", "[", ":resource_type", "]", "labels", "[", "\"#{EC2_CONSTANTS[:service]}/resource_name\"", "]", "=", "@vm_name", "end", "labels", "end" ]
Determine the common labels that should be added to all log entries processed by this logging agent.
[ "Determine", "the", "common", "labels", "that", "should", "be", "added", "to", "all", "log", "entries", "processed", "by", "this", "logging", "agent", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1286-L1313
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.group_log_entries_by_tag_and_local_resource_id
def group_log_entries_by_tag_and_local_resource_id(chunk) groups = {} chunk.msgpack_each do |tag, time, record| unless record.is_a?(Hash) @log.warn 'Dropping log entries with malformed record: ' \ "'#{record.inspect}'. " \ 'A log record should be in JSON format.' next end sanitized_tag = sanitize_tag(tag) if sanitized_tag.nil? @log.warn "Dropping log entries with invalid tag: '#{tag.inspect}'." \ ' A tag should be a string with utf8 characters.' next end local_resource_id = record.delete(LOCAL_RESOURCE_ID_KEY) # A nil local_resource_id means "fall back to legacy". hash_key = [sanitized_tag, local_resource_id].freeze groups[hash_key] ||= [] groups[hash_key].push([time, record]) end groups end
ruby
def group_log_entries_by_tag_and_local_resource_id(chunk) groups = {} chunk.msgpack_each do |tag, time, record| unless record.is_a?(Hash) @log.warn 'Dropping log entries with malformed record: ' \ "'#{record.inspect}'. " \ 'A log record should be in JSON format.' next end sanitized_tag = sanitize_tag(tag) if sanitized_tag.nil? @log.warn "Dropping log entries with invalid tag: '#{tag.inspect}'." \ ' A tag should be a string with utf8 characters.' next end local_resource_id = record.delete(LOCAL_RESOURCE_ID_KEY) # A nil local_resource_id means "fall back to legacy". hash_key = [sanitized_tag, local_resource_id].freeze groups[hash_key] ||= [] groups[hash_key].push([time, record]) end groups end
[ "def", "group_log_entries_by_tag_and_local_resource_id", "(", "chunk", ")", "groups", "=", "{", "}", "chunk", ".", "msgpack_each", "do", "|", "tag", ",", "time", ",", "record", "|", "unless", "record", ".", "is_a?", "(", "Hash", ")", "@log", ".", "warn", "'Dropping log entries with malformed record: '", "\"'#{record.inspect}'. \"", "'A log record should be in JSON format.'", "next", "end", "sanitized_tag", "=", "sanitize_tag", "(", "tag", ")", "if", "sanitized_tag", ".", "nil?", "@log", ".", "warn", "\"Dropping log entries with invalid tag: '#{tag.inspect}'.\"", "' A tag should be a string with utf8 characters.'", "next", "end", "local_resource_id", "=", "record", ".", "delete", "(", "LOCAL_RESOURCE_ID_KEY", ")", "# A nil local_resource_id means \"fall back to legacy\".", "hash_key", "=", "[", "sanitized_tag", ",", "local_resource_id", "]", ".", "freeze", "groups", "[", "hash_key", "]", "||=", "[", "]", "groups", "[", "hash_key", "]", ".", "push", "(", "[", "time", ",", "record", "]", ")", "end", "groups", "end" ]
Group the log entries by tag and local_resource_id pairs. Also filter out invalid non-Hash entries.
[ "Group", "the", "log", "entries", "by", "tag", "and", "local_resource_id", "pairs", ".", "Also", "filter", "out", "invalid", "non", "-", "Hash", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1317-L1339
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_group_level_monitored_resource_and_labels
def determine_group_level_monitored_resource_and_labels(tag, local_resource_id) resource = @resource.dup resource.labels = @resource.labels.dup common_labels = @common_labels.dup # Change the resource type and set matched_regexp_group if the tag matches # certain regexp. matched_regexp_group = nil # @tag_regexp_list can be an empty list. @tag_regexp_list.each do |derived_type, tag_regexp| matched_regexp_group = tag_regexp.match(tag) if matched_regexp_group resource.type = derived_type break end end # Determine the monitored resource based on the local_resource_id. # Different monitored resource types have unique ids in different format. # We will query Metadata Agent for the monitored resource. Return the # legacy monitored resource (either the instance resource or the resource # inferred from the tag) if failed to get a monitored resource from # Metadata Agent with this key. # # Examples: # "container.<container_id>" // Docker container. # "k8s_pod.<namespace_name>.<pod_name>" // GKE pod. if local_resource_id converted_resource = monitored_resource_from_local_resource_id( local_resource_id) resource = converted_resource if converted_resource end # Once the resource type is settled down, determine the labels. case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] resource.labels.merge!( 'region' => @gcf_region, 'function_name' => decode_cloudfunctions_function_name( matched_regexp_group['encoded_function_name']) ) instance_id = resource.labels.delete('instance_id') common_labels.merge!( "#{GKE_CONSTANTS[:service]}/instance_id" => instance_id, "#{COMPUTE_CONSTANTS[:service]}/resource_id" => instance_id, "#{GKE_CONSTANTS[:service]}/cluster_name" => resource.labels.delete('cluster_name'), "#{COMPUTE_CONSTANTS[:service]}/zone" => resource.labels.delete('zone') ) # GKE container. when GKE_CONSTANTS[:resource_type] if matched_regexp_group # We only expect one occurrence of each key in the match group. resource_labels_candidates = matched_regexp_group.names.zip(matched_regexp_group.captures).to_h common_labels_candidates = resource_labels_candidates.dup resource.labels.merge!( delete_and_extract_labels( resource_labels_candidates, # The kubernetes_tag_regexp is poorly named. 'namespace_name' is # in fact 'namespace_id'. 'pod_name' is in fact 'pod_id'. # TODO(qingling128): Figure out how to put this map into # constants like GKE_CONSTANTS[:extra_resource_labels]. 'container_name' => 'container_name', 'namespace_name' => 'namespace_id', 'pod_name' => 'pod_id')) common_labels.merge!( delete_and_extract_labels( common_labels_candidates, GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) end # Docker container. # TODO(qingling128): Remove this logic once the resource is retrieved at a # proper time (b/65175256). when DOCKER_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") # TODO(qingling128): Temporary fallback for metadata agent restarts. # K8s resources. when K8S_CONTAINER_CONSTANTS[:resource_type], K8S_POD_CONSTANTS[:resource_type], K8S_NODE_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") end # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' option. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end resource.freeze resource.labels.freeze common_labels.freeze [resource, common_labels] end
ruby
def determine_group_level_monitored_resource_and_labels(tag, local_resource_id) resource = @resource.dup resource.labels = @resource.labels.dup common_labels = @common_labels.dup # Change the resource type and set matched_regexp_group if the tag matches # certain regexp. matched_regexp_group = nil # @tag_regexp_list can be an empty list. @tag_regexp_list.each do |derived_type, tag_regexp| matched_regexp_group = tag_regexp.match(tag) if matched_regexp_group resource.type = derived_type break end end # Determine the monitored resource based on the local_resource_id. # Different monitored resource types have unique ids in different format. # We will query Metadata Agent for the monitored resource. Return the # legacy monitored resource (either the instance resource or the resource # inferred from the tag) if failed to get a monitored resource from # Metadata Agent with this key. # # Examples: # "container.<container_id>" // Docker container. # "k8s_pod.<namespace_name>.<pod_name>" // GKE pod. if local_resource_id converted_resource = monitored_resource_from_local_resource_id( local_resource_id) resource = converted_resource if converted_resource end # Once the resource type is settled down, determine the labels. case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] resource.labels.merge!( 'region' => @gcf_region, 'function_name' => decode_cloudfunctions_function_name( matched_regexp_group['encoded_function_name']) ) instance_id = resource.labels.delete('instance_id') common_labels.merge!( "#{GKE_CONSTANTS[:service]}/instance_id" => instance_id, "#{COMPUTE_CONSTANTS[:service]}/resource_id" => instance_id, "#{GKE_CONSTANTS[:service]}/cluster_name" => resource.labels.delete('cluster_name'), "#{COMPUTE_CONSTANTS[:service]}/zone" => resource.labels.delete('zone') ) # GKE container. when GKE_CONSTANTS[:resource_type] if matched_regexp_group # We only expect one occurrence of each key in the match group. resource_labels_candidates = matched_regexp_group.names.zip(matched_regexp_group.captures).to_h common_labels_candidates = resource_labels_candidates.dup resource.labels.merge!( delete_and_extract_labels( resource_labels_candidates, # The kubernetes_tag_regexp is poorly named. 'namespace_name' is # in fact 'namespace_id'. 'pod_name' is in fact 'pod_id'. # TODO(qingling128): Figure out how to put this map into # constants like GKE_CONSTANTS[:extra_resource_labels]. 'container_name' => 'container_name', 'namespace_name' => 'namespace_id', 'pod_name' => 'pod_id')) common_labels.merge!( delete_and_extract_labels( common_labels_candidates, GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) end # Docker container. # TODO(qingling128): Remove this logic once the resource is retrieved at a # proper time (b/65175256). when DOCKER_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") # TODO(qingling128): Temporary fallback for metadata agent restarts. # K8s resources. when K8S_CONTAINER_CONSTANTS[:resource_type], K8S_POD_CONSTANTS[:resource_type], K8S_NODE_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") end # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' option. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end resource.freeze resource.labels.freeze common_labels.freeze [resource, common_labels] end
[ "def", "determine_group_level_monitored_resource_and_labels", "(", "tag", ",", "local_resource_id", ")", "resource", "=", "@resource", ".", "dup", "resource", ".", "labels", "=", "@resource", ".", "labels", ".", "dup", "common_labels", "=", "@common_labels", ".", "dup", "# Change the resource type and set matched_regexp_group if the tag matches", "# certain regexp.", "matched_regexp_group", "=", "nil", "# @tag_regexp_list can be an empty list.", "@tag_regexp_list", ".", "each", "do", "|", "derived_type", ",", "tag_regexp", "|", "matched_regexp_group", "=", "tag_regexp", ".", "match", "(", "tag", ")", "if", "matched_regexp_group", "resource", ".", "type", "=", "derived_type", "break", "end", "end", "# Determine the monitored resource based on the local_resource_id.", "# Different monitored resource types have unique ids in different format.", "# We will query Metadata Agent for the monitored resource. Return the", "# legacy monitored resource (either the instance resource or the resource", "# inferred from the tag) if failed to get a monitored resource from", "# Metadata Agent with this key.", "#", "# Examples:", "# \"container.<container_id>\" // Docker container.", "# \"k8s_pod.<namespace_name>.<pod_name>\" // GKE pod.", "if", "local_resource_id", "converted_resource", "=", "monitored_resource_from_local_resource_id", "(", "local_resource_id", ")", "resource", "=", "converted_resource", "if", "converted_resource", "end", "# Once the resource type is settled down, determine the labels.", "case", "resource", ".", "type", "# Cloud Functions.", "when", "CLOUDFUNCTIONS_CONSTANTS", "[", ":resource_type", "]", "resource", ".", "labels", ".", "merge!", "(", "'region'", "=>", "@gcf_region", ",", "'function_name'", "=>", "decode_cloudfunctions_function_name", "(", "matched_regexp_group", "[", "'encoded_function_name'", "]", ")", ")", "instance_id", "=", "resource", ".", "labels", ".", "delete", "(", "'instance_id'", ")", "common_labels", ".", "merge!", "(", "\"#{GKE_CONSTANTS[:service]}/instance_id\"", "=>", "instance_id", ",", "\"#{COMPUTE_CONSTANTS[:service]}/resource_id\"", "=>", "instance_id", ",", "\"#{GKE_CONSTANTS[:service]}/cluster_name\"", "=>", "resource", ".", "labels", ".", "delete", "(", "'cluster_name'", ")", ",", "\"#{COMPUTE_CONSTANTS[:service]}/zone\"", "=>", "resource", ".", "labels", ".", "delete", "(", "'zone'", ")", ")", "# GKE container.", "when", "GKE_CONSTANTS", "[", ":resource_type", "]", "if", "matched_regexp_group", "# We only expect one occurrence of each key in the match group.", "resource_labels_candidates", "=", "matched_regexp_group", ".", "names", ".", "zip", "(", "matched_regexp_group", ".", "captures", ")", ".", "to_h", "common_labels_candidates", "=", "resource_labels_candidates", ".", "dup", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "resource_labels_candidates", ",", "# The kubernetes_tag_regexp is poorly named. 'namespace_name' is", "# in fact 'namespace_id'. 'pod_name' is in fact 'pod_id'.", "# TODO(qingling128): Figure out how to put this map into", "# constants like GKE_CONSTANTS[:extra_resource_labels].", "'container_name'", "=>", "'container_name'", ",", "'namespace_name'", "=>", "'namespace_id'", ",", "'pod_name'", "=>", "'pod_id'", ")", ")", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "common_labels_candidates", ",", "GKE_CONSTANTS", "[", ":extra_common_labels", "]", ".", "map", "{", "|", "l", "|", "[", "l", ",", "\"#{GKE_CONSTANTS[:service]}/#{l}\"", "]", "}", ".", "to_h", ")", ")", "end", "# Docker container.", "# TODO(qingling128): Remove this logic once the resource is retrieved at a", "# proper time (b/65175256).", "when", "DOCKER_CONSTANTS", "[", ":resource_type", "]", "common_labels", ".", "delete", "(", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", ")", "# TODO(qingling128): Temporary fallback for metadata agent restarts.", "# K8s resources.", "when", "K8S_CONTAINER_CONSTANTS", "[", ":resource_type", "]", ",", "K8S_POD_CONSTANTS", "[", ":resource_type", "]", ",", "K8S_NODE_CONSTANTS", "[", ":resource_type", "]", "common_labels", ".", "delete", "(", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", ")", "end", "# Cloud Dataflow and Cloud ML.", "# These labels can be set via the 'labels' option.", "# Report them as monitored resource labels instead of common labels.", "# e.g. \"dataflow.googleapis.com/job_id\" => \"job_id\"", "[", "DATAFLOW_CONSTANTS", ",", "ML_CONSTANTS", "]", ".", "each", "do", "|", "service_constants", "|", "next", "unless", "resource", ".", "type", "==", "service_constants", "[", ":resource_type", "]", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "common_labels", ",", "service_constants", "[", ":extra_resource_labels", "]", ".", "map", "{", "|", "l", "|", "[", "\"#{service_constants[:service]}/#{l}\"", ",", "l", "]", "}", ".", "to_h", ")", ")", "end", "resource", ".", "freeze", "resource", ".", "labels", ".", "freeze", "common_labels", ".", "freeze", "[", "resource", ",", "common_labels", "]", "end" ]
Determine the group level monitored resource and common labels shared by a collection of entries.
[ "Determine", "the", "group", "level", "monitored", "resource", "and", "common", "labels", "shared", "by", "a", "collection", "of", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1343-L1452
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.monitored_resource_from_local_resource_id
def monitored_resource_from_local_resource_id(local_resource_id) return unless local_resource_id if @enable_metadata_agent @log.debug 'Calling metadata agent with local_resource_id: ' \ "#{local_resource_id}." resource = query_metadata_agent_for_monitored_resource( local_resource_id) @log.debug 'Retrieved monitored resource from metadata agent: ' \ "#{resource.inspect}." if resource # TODO(qingling128): Fix this temporary renaming from 'gke_container' # to 'container'. resource.type = 'container' if resource.type == 'gke_container' return resource end end # Fall back to constructing monitored resource locally. # TODO(qingling128): This entire else clause is temporary until we # implement buffering and caching. @log.debug('Failed to retrieve monitored resource from Metadata' \ " Agent with local_resource_id #{local_resource_id}.") construct_k8s_resource_locally(local_resource_id) end
ruby
def monitored_resource_from_local_resource_id(local_resource_id) return unless local_resource_id if @enable_metadata_agent @log.debug 'Calling metadata agent with local_resource_id: ' \ "#{local_resource_id}." resource = query_metadata_agent_for_monitored_resource( local_resource_id) @log.debug 'Retrieved monitored resource from metadata agent: ' \ "#{resource.inspect}." if resource # TODO(qingling128): Fix this temporary renaming from 'gke_container' # to 'container'. resource.type = 'container' if resource.type == 'gke_container' return resource end end # Fall back to constructing monitored resource locally. # TODO(qingling128): This entire else clause is temporary until we # implement buffering and caching. @log.debug('Failed to retrieve monitored resource from Metadata' \ " Agent with local_resource_id #{local_resource_id}.") construct_k8s_resource_locally(local_resource_id) end
[ "def", "monitored_resource_from_local_resource_id", "(", "local_resource_id", ")", "return", "unless", "local_resource_id", "if", "@enable_metadata_agent", "@log", ".", "debug", "'Calling metadata agent with local_resource_id: '", "\"#{local_resource_id}.\"", "resource", "=", "query_metadata_agent_for_monitored_resource", "(", "local_resource_id", ")", "@log", ".", "debug", "'Retrieved monitored resource from metadata agent: '", "\"#{resource.inspect}.\"", "if", "resource", "# TODO(qingling128): Fix this temporary renaming from 'gke_container'", "# to 'container'.", "resource", ".", "type", "=", "'container'", "if", "resource", ".", "type", "==", "'gke_container'", "return", "resource", "end", "end", "# Fall back to constructing monitored resource locally.", "# TODO(qingling128): This entire else clause is temporary until we", "# implement buffering and caching.", "@log", ".", "debug", "(", "'Failed to retrieve monitored resource from Metadata'", "\" Agent with local_resource_id #{local_resource_id}.\"", ")", "construct_k8s_resource_locally", "(", "local_resource_id", ")", "end" ]
Take a locally unique resource id and convert it to the globally unique monitored resource.
[ "Take", "a", "locally", "unique", "resource", "id", "and", "convert", "it", "to", "the", "globally", "unique", "monitored", "resource", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1456-L1478
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_entry_level_monitored_resource_and_labels
def determine_entry_level_monitored_resource_and_labels( group_level_resource, group_level_common_labels, record) resource = group_level_resource.dup resource.labels = group_level_resource.labels.dup common_labels = group_level_common_labels.dup case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] if record.key?('log') @cloudfunctions_log_match = @compiled_cloudfunctions_log_regexp.match(record['log']) common_labels['execution_id'] = @cloudfunctions_log_match['execution_id'] if @cloudfunctions_log_match && @cloudfunctions_log_match['execution_id'] end # GKE container. when GKE_CONSTANTS[:resource_type] # Move the stdout/stderr annotation from the record into a label. common_labels.merge!( delete_and_extract_labels( record, 'stream' => "#{GKE_CONSTANTS[:service]}/stream")) # If the record has been annotated by the kubernetes_metadata_filter # plugin, then use that metadata. Otherwise, rely on commonLabels # populated from the group's tag. if record.key?('kubernetes') resource.labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_resource_labels] .map { |l| [l, l] }.to_h)) common_labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) # Prepend label/ to all user-defined labels' keys. if record['kubernetes'].key?('labels') common_labels.merge!( delete_and_extract_labels( record['kubernetes']['labels'], record['kubernetes']['labels'] .map { |key, _| [key, "label/#{key}"] }.to_h)) end # We've explicitly consumed all the fields we care about -- don't # litter the log entries with the remaining fields that the kubernetes # metadata filter plugin includes (or an empty 'kubernetes' field). record.delete('kubernetes') record.delete('docker') end end # If the name of a field in the record is present in the @label_map # configured by users, report its value as a label and do not send that # field as part of the payload. common_labels.merge!(delete_and_extract_labels(record, @label_map)) # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' or 'label_map' options. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end [resource, common_labels] end
ruby
def determine_entry_level_monitored_resource_and_labels( group_level_resource, group_level_common_labels, record) resource = group_level_resource.dup resource.labels = group_level_resource.labels.dup common_labels = group_level_common_labels.dup case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] if record.key?('log') @cloudfunctions_log_match = @compiled_cloudfunctions_log_regexp.match(record['log']) common_labels['execution_id'] = @cloudfunctions_log_match['execution_id'] if @cloudfunctions_log_match && @cloudfunctions_log_match['execution_id'] end # GKE container. when GKE_CONSTANTS[:resource_type] # Move the stdout/stderr annotation from the record into a label. common_labels.merge!( delete_and_extract_labels( record, 'stream' => "#{GKE_CONSTANTS[:service]}/stream")) # If the record has been annotated by the kubernetes_metadata_filter # plugin, then use that metadata. Otherwise, rely on commonLabels # populated from the group's tag. if record.key?('kubernetes') resource.labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_resource_labels] .map { |l| [l, l] }.to_h)) common_labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) # Prepend label/ to all user-defined labels' keys. if record['kubernetes'].key?('labels') common_labels.merge!( delete_and_extract_labels( record['kubernetes']['labels'], record['kubernetes']['labels'] .map { |key, _| [key, "label/#{key}"] }.to_h)) end # We've explicitly consumed all the fields we care about -- don't # litter the log entries with the remaining fields that the kubernetes # metadata filter plugin includes (or an empty 'kubernetes' field). record.delete('kubernetes') record.delete('docker') end end # If the name of a field in the record is present in the @label_map # configured by users, report its value as a label and do not send that # field as part of the payload. common_labels.merge!(delete_and_extract_labels(record, @label_map)) # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' or 'label_map' options. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end [resource, common_labels] end
[ "def", "determine_entry_level_monitored_resource_and_labels", "(", "group_level_resource", ",", "group_level_common_labels", ",", "record", ")", "resource", "=", "group_level_resource", ".", "dup", "resource", ".", "labels", "=", "group_level_resource", ".", "labels", ".", "dup", "common_labels", "=", "group_level_common_labels", ".", "dup", "case", "resource", ".", "type", "# Cloud Functions.", "when", "CLOUDFUNCTIONS_CONSTANTS", "[", ":resource_type", "]", "if", "record", ".", "key?", "(", "'log'", ")", "@cloudfunctions_log_match", "=", "@compiled_cloudfunctions_log_regexp", ".", "match", "(", "record", "[", "'log'", "]", ")", "common_labels", "[", "'execution_id'", "]", "=", "@cloudfunctions_log_match", "[", "'execution_id'", "]", "if", "@cloudfunctions_log_match", "&&", "@cloudfunctions_log_match", "[", "'execution_id'", "]", "end", "# GKE container.", "when", "GKE_CONSTANTS", "[", ":resource_type", "]", "# Move the stdout/stderr annotation from the record into a label.", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", ",", "'stream'", "=>", "\"#{GKE_CONSTANTS[:service]}/stream\"", ")", ")", "# If the record has been annotated by the kubernetes_metadata_filter", "# plugin, then use that metadata. Otherwise, rely on commonLabels", "# populated from the group's tag.", "if", "record", ".", "key?", "(", "'kubernetes'", ")", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", "[", "'kubernetes'", "]", ",", "GKE_CONSTANTS", "[", ":extra_resource_labels", "]", ".", "map", "{", "|", "l", "|", "[", "l", ",", "l", "]", "}", ".", "to_h", ")", ")", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", "[", "'kubernetes'", "]", ",", "GKE_CONSTANTS", "[", ":extra_common_labels", "]", ".", "map", "{", "|", "l", "|", "[", "l", ",", "\"#{GKE_CONSTANTS[:service]}/#{l}\"", "]", "}", ".", "to_h", ")", ")", "# Prepend label/ to all user-defined labels' keys.", "if", "record", "[", "'kubernetes'", "]", ".", "key?", "(", "'labels'", ")", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", "[", "'kubernetes'", "]", "[", "'labels'", "]", ",", "record", "[", "'kubernetes'", "]", "[", "'labels'", "]", ".", "map", "{", "|", "key", ",", "_", "|", "[", "key", ",", "\"label/#{key}\"", "]", "}", ".", "to_h", ")", ")", "end", "# We've explicitly consumed all the fields we care about -- don't", "# litter the log entries with the remaining fields that the kubernetes", "# metadata filter plugin includes (or an empty 'kubernetes' field).", "record", ".", "delete", "(", "'kubernetes'", ")", "record", ".", "delete", "(", "'docker'", ")", "end", "end", "# If the name of a field in the record is present in the @label_map", "# configured by users, report its value as a label and do not send that", "# field as part of the payload.", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", ",", "@label_map", ")", ")", "# Cloud Dataflow and Cloud ML.", "# These labels can be set via the 'labels' or 'label_map' options.", "# Report them as monitored resource labels instead of common labels.", "# e.g. \"dataflow.googleapis.com/job_id\" => \"job_id\"", "[", "DATAFLOW_CONSTANTS", ",", "ML_CONSTANTS", "]", ".", "each", "do", "|", "service_constants", "|", "next", "unless", "resource", ".", "type", "==", "service_constants", "[", ":resource_type", "]", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "common_labels", ",", "service_constants", "[", ":extra_resource_labels", "]", ".", "map", "{", "|", "l", "|", "[", "\"#{service_constants[:service]}/#{l}\"", ",", "l", "]", "}", ".", "to_h", ")", ")", "end", "[", "resource", ",", "common_labels", "]", "end" ]
Extract entry level monitored resource and common labels that should be applied to individual entries.
[ "Extract", "entry", "level", "monitored", "resource", "and", "common", "labels", "that", "should", "be", "applied", "to", "individual", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1482-L1552
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.query_metadata_agent
def query_metadata_agent(path) url = "#{@metadata_agent_url}/#{path}" @log.debug("Calling Metadata Agent: #{url}") open(url) do |f| response = f.read parsed_hash = parse_json_or_nil(response) if parsed_hash.nil? @log.error 'Response from Metadata Agent is not in valid json ' \ "format: '#{response.inspect}'." return nil end @log.debug "Response from Metadata Agent: #{parsed_hash}" return parsed_hash end rescue StandardError => e @log.error "Error calling Metadata Agent at #{url}.", error: e nil end
ruby
def query_metadata_agent(path) url = "#{@metadata_agent_url}/#{path}" @log.debug("Calling Metadata Agent: #{url}") open(url) do |f| response = f.read parsed_hash = parse_json_or_nil(response) if parsed_hash.nil? @log.error 'Response from Metadata Agent is not in valid json ' \ "format: '#{response.inspect}'." return nil end @log.debug "Response from Metadata Agent: #{parsed_hash}" return parsed_hash end rescue StandardError => e @log.error "Error calling Metadata Agent at #{url}.", error: e nil end
[ "def", "query_metadata_agent", "(", "path", ")", "url", "=", "\"#{@metadata_agent_url}/#{path}\"", "@log", ".", "debug", "(", "\"Calling Metadata Agent: #{url}\"", ")", "open", "(", "url", ")", "do", "|", "f", "|", "response", "=", "f", ".", "read", "parsed_hash", "=", "parse_json_or_nil", "(", "response", ")", "if", "parsed_hash", ".", "nil?", "@log", ".", "error", "'Response from Metadata Agent is not in valid json '", "\"format: '#{response.inspect}'.\"", "return", "nil", "end", "@log", ".", "debug", "\"Response from Metadata Agent: #{parsed_hash}\"", "return", "parsed_hash", "end", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "\"Error calling Metadata Agent at #{url}.\"", ",", "error", ":", "e", "nil", "end" ]
Issue a request to the Metadata Agent's local API and parse the response to JSON. Return nil in case of failure.
[ "Issue", "a", "request", "to", "the", "Metadata", "Agent", "s", "local", "API", "and", "parse", "the", "response", "to", "JSON", ".", "Return", "nil", "in", "case", "of", "failure", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1578-L1595
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.parse_labels
def parse_labels(record) payload_labels = record.delete(@labels_key) return nil unless payload_labels unless payload_labels.is_a?(Hash) @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need to be a JSON object." return nil end non_string_keys = payload_labels.each_with_object([]) do |(k, v), a| a << k unless k.is_a?(String) && v.is_a?(String) end unless non_string_keys.empty? @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need string values for all " \ "keys; keys #{non_string_keys} don't." return nil end payload_labels rescue StandardError => err @log.error "Failed to extract '#{@labels_key}' from payload.", err return nil end
ruby
def parse_labels(record) payload_labels = record.delete(@labels_key) return nil unless payload_labels unless payload_labels.is_a?(Hash) @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need to be a JSON object." return nil end non_string_keys = payload_labels.each_with_object([]) do |(k, v), a| a << k unless k.is_a?(String) && v.is_a?(String) end unless non_string_keys.empty? @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need string values for all " \ "keys; keys #{non_string_keys} don't." return nil end payload_labels rescue StandardError => err @log.error "Failed to extract '#{@labels_key}' from payload.", err return nil end
[ "def", "parse_labels", "(", "record", ")", "payload_labels", "=", "record", ".", "delete", "(", "@labels_key", ")", "return", "nil", "unless", "payload_labels", "unless", "payload_labels", ".", "is_a?", "(", "Hash", ")", "@log", ".", "error", "\"Invalid value of '#{@labels_key}' in the payload: \"", "\"#{payload_labels}. Labels need to be a JSON object.\"", "return", "nil", "end", "non_string_keys", "=", "payload_labels", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "(", "k", ",", "v", ")", ",", "a", "|", "a", "<<", "k", "unless", "k", ".", "is_a?", "(", "String", ")", "&&", "v", ".", "is_a?", "(", "String", ")", "end", "unless", "non_string_keys", ".", "empty?", "@log", ".", "error", "\"Invalid value of '#{@labels_key}' in the payload: \"", "\"#{payload_labels}. Labels need string values for all \"", "\"keys; keys #{non_string_keys} don't.\"", "return", "nil", "end", "payload_labels", "rescue", "StandardError", "=>", "err", "@log", ".", "error", "\"Failed to extract '#{@labels_key}' from payload.\"", ",", "err", "return", "nil", "end" ]
Parse labels. Return nil if not set.
[ "Parse", "labels", ".", "Return", "nil", "if", "not", "set", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1797-L1819
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.sanitize_tag
def sanitize_tag(tag) if @require_valid_tags && (!tag.is_a?(String) || tag == '' || convert_to_utf8(tag) != tag) return nil end tag = convert_to_utf8(tag.to_s) tag = '_' if tag == '' tag end
ruby
def sanitize_tag(tag) if @require_valid_tags && (!tag.is_a?(String) || tag == '' || convert_to_utf8(tag) != tag) return nil end tag = convert_to_utf8(tag.to_s) tag = '_' if tag == '' tag end
[ "def", "sanitize_tag", "(", "tag", ")", "if", "@require_valid_tags", "&&", "(", "!", "tag", ".", "is_a?", "(", "String", ")", "||", "tag", "==", "''", "||", "convert_to_utf8", "(", "tag", ")", "!=", "tag", ")", "return", "nil", "end", "tag", "=", "convert_to_utf8", "(", "tag", ".", "to_s", ")", "tag", "=", "'_'", "if", "tag", "==", "''", "tag", "end" ]
Given a tag, returns the corresponding valid tag if possible, or nil if the tag should be rejected. If 'require_valid_tags' is false, non-string tags are converted to strings, and invalid characters are sanitized; otherwise such tags are rejected.
[ "Given", "a", "tag", "returns", "the", "corresponding", "valid", "tag", "if", "possible", "or", "nil", "if", "the", "tag", "should", "be", "rejected", ".", "If", "require_valid_tags", "is", "false", "non", "-", "string", "tags", "are", "converted", "to", "strings", "and", "invalid", "characters", "are", "sanitized", ";", "otherwise", "such", "tags", "are", "rejected", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1976-L1984
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.delete_and_extract_labels
def delete_and_extract_labels(hash, label_map) return {} if label_map.nil? || !label_map.is_a?(Hash) || hash.nil? || !hash.is_a?(Hash) label_map.each_with_object({}) \ do |(original_label, new_label), extracted_labels| value = hash.delete(original_label) extracted_labels[new_label] = convert_to_utf8(value.to_s) if value end end
ruby
def delete_and_extract_labels(hash, label_map) return {} if label_map.nil? || !label_map.is_a?(Hash) || hash.nil? || !hash.is_a?(Hash) label_map.each_with_object({}) \ do |(original_label, new_label), extracted_labels| value = hash.delete(original_label) extracted_labels[new_label] = convert_to_utf8(value.to_s) if value end end
[ "def", "delete_and_extract_labels", "(", "hash", ",", "label_map", ")", "return", "{", "}", "if", "label_map", ".", "nil?", "||", "!", "label_map", ".", "is_a?", "(", "Hash", ")", "||", "hash", ".", "nil?", "||", "!", "hash", ".", "is_a?", "(", "Hash", ")", "label_map", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "original_label", ",", "new_label", ")", ",", "extracted_labels", "|", "value", "=", "hash", ".", "delete", "(", "original_label", ")", "extracted_labels", "[", "new_label", "]", "=", "convert_to_utf8", "(", "value", ".", "to_s", ")", "if", "value", "end", "end" ]
For every original_label => new_label pair in the label_map, delete the original_label from the hash map if it exists, and extract the value to form a map with the new_label as the key.
[ "For", "every", "original_label", "=", ">", "new_label", "pair", "in", "the", "label_map", "delete", "the", "original_label", "from", "the", "hash", "map", "if", "it", "exists", "and", "extract", "the", "value", "to", "form", "a", "map", "with", "the", "new_label", "as", "the", "key", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1989-L1997
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.convert_to_utf8
def convert_to_utf8(input) if @coerce_to_utf8 input.encode( 'utf-8', invalid: :replace, undef: :replace, replace: @non_utf8_replacement_string) else begin input.encode('utf-8') rescue EncodingError @log.error 'Encountered encoding issues potentially due to non ' \ 'UTF-8 characters. To allow non-UTF-8 characters and ' \ 'replace them with spaces, please set "coerce_to_utf8" ' \ 'to true.' raise end end end
ruby
def convert_to_utf8(input) if @coerce_to_utf8 input.encode( 'utf-8', invalid: :replace, undef: :replace, replace: @non_utf8_replacement_string) else begin input.encode('utf-8') rescue EncodingError @log.error 'Encountered encoding issues potentially due to non ' \ 'UTF-8 characters. To allow non-UTF-8 characters and ' \ 'replace them with spaces, please set "coerce_to_utf8" ' \ 'to true.' raise end end end
[ "def", "convert_to_utf8", "(", "input", ")", "if", "@coerce_to_utf8", "input", ".", "encode", "(", "'utf-8'", ",", "invalid", ":", ":replace", ",", "undef", ":", ":replace", ",", "replace", ":", "@non_utf8_replacement_string", ")", "else", "begin", "input", ".", "encode", "(", "'utf-8'", ")", "rescue", "EncodingError", "@log", ".", "error", "'Encountered encoding issues potentially due to non '", "'UTF-8 characters. To allow non-UTF-8 characters and '", "'replace them with spaces, please set \"coerce_to_utf8\" '", "'to true.'", "raise", "end", "end", "end" ]
Encode as UTF-8. If 'coerce_to_utf8' is set to true in the config, any non-UTF-8 character would be replaced by the string specified by 'non_utf8_replacement_string'. If 'coerce_to_utf8' is set to false, any non-UTF-8 character would trigger the plugin to error out.
[ "Encode", "as", "UTF", "-", "8", ".", "If", "coerce_to_utf8", "is", "set", "to", "true", "in", "the", "config", "any", "non", "-", "UTF", "-", "8", "character", "would", "be", "replaced", "by", "the", "string", "specified", "by", "non_utf8_replacement_string", ".", "If", "coerce_to_utf8", "is", "set", "to", "false", "any", "non", "-", "UTF", "-", "8", "character", "would", "trigger", "the", "plugin", "to", "error", "out", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L2162-L2180
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.construct_k8s_resource_locally
def construct_k8s_resource_locally(local_resource_id) return unless /^ (?<resource_type>k8s_container) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+) \.(?<container_name>[0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_pod) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_node) \.(?<node_name>[0-9a-z-]+)$/x =~ local_resource_id # Clear name and location if they're explicitly set to empty. @k8s_cluster_name = nil if @k8s_cluster_name == '' @k8s_cluster_location = nil if @k8s_cluster_location == '' begin @k8s_cluster_name ||= fetch_gce_metadata( 'instance/attributes/cluster-name') @k8s_cluster_location ||= fetch_gce_metadata( 'instance/attributes/cluster-location') rescue StandardError => e @log.error 'Failed to retrieve k8s cluster name and location.', \ error: e end case resource_type when K8S_CONTAINER_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'container_name' => container_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_POD_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_NODE_CONSTANTS[:resource_type] labels = { 'node_name' => node_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = COMPUTE_CONSTANTS[:resource_type] end unless @k8s_cluster_name && @k8s_cluster_location @log.error "Failed to construct #{resource_type} resource locally." \ ' Falling back to writing logs against' \ " #{fallback_resource} resource.", error: e return end constructed_resource = Google::Apis::LoggingV2::MonitoredResource.new( type: resource_type, labels: labels) @log.debug("Constructed #{resource_type} resource locally: " \ "#{constructed_resource.inspect}") constructed_resource end
ruby
def construct_k8s_resource_locally(local_resource_id) return unless /^ (?<resource_type>k8s_container) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+) \.(?<container_name>[0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_pod) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_node) \.(?<node_name>[0-9a-z-]+)$/x =~ local_resource_id # Clear name and location if they're explicitly set to empty. @k8s_cluster_name = nil if @k8s_cluster_name == '' @k8s_cluster_location = nil if @k8s_cluster_location == '' begin @k8s_cluster_name ||= fetch_gce_metadata( 'instance/attributes/cluster-name') @k8s_cluster_location ||= fetch_gce_metadata( 'instance/attributes/cluster-location') rescue StandardError => e @log.error 'Failed to retrieve k8s cluster name and location.', \ error: e end case resource_type when K8S_CONTAINER_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'container_name' => container_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_POD_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_NODE_CONSTANTS[:resource_type] labels = { 'node_name' => node_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = COMPUTE_CONSTANTS[:resource_type] end unless @k8s_cluster_name && @k8s_cluster_location @log.error "Failed to construct #{resource_type} resource locally." \ ' Falling back to writing logs against' \ " #{fallback_resource} resource.", error: e return end constructed_resource = Google::Apis::LoggingV2::MonitoredResource.new( type: resource_type, labels: labels) @log.debug("Constructed #{resource_type} resource locally: " \ "#{constructed_resource.inspect}") constructed_resource end
[ "def", "construct_k8s_resource_locally", "(", "local_resource_id", ")", "return", "unless", "/", "\\.", "\\.", "\\.", "/x", "=~", "local_resource_id", "||", "/", "\\.", "\\.", "/x", "=~", "local_resource_id", "||", "/", "\\.", "/x", "=~", "local_resource_id", "# Clear name and location if they're explicitly set to empty.", "@k8s_cluster_name", "=", "nil", "if", "@k8s_cluster_name", "==", "''", "@k8s_cluster_location", "=", "nil", "if", "@k8s_cluster_location", "==", "''", "begin", "@k8s_cluster_name", "||=", "fetch_gce_metadata", "(", "'instance/attributes/cluster-name'", ")", "@k8s_cluster_location", "||=", "fetch_gce_metadata", "(", "'instance/attributes/cluster-location'", ")", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to retrieve k8s cluster name and location.'", ",", "error", ":", "e", "end", "case", "resource_type", "when", "K8S_CONTAINER_CONSTANTS", "[", ":resource_type", "]", "labels", "=", "{", "'namespace_name'", "=>", "namespace_name", ",", "'pod_name'", "=>", "pod_name", ",", "'container_name'", "=>", "container_name", ",", "'cluster_name'", "=>", "@k8s_cluster_name", ",", "'location'", "=>", "@k8s_cluster_location", "}", "fallback_resource", "=", "GKE_CONSTANTS", "[", ":resource_type", "]", "when", "K8S_POD_CONSTANTS", "[", ":resource_type", "]", "labels", "=", "{", "'namespace_name'", "=>", "namespace_name", ",", "'pod_name'", "=>", "pod_name", ",", "'cluster_name'", "=>", "@k8s_cluster_name", ",", "'location'", "=>", "@k8s_cluster_location", "}", "fallback_resource", "=", "GKE_CONSTANTS", "[", ":resource_type", "]", "when", "K8S_NODE_CONSTANTS", "[", ":resource_type", "]", "labels", "=", "{", "'node_name'", "=>", "node_name", ",", "'cluster_name'", "=>", "@k8s_cluster_name", ",", "'location'", "=>", "@k8s_cluster_location", "}", "fallback_resource", "=", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "end", "unless", "@k8s_cluster_name", "&&", "@k8s_cluster_location", "@log", ".", "error", "\"Failed to construct #{resource_type} resource locally.\"", "' Falling back to writing logs against'", "\" #{fallback_resource} resource.\"", ",", "error", ":", "e", "return", "end", "constructed_resource", "=", "Google", "::", "Apis", "::", "LoggingV2", "::", "MonitoredResource", ".", "new", "(", "type", ":", "resource_type", ",", "labels", ":", "labels", ")", "@log", ".", "debug", "(", "\"Constructed #{resource_type} resource locally: \"", "\"#{constructed_resource.inspect}\"", ")", "constructed_resource", "end" ]
Construct monitored resource locally for k8s resources.
[ "Construct", "monitored", "resource", "locally", "for", "k8s", "resources", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L2349-L2415
train
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/monitoring.rb
Monitoring.PrometheusMonitoringRegistry.counter
def counter(name, desc) return @registry.counter(name, desc) rescue Prometheus::Client::Registry::AlreadyRegisteredError return @registry.get(name) end
ruby
def counter(name, desc) return @registry.counter(name, desc) rescue Prometheus::Client::Registry::AlreadyRegisteredError return @registry.get(name) end
[ "def", "counter", "(", "name", ",", "desc", ")", "return", "@registry", ".", "counter", "(", "name", ",", "desc", ")", "rescue", "Prometheus", "::", "Client", "::", "Registry", "::", "AlreadyRegisteredError", "return", "@registry", ".", "get", "(", "name", ")", "end" ]
Exception-driven behavior to avoid synchronization errors.
[ "Exception", "-", "driven", "behavior", "to", "avoid", "synchronization", "errors", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/monitoring.rb#L36-L40
train
rossta/serviceworker-rails
lib/serviceworker/middleware.rb
ServiceWorker.Middleware.call
def call(env) case env[REQUEST_METHOD] when GET, HEAD route_match = @router.match_route(env) return respond_to_match(route_match, env) if route_match end @app.call(env) end
ruby
def call(env) case env[REQUEST_METHOD] when GET, HEAD route_match = @router.match_route(env) return respond_to_match(route_match, env) if route_match end @app.call(env) end
[ "def", "call", "(", "env", ")", "case", "env", "[", "REQUEST_METHOD", "]", "when", "GET", ",", "HEAD", "route_match", "=", "@router", ".", "match_route", "(", "env", ")", "return", "respond_to_match", "(", "route_match", ",", "env", ")", "if", "route_match", "end", "@app", ".", "call", "(", "env", ")", "end" ]
Initialize the Rack middleware for responding to serviceworker asset requests @app [#call] middleware stack @opts [Hash] options to inject @param opts [#match_route] :routes matches routes on PATH_INFO @param opts [Hash] :headers default headers to use for matched routes @param opts [#call] :handler resolves response from matched asset name @param opts [#info] :logger logs requests
[ "Initialize", "the", "Rack", "middleware", "for", "responding", "to", "serviceworker", "asset", "requests" ]
757db5354c9e47a144397c4655f3d1cab6046bc0
https://github.com/rossta/serviceworker-rails/blob/757db5354c9e47a144397c4655f3d1cab6046bc0/lib/serviceworker/middleware.rb#L28-L36
train
glebm/i18n-tasks
lib/i18n/tasks/used_keys.rb
I18n::Tasks.UsedKeys.used_tree
def used_tree(key_filter: nil, strict: nil, include_raw_references: false) src_tree = used_in_source_tree(key_filter: key_filter, strict: strict) raw_refs, resolved_refs, used_refs = process_references(src_tree['used'].children) raw_refs.leaves { |node| node.data[:ref_type] = :reference_usage } resolved_refs.leaves { |node| node.data[:ref_type] = :reference_usage_resolved } used_refs.leaves { |node| node.data[:ref_type] = :reference_usage_key } src_tree.tap do |result| tree = result['used'].children tree.subtract_by_key!(raw_refs) tree.merge!(raw_refs) if include_raw_references tree.merge!(used_refs).merge!(resolved_refs) end end
ruby
def used_tree(key_filter: nil, strict: nil, include_raw_references: false) src_tree = used_in_source_tree(key_filter: key_filter, strict: strict) raw_refs, resolved_refs, used_refs = process_references(src_tree['used'].children) raw_refs.leaves { |node| node.data[:ref_type] = :reference_usage } resolved_refs.leaves { |node| node.data[:ref_type] = :reference_usage_resolved } used_refs.leaves { |node| node.data[:ref_type] = :reference_usage_key } src_tree.tap do |result| tree = result['used'].children tree.subtract_by_key!(raw_refs) tree.merge!(raw_refs) if include_raw_references tree.merge!(used_refs).merge!(resolved_refs) end end
[ "def", "used_tree", "(", "key_filter", ":", "nil", ",", "strict", ":", "nil", ",", "include_raw_references", ":", "false", ")", "src_tree", "=", "used_in_source_tree", "(", "key_filter", ":", "key_filter", ",", "strict", ":", "strict", ")", "raw_refs", ",", "resolved_refs", ",", "used_refs", "=", "process_references", "(", "src_tree", "[", "'used'", "]", ".", "children", ")", "raw_refs", ".", "leaves", "{", "|", "node", "|", "node", ".", "data", "[", ":ref_type", "]", "=", ":reference_usage", "}", "resolved_refs", ".", "leaves", "{", "|", "node", "|", "node", ".", "data", "[", ":ref_type", "]", "=", ":reference_usage_resolved", "}", "used_refs", ".", "leaves", "{", "|", "node", "|", "node", ".", "data", "[", ":ref_type", "]", "=", ":reference_usage_key", "}", "src_tree", ".", "tap", "do", "|", "result", "|", "tree", "=", "result", "[", "'used'", "]", ".", "children", "tree", ".", "subtract_by_key!", "(", "raw_refs", ")", "tree", ".", "merge!", "(", "raw_refs", ")", "if", "include_raw_references", "tree", ".", "merge!", "(", "used_refs", ")", ".", "merge!", "(", "resolved_refs", ")", "end", "end" ]
Find all keys in the source and return a forest with the keys in absolute form and their occurrences. @param key_filter [String] only return keys matching this pattern. @param strict [Boolean] if true, dynamic keys are excluded (e.g. `t("category.#{ category.key }")`) @param include_raw_references [Boolean] if true, includes reference usages as they appear in the source @return [Data::Tree::Siblings]
[ "Find", "all", "keys", "in", "the", "source", "and", "return", "a", "forest", "with", "the", "keys", "in", "absolute", "form", "and", "their", "occurrences", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/used_keys.rb#L36-L48
train
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_key_literals.rb
I18n::Tasks::Scanners.RubyKeyLiterals.strip_literal
def strip_literal(literal) literal = literal[1..-1] if literal[0] == ':' literal = literal[1..-2] if literal[0] == "'" || literal[0] == '"' literal end
ruby
def strip_literal(literal) literal = literal[1..-1] if literal[0] == ':' literal = literal[1..-2] if literal[0] == "'" || literal[0] == '"' literal end
[ "def", "strip_literal", "(", "literal", ")", "literal", "=", "literal", "[", "1", "..", "-", "1", "]", "if", "literal", "[", "0", "]", "==", "':'", "literal", "=", "literal", "[", "1", "..", "-", "2", "]", "if", "literal", "[", "0", "]", "==", "\"'\"", "||", "literal", "[", "0", "]", "==", "'\"'", "literal", "end" ]
remove the leading colon and unwrap quotes from the key match @param literal [String] e.g: "key", 'key', or :key. @return [String] key
[ "remove", "the", "leading", "colon", "and", "unwrap", "quotes", "from", "the", "key", "match" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_key_literals.rb#L17-L21
train
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.load_rails_i18n_pluralization!
def load_rails_i18n_pluralization!(locale) path = File.join(Gem::Specification.find_by_name('rails-i18n').gem_dir, 'rails', 'pluralization', "#{locale}.rb") eval(File.read(path), binding, path) # rubocop:disable Security/Eval end
ruby
def load_rails_i18n_pluralization!(locale) path = File.join(Gem::Specification.find_by_name('rails-i18n').gem_dir, 'rails', 'pluralization', "#{locale}.rb") eval(File.read(path), binding, path) # rubocop:disable Security/Eval end
[ "def", "load_rails_i18n_pluralization!", "(", "locale", ")", "path", "=", "File", ".", "join", "(", "Gem", "::", "Specification", ".", "find_by_name", "(", "'rails-i18n'", ")", ".", "gem_dir", ",", "'rails'", ",", "'pluralization'", ",", "\"#{locale}.rb\"", ")", "eval", "(", "File", ".", "read", "(", "path", ")", ",", "binding", ",", "path", ")", "# rubocop:disable Security/Eval", "end" ]
Loads rails-i18n pluralization config for the given locale.
[ "Loads", "rails", "-", "i18n", "pluralization", "config", "for", "the", "given", "locale", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L91-L94
train
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.missing_diff_tree
def missing_diff_tree(locale, compared_to = base_locale) data[compared_to].select_keys do |key, _node| locale_key_missing? locale, depluralize_key(key, compared_to) end.set_root_key!(locale, type: :missing_diff).keys do |_key, node| # change path and locale to base data = { locale: locale, missing_diff_locale: node.data[:locale] } if node.data.key?(:path) data[:path] = LocalePathname.replace_locale(node.data[:path], node.data[:locale], locale) end node.data.update data end end
ruby
def missing_diff_tree(locale, compared_to = base_locale) data[compared_to].select_keys do |key, _node| locale_key_missing? locale, depluralize_key(key, compared_to) end.set_root_key!(locale, type: :missing_diff).keys do |_key, node| # change path and locale to base data = { locale: locale, missing_diff_locale: node.data[:locale] } if node.data.key?(:path) data[:path] = LocalePathname.replace_locale(node.data[:path], node.data[:locale], locale) end node.data.update data end end
[ "def", "missing_diff_tree", "(", "locale", ",", "compared_to", "=", "base_locale", ")", "data", "[", "compared_to", "]", ".", "select_keys", "do", "|", "key", ",", "_node", "|", "locale_key_missing?", "locale", ",", "depluralize_key", "(", "key", ",", "compared_to", ")", "end", ".", "set_root_key!", "(", "locale", ",", "type", ":", ":missing_diff", ")", ".", "keys", "do", "|", "_key", ",", "node", "|", "# change path and locale to base", "data", "=", "{", "locale", ":", "locale", ",", "missing_diff_locale", ":", "node", ".", "data", "[", ":locale", "]", "}", "if", "node", ".", "data", ".", "key?", "(", ":path", ")", "data", "[", ":path", "]", "=", "LocalePathname", ".", "replace_locale", "(", "node", ".", "data", "[", ":path", "]", ",", "node", ".", "data", "[", ":locale", "]", ",", "locale", ")", "end", "node", ".", "data", ".", "update", "data", "end", "end" ]
keys present in compared_to, but not in locale
[ "keys", "present", "in", "compared_to", "but", "not", "in", "locale" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L97-L108
train
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.missing_used_tree
def missing_used_tree(locale) used_tree(strict: true).select_keys do |key, _node| locale_key_missing?(locale, key) end.set_root_key!(locale, type: :missing_used) end
ruby
def missing_used_tree(locale) used_tree(strict: true).select_keys do |key, _node| locale_key_missing?(locale, key) end.set_root_key!(locale, type: :missing_used) end
[ "def", "missing_used_tree", "(", "locale", ")", "used_tree", "(", "strict", ":", "true", ")", ".", "select_keys", "do", "|", "key", ",", "_node", "|", "locale_key_missing?", "(", "locale", ",", "key", ")", "end", ".", "set_root_key!", "(", "locale", ",", "type", ":", ":missing_used", ")", "end" ]
keys used in the code missing translations in locale
[ "keys", "used", "in", "the", "code", "missing", "translations", "in", "locale" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L111-L115
train
glebm/i18n-tasks
lib/i18n/tasks/scanners/pattern_scanner.rb
I18n::Tasks::Scanners.PatternScanner.scan_file
def scan_file(path) keys = [] text = read_file(path) text.scan(@pattern) do |match| src_pos = Regexp.last_match.offset(0).first location = occurrence_from_position(path, text, src_pos, raw_key: strip_literal(match[0])) next if exclude_line?(location.line, path) key = match_to_key(match, path, location) next unless key key += ':' if key.end_with?('.') next unless valid_key?(key) keys << [key, location] end keys rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
ruby
def scan_file(path) keys = [] text = read_file(path) text.scan(@pattern) do |match| src_pos = Regexp.last_match.offset(0).first location = occurrence_from_position(path, text, src_pos, raw_key: strip_literal(match[0])) next if exclude_line?(location.line, path) key = match_to_key(match, path, location) next unless key key += ':' if key.end_with?('.') next unless valid_key?(key) keys << [key, location] end keys rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
[ "def", "scan_file", "(", "path", ")", "keys", "=", "[", "]", "text", "=", "read_file", "(", "path", ")", "text", ".", "scan", "(", "@pattern", ")", "do", "|", "match", "|", "src_pos", "=", "Regexp", ".", "last_match", ".", "offset", "(", "0", ")", ".", "first", "location", "=", "occurrence_from_position", "(", "path", ",", "text", ",", "src_pos", ",", "raw_key", ":", "strip_literal", "(", "match", "[", "0", "]", ")", ")", "next", "if", "exclude_line?", "(", "location", ".", "line", ",", "path", ")", "key", "=", "match_to_key", "(", "match", ",", "path", ",", "location", ")", "next", "unless", "key", "key", "+=", "':'", "if", "key", ".", "end_with?", "(", "'.'", ")", "next", "unless", "valid_key?", "(", "key", ")", "keys", "<<", "[", "key", ",", "location", "]", "end", "keys", "rescue", "Exception", "=>", "e", "# rubocop:disable Lint/RescueException", "raise", "::", "I18n", "::", "Tasks", "::", "CommandError", ".", "new", "(", "e", ",", "\"Error scanning #{path}: #{e.message}\"", ")", "end" ]
Extract i18n keys from file based on the pattern which must capture the key literal. @return [Array<[key, Results::Occurrence]>] each occurrence found in the file
[ "Extract", "i18n", "keys", "from", "file", "based", "on", "the", "pattern", "which", "must", "capture", "the", "key", "literal", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/pattern_scanner.rb#L39-L55
train
glebm/i18n-tasks
lib/i18n/tasks/translators/google_translator.rb
I18n::Tasks::Translators.GoogleTranslator.to_google_translate_compatible_locale
def to_google_translate_compatible_locale(locale) return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale) locale.split('-', 2).first end
ruby
def to_google_translate_compatible_locale(locale) return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale) locale.split('-', 2).first end
[ "def", "to_google_translate_compatible_locale", "(", "locale", ")", "return", "locale", "unless", "locale", ".", "include?", "(", "'-'", ")", "&&", "!", "SUPPORTED_LOCALES_WITH_REGION", ".", "include?", "(", "locale", ")", "locale", ".", "split", "(", "'-'", ",", "2", ")", ".", "first", "end" ]
Convert 'es-ES' to 'es'
[ "Convert", "es", "-", "ES", "to", "es" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/translators/google_translator.rb#L47-L50
train
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.scan_file
def scan_file(path) @parser.reset ast, comments = @parser.parse_with_comments(make_buffer(path)) results = @call_finder.collect_calls ast do |send_node, method_name| send_node_to_key_occurrence(send_node, method_name) end magic_comments = comments.select { |comment| comment.text =~ MAGIC_COMMENT_PREFIX } comment_to_node = Parser::Source::Comment.associate_locations(ast, magic_comments).tap do |h| # transform_values is only available in ActiveSupport 4.2+ h.each { |k, v| h[k] = v.first } end.invert results + (magic_comments.flat_map do |comment| @parser.reset associated_node = comment_to_node[comment] @call_finder.collect_calls( @parser.parse(make_buffer(path, comment.text.sub(MAGIC_COMMENT_PREFIX, '').split(/\s+(?=t)/).join('; '))) ) do |send_node, _method_name| # method_name is not available at this stage send_node_to_key_occurrence(send_node, nil, location: associated_node || comment.location) end end) rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
ruby
def scan_file(path) @parser.reset ast, comments = @parser.parse_with_comments(make_buffer(path)) results = @call_finder.collect_calls ast do |send_node, method_name| send_node_to_key_occurrence(send_node, method_name) end magic_comments = comments.select { |comment| comment.text =~ MAGIC_COMMENT_PREFIX } comment_to_node = Parser::Source::Comment.associate_locations(ast, magic_comments).tap do |h| # transform_values is only available in ActiveSupport 4.2+ h.each { |k, v| h[k] = v.first } end.invert results + (magic_comments.flat_map do |comment| @parser.reset associated_node = comment_to_node[comment] @call_finder.collect_calls( @parser.parse(make_buffer(path, comment.text.sub(MAGIC_COMMENT_PREFIX, '').split(/\s+(?=t)/).join('; '))) ) do |send_node, _method_name| # method_name is not available at this stage send_node_to_key_occurrence(send_node, nil, location: associated_node || comment.location) end end) rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
[ "def", "scan_file", "(", "path", ")", "@parser", ".", "reset", "ast", ",", "comments", "=", "@parser", ".", "parse_with_comments", "(", "make_buffer", "(", "path", ")", ")", "results", "=", "@call_finder", ".", "collect_calls", "ast", "do", "|", "send_node", ",", "method_name", "|", "send_node_to_key_occurrence", "(", "send_node", ",", "method_name", ")", "end", "magic_comments", "=", "comments", ".", "select", "{", "|", "comment", "|", "comment", ".", "text", "=~", "MAGIC_COMMENT_PREFIX", "}", "comment_to_node", "=", "Parser", "::", "Source", "::", "Comment", ".", "associate_locations", "(", "ast", ",", "magic_comments", ")", ".", "tap", "do", "|", "h", "|", "# transform_values is only available in ActiveSupport 4.2+", "h", ".", "each", "{", "|", "k", ",", "v", "|", "h", "[", "k", "]", "=", "v", ".", "first", "}", "end", ".", "invert", "results", "+", "(", "magic_comments", ".", "flat_map", "do", "|", "comment", "|", "@parser", ".", "reset", "associated_node", "=", "comment_to_node", "[", "comment", "]", "@call_finder", ".", "collect_calls", "(", "@parser", ".", "parse", "(", "make_buffer", "(", "path", ",", "comment", ".", "text", ".", "sub", "(", "MAGIC_COMMENT_PREFIX", ",", "''", ")", ".", "split", "(", "/", "\\s", "/", ")", ".", "join", "(", "'; '", ")", ")", ")", ")", "do", "|", "send_node", ",", "_method_name", "|", "# method_name is not available at this stage", "send_node_to_key_occurrence", "(", "send_node", ",", "nil", ",", "location", ":", "associated_node", "||", "comment", ".", "location", ")", "end", "end", ")", "rescue", "Exception", "=>", "e", "# rubocop:disable Lint/RescueException", "raise", "::", "I18n", "::", "Tasks", "::", "CommandError", ".", "new", "(", "e", ",", "\"Error scanning #{path}: #{e.message}\"", ")", "end" ]
Extract all occurrences of translate calls from the file at the given path. @return [Array<[key, Results::KeyOccurrence]>] each occurrence found in the file
[ "Extract", "all", "occurrences", "of", "translate", "calls", "from", "the", "file", "at", "the", "given", "path", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L34-L59
train
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.extract_hash_pair
def extract_hash_pair(node, key) node.children.detect do |child| next unless child.type == :pair key_node = child.children[0] %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key end end
ruby
def extract_hash_pair(node, key) node.children.detect do |child| next unless child.type == :pair key_node = child.children[0] %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key end end
[ "def", "extract_hash_pair", "(", "node", ",", "key", ")", "node", ".", "children", ".", "detect", "do", "|", "child", "|", "next", "unless", "child", ".", "type", "==", ":pair", "key_node", "=", "child", ".", "children", "[", "0", "]", "%i[", "sym", "str", "]", ".", "include?", "(", "key_node", ".", "type", ")", "&&", "key_node", ".", "children", "[", "0", "]", ".", "to_s", "==", "key", "end", "end" ]
Extract a hash pair with a given literal key. @param node [AST::Node] a node of type `:hash`. @param key [String] node key as a string (indifferent symbol-string matching). @return [AST::Node, nil] a node of type `:pair` or nil.
[ "Extract", "a", "hash", "pair", "with", "a", "given", "literal", "key", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L95-L101
train
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.extract_array_as_string
def extract_array_as_string(node, array_join_with:, array_flatten: false, array_reject_blank: false) children_strings = node.children.map do |child| if %i[sym str int true false].include?(child.type) # rubocop:disable Lint/BooleanSymbol extract_string child else # ignore dynamic argument in strict mode return nil if config[:strict] if %i[dsym dstr].include?(child.type) || (child.type == :array && array_flatten) extract_string(child, array_join_with: array_join_with) else "\#{#{child.loc.expression.source}}" end end end if array_reject_blank children_strings.reject! do |x| # empty strings and nils in the scope argument are ignored by i18n x == '' end end children_strings.join(array_join_with) end
ruby
def extract_array_as_string(node, array_join_with:, array_flatten: false, array_reject_blank: false) children_strings = node.children.map do |child| if %i[sym str int true false].include?(child.type) # rubocop:disable Lint/BooleanSymbol extract_string child else # ignore dynamic argument in strict mode return nil if config[:strict] if %i[dsym dstr].include?(child.type) || (child.type == :array && array_flatten) extract_string(child, array_join_with: array_join_with) else "\#{#{child.loc.expression.source}}" end end end if array_reject_blank children_strings.reject! do |x| # empty strings and nils in the scope argument are ignored by i18n x == '' end end children_strings.join(array_join_with) end
[ "def", "extract_array_as_string", "(", "node", ",", "array_join_with", ":", ",", "array_flatten", ":", "false", ",", "array_reject_blank", ":", "false", ")", "children_strings", "=", "node", ".", "children", ".", "map", "do", "|", "child", "|", "if", "%i[", "sym", "str", "int", "true", "false", "]", ".", "include?", "(", "child", ".", "type", ")", "# rubocop:disable Lint/BooleanSymbol", "extract_string", "child", "else", "# ignore dynamic argument in strict mode", "return", "nil", "if", "config", "[", ":strict", "]", "if", "%i[", "dsym", "dstr", "]", ".", "include?", "(", "child", ".", "type", ")", "||", "(", "child", ".", "type", "==", ":array", "&&", "array_flatten", ")", "extract_string", "(", "child", ",", "array_join_with", ":", "array_join_with", ")", "else", "\"\\#{#{child.loc.expression.source}}\"", "end", "end", "end", "if", "array_reject_blank", "children_strings", ".", "reject!", "do", "|", "x", "|", "# empty strings and nils in the scope argument are ignored by i18n", "x", "==", "''", "end", "end", "children_strings", ".", "join", "(", "array_join_with", ")", "end" ]
Extract an array as a single string. @param array_join_with [String] joiner of the array elements. @param array_flatten [Boolean] if true, nested arrays are flattened, otherwise their source is copied and surrounded by #{}. @param array_reject_blank [Boolean] if true, empty strings and `nil`s are skipped. @return [String, nil] `nil` is returned only when a dynamic value is encountered in strict mode.
[ "Extract", "an", "array", "as", "a", "single", "string", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L150-L171
train
glebm/i18n-tasks
lib/i18n/tasks/data/tree/siblings.rb
I18n::Tasks::Data::Tree.Siblings.add_ancestors_that_only_contain_nodes!
def add_ancestors_that_only_contain_nodes!(nodes) levels.reverse_each do |level_nodes| level_nodes.each { |node| nodes << node if node.children? && node.children.all? { |c| nodes.include?(c) } } end end
ruby
def add_ancestors_that_only_contain_nodes!(nodes) levels.reverse_each do |level_nodes| level_nodes.each { |node| nodes << node if node.children? && node.children.all? { |c| nodes.include?(c) } } end end
[ "def", "add_ancestors_that_only_contain_nodes!", "(", "nodes", ")", "levels", ".", "reverse_each", "do", "|", "level_nodes", "|", "level_nodes", ".", "each", "{", "|", "node", "|", "nodes", "<<", "node", "if", "node", ".", "children?", "&&", "node", ".", "children", ".", "all?", "{", "|", "c", "|", "nodes", ".", "include?", "(", "c", ")", "}", "}", "end", "end" ]
Adds all the ancestors that only contain the given nodes as descendants to the given nodes. @param nodes [Set] Modified in-place.
[ "Adds", "all", "the", "ancestors", "that", "only", "contain", "the", "given", "nodes", "as", "descendants", "to", "the", "given", "nodes", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/data/tree/siblings.rb#L226-L230
train
glebm/i18n-tasks
lib/i18n/tasks/reports/base.rb
I18n::Tasks::Reports.Base.sort_by_attr!
def sort_by_attr!(objects, order = { locale: :asc, key: :asc }) order_keys = order.keys objects.sort! do |a, b| by = order_keys.detect { |k| a[k] != b[k] } order[by] == :desc ? b[by] <=> a[by] : a[by] <=> b[by] end objects end
ruby
def sort_by_attr!(objects, order = { locale: :asc, key: :asc }) order_keys = order.keys objects.sort! do |a, b| by = order_keys.detect { |k| a[k] != b[k] } order[by] == :desc ? b[by] <=> a[by] : a[by] <=> b[by] end objects end
[ "def", "sort_by_attr!", "(", "objects", ",", "order", "=", "{", "locale", ":", ":asc", ",", "key", ":", ":asc", "}", ")", "order_keys", "=", "order", ".", "keys", "objects", ".", "sort!", "do", "|", "a", ",", "b", "|", "by", "=", "order_keys", ".", "detect", "{", "|", "k", "|", "a", "[", "k", "]", "!=", "b", "[", "k", "]", "}", "order", "[", "by", "]", "==", ":desc", "?", "b", "[", "by", "]", "<=>", "a", "[", "by", "]", ":", "a", "[", "by", "]", "<=>", "b", "[", "by", "]", "end", "objects", "end" ]
Sort keys by their attributes in order @param [Hash] order e.g. {locale: :asc, type: :desc, key: :asc}
[ "Sort", "keys", "by", "their", "attributes", "in", "order" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/reports/base.rb#L44-L51
train
glebm/i18n-tasks
lib/i18n/tasks/data.rb
I18n::Tasks.Data.data
def data @data ||= begin data_config = (config[:data] || {}).deep_symbolize_keys data_config[:base_locale] = base_locale data_config[:locales] = config[:locales] adapter_class = data_config[:adapter].presence || data_config[:class].presence || DATA_DEFAULTS[:adapter] adapter_class = adapter_class.to_s adapter_class = 'I18n::Tasks::Data::FileSystem' if adapter_class == 'file_system' data_config.except!(:adapter, :class) ActiveSupport::Inflector.constantize(adapter_class).new data_config end end
ruby
def data @data ||= begin data_config = (config[:data] || {}).deep_symbolize_keys data_config[:base_locale] = base_locale data_config[:locales] = config[:locales] adapter_class = data_config[:adapter].presence || data_config[:class].presence || DATA_DEFAULTS[:adapter] adapter_class = adapter_class.to_s adapter_class = 'I18n::Tasks::Data::FileSystem' if adapter_class == 'file_system' data_config.except!(:adapter, :class) ActiveSupport::Inflector.constantize(adapter_class).new data_config end end
[ "def", "data", "@data", "||=", "begin", "data_config", "=", "(", "config", "[", ":data", "]", "||", "{", "}", ")", ".", "deep_symbolize_keys", "data_config", "[", ":base_locale", "]", "=", "base_locale", "data_config", "[", ":locales", "]", "=", "config", "[", ":locales", "]", "adapter_class", "=", "data_config", "[", ":adapter", "]", ".", "presence", "||", "data_config", "[", ":class", "]", ".", "presence", "||", "DATA_DEFAULTS", "[", ":adapter", "]", "adapter_class", "=", "adapter_class", ".", "to_s", "adapter_class", "=", "'I18n::Tasks::Data::FileSystem'", "if", "adapter_class", "==", "'file_system'", "data_config", ".", "except!", "(", ":adapter", ",", ":class", ")", "ActiveSupport", "::", "Inflector", ".", "constantize", "(", "adapter_class", ")", ".", "new", "data_config", "end", "end" ]
I18n data provider @see I18n::Tasks::Data::FileSystem
[ "I18n", "data", "provider" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/data.rb#L13-L24
train
glebm/i18n-tasks
lib/i18n/tasks/references.rb
I18n::Tasks.References.merge_reference_trees
def merge_reference_trees(roots) roots.inject(empty_forest) do |forest, root| root.keys do |full_key, node| if full_key == node.value.to_s log_warn( "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}" ) end end forest.merge!( root.children, on_leaves_merge: lambda do |node, other| if node.value != other.value log_warn( 'Conflicting references: '\ "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\ " but ⮕ #{other.value} in #{other.data[:locale]}" ) end end ) end end
ruby
def merge_reference_trees(roots) roots.inject(empty_forest) do |forest, root| root.keys do |full_key, node| if full_key == node.value.to_s log_warn( "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}" ) end end forest.merge!( root.children, on_leaves_merge: lambda do |node, other| if node.value != other.value log_warn( 'Conflicting references: '\ "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\ " but ⮕ #{other.value} in #{other.data[:locale]}" ) end end ) end end
[ "def", "merge_reference_trees", "(", "roots", ")", "roots", ".", "inject", "(", "empty_forest", ")", "do", "|", "forest", ",", "root", "|", "root", ".", "keys", "do", "|", "full_key", ",", "node", "|", "if", "full_key", "==", "node", ".", "value", ".", "to_s", "log_warn", "(", "\"Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}\"", ")", "end", "end", "forest", ".", "merge!", "(", "root", ".", "children", ",", "on_leaves_merge", ":", "lambda", "do", "|", "node", ",", "other", "|", "if", "node", ".", "value", "!=", "other", ".", "value", "log_warn", "(", "'Conflicting references: '", "\"#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},\"\\", "\" but ⮕ #{other.value} in #{other.data[:locale]}\"", ")", "end", "end", ")", "end", "end" ]
Given a forest of references, merge trees into one tree, ensuring there are no conflicting references. @param roots [I18n::Tasks::Data::Tree::Siblings] @return [I18n::Tasks::Data::Tree::Siblings]
[ "Given", "a", "forest", "of", "references", "merge", "trees", "into", "one", "tree", "ensuring", "there", "are", "no", "conflicting", "references", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/references.rb#L77-L99
train
glebm/i18n-tasks
lib/i18n/tasks/scanners/files/file_reader.rb
I18n::Tasks::Scanners::Files.FileReader.read_file
def read_file(path) result = nil File.open(path, 'rb', encoding: 'UTF-8') { |f| result = f.read } result end
ruby
def read_file(path) result = nil File.open(path, 'rb', encoding: 'UTF-8') { |f| result = f.read } result end
[ "def", "read_file", "(", "path", ")", "result", "=", "nil", "File", ".", "open", "(", "path", ",", "'rb'", ",", "encoding", ":", "'UTF-8'", ")", "{", "|", "f", "|", "result", "=", "f", ".", "read", "}", "result", "end" ]
Return the contents of the file at the given path. The file is read in the 'rb' mode and UTF-8 encoding. @param path [String] Path to the file, absolute or relative to the working directory. @return [String] file contents
[ "Return", "the", "contents", "of", "the", "file", "at", "the", "given", "path", ".", "The", "file", "is", "read", "in", "the", "rb", "mode", "and", "UTF", "-", "8", "encoding", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/files/file_reader.rb#L13-L17
train
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.pos
def pos *indexes positions = indexes.map do |index| if include? index @cat_hash[index] elsif index.is_a?(Numeric) && index < @array.size index else raise IndexError, "#{index.inspect} is neither a valid category"\ ' nor a valid position' end end positions.flatten! positions.size == 1 ? positions.first : positions.sort end
ruby
def pos *indexes positions = indexes.map do |index| if include? index @cat_hash[index] elsif index.is_a?(Numeric) && index < @array.size index else raise IndexError, "#{index.inspect} is neither a valid category"\ ' nor a valid position' end end positions.flatten! positions.size == 1 ? positions.first : positions.sort end
[ "def", "pos", "*", "indexes", "positions", "=", "indexes", ".", "map", "do", "|", "index", "|", "if", "include?", "index", "@cat_hash", "[", "index", "]", "elsif", "index", ".", "is_a?", "(", "Numeric", ")", "&&", "index", "<", "@array", ".", "size", "index", "else", "raise", "IndexError", ",", "\"#{index.inspect} is neither a valid category\"", "' nor a valid position'", "end", "end", "positions", ".", "flatten!", "positions", ".", "size", "==", "1", "?", "positions", ".", "first", ":", "positions", ".", "sort", "end" ]
Returns positions given categories or positions @note If the argument does not a valid category it treats it as position value and return it as it is. @param indexes [Array<object>] categories or positions @example x = Daru::CategoricalIndex.new [:a, 1, :a, 1, :c] x.pos :a, 1 # => [0, 1, 2, 3]
[ "Returns", "positions", "given", "categories", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L53-L67
train
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.subset
def subset *indexes positions = pos(*indexes) new_index = positions.map { |pos| index_from_pos pos } Daru::CategoricalIndex.new new_index.flatten end
ruby
def subset *indexes positions = pos(*indexes) new_index = positions.map { |pos| index_from_pos pos } Daru::CategoricalIndex.new new_index.flatten end
[ "def", "subset", "*", "indexes", "positions", "=", "pos", "(", "indexes", ")", "new_index", "=", "positions", ".", "map", "{", "|", "pos", "|", "index_from_pos", "pos", "}", "Daru", "::", "CategoricalIndex", ".", "new", "new_index", ".", "flatten", "end" ]
Return subset given categories or positions @param indexes [Array<object>] categories or positions @return [Daru::CategoricalIndex] subset of the self containing the mentioned categories or positions @example idx = Daru::CategoricalIndex.new [:a, :b, :a, :b, :c] idx.subset :a, :b # => #<Daru::CategoricalIndex(4): {a, b, a, b}>
[ "Return", "subset", "given", "categories", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L155-L160
train
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.at
def at *positions positions = preprocess_positions(*positions) validate_positions(*positions) if positions.is_a? Integer index_from_pos(positions) else Daru::CategoricalIndex.new positions.map(&method(:index_from_pos)) end end
ruby
def at *positions positions = preprocess_positions(*positions) validate_positions(*positions) if positions.is_a? Integer index_from_pos(positions) else Daru::CategoricalIndex.new positions.map(&method(:index_from_pos)) end end
[ "def", "at", "*", "positions", "positions", "=", "preprocess_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "index_from_pos", "(", "positions", ")", "else", "Daru", "::", "CategoricalIndex", ".", "new", "positions", ".", "map", "(", "method", "(", ":index_from_pos", ")", ")", "end", "end" ]
Takes positional values and returns subset of the self capturing the categories at mentioned positions @param positions [Array<Integer>] positional values @return [object] index object @example idx = Daru::CategoricalIndex.new [:a, :b, :a, :b, :c] idx.at 0, 1 # => #<Daru::CategoricalIndex(2): {a, b}>
[ "Takes", "positional", "values", "and", "returns", "subset", "of", "the", "self", "capturing", "the", "categories", "at", "mentioned", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L170-L178
train
SciRuby/daru
lib/daru/index/multi_index.rb
Daru.MultiIndex.validate_name
def validate_name names, levels error_msg = "'names' and 'levels' should be of same size. Size of the "\ "'name' array is #{names.size} and size of the MultiIndex 'levels' and "\ "'labels' is #{labels.size}." suggestion_msg = "If you don\'t want to set name for particular level " \ "(say level 'i') then put empty string on index 'i' of the 'name' Array." raise SizeError, error_msg if names.size > levels.size raise SizeError, [error_msg, suggestion_msg].join("\n") if names.size < levels.size end
ruby
def validate_name names, levels error_msg = "'names' and 'levels' should be of same size. Size of the "\ "'name' array is #{names.size} and size of the MultiIndex 'levels' and "\ "'labels' is #{labels.size}." suggestion_msg = "If you don\'t want to set name for particular level " \ "(say level 'i') then put empty string on index 'i' of the 'name' Array." raise SizeError, error_msg if names.size > levels.size raise SizeError, [error_msg, suggestion_msg].join("\n") if names.size < levels.size end
[ "def", "validate_name", "names", ",", "levels", "error_msg", "=", "\"'names' and 'levels' should be of same size. Size of the \"", "\"'name' array is #{names.size} and size of the MultiIndex 'levels' and \"", "\"'labels' is #{labels.size}.\"", "suggestion_msg", "=", "\"If you don\\'t want to set name for particular level \"", "\"(say level 'i') then put empty string on index 'i' of the 'name' Array.\"", "raise", "SizeError", ",", "error_msg", "if", "names", ".", "size", ">", "levels", ".", "size", "raise", "SizeError", ",", "[", "error_msg", ",", "suggestion_msg", "]", ".", "join", "(", "\"\\n\"", ")", "if", "names", ".", "size", "<", "levels", ".", "size", "end" ]
Array `name` must have same length as levels and labels.
[ "Array", "name", "must", "have", "same", "length", "as", "levels", "and", "labels", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/multi_index.rb#L266-L275
train