_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q11500
Responders.ControllerMethod.responders
train
def responders(*responders) self.responder = responders.inject(Class.new(responder)) do |klass, responder| responder = case responder when Module responder when String, Symbol Responders.const_get("#{responder.to_s.camelize}Responder") else raise "responder has to be a string, a symbol or a module" end klass.send(:include, responder) klass end end
ruby
{ "resource": "" }
q11501
ActionController.RespondWith.respond_with
train
def respond_with(*resources, &block) if self.class.mimes_for_respond_to.empty? raise "In order to use respond_with, first you need to declare the " \ "formats your controller responds to in the class level." end mimes = collect_mimes_from_class_level collector = ActionController::MimeResponds::Collector.new(mimes, request.variant) block.call(collector) if block_given? if format = collector.negotiate_format(request) _process_format(format) options = resources.size == 1 ? {} : resources.extract_options! options = options.clone options[:default_response] = collector.response (options.delete(:responder) || self.class.responder).call(self, resources, options) else raise ActionController::UnknownFormat end end
ruby
{ "resource": "" }
q11502
ActionController.RespondWith.collect_mimes_from_class_level
train
def collect_mimes_from_class_level #:nodoc: action = action_name.to_sym self.class.mimes_for_respond_to.keys.select do |mime| config = self.class.mimes_for_respond_to[mime] if config[:except] !config[:except].include?(action) elsif config[:only] config[:only].include?(action) else true end end end
ruby
{ "resource": "" }
q11503
AlgoliaSearch.ClassMethods.algolia_reindex
train
def algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) return if algolia_without_auto_index_scope algolia_configurations.each do |options, settings| next if algolia_indexing_disabled?(options) next if options[:slave] || options[:replica] # fetch the master settings master_index = algolia_ensure_init(options, settings) master_settings = master_index.get_settings rescue {} # if master doesn't exist yet master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings # remove the replicas of the temporary index master_settings.delete :slaves master_settings.delete 'slaves' master_settings.delete :replicas master_settings.delete 'replicas' # init temporary index index_name = algolia_index_name(options) tmp_options = options.merge({ :index_name => "#{index_name}.tmp" }) tmp_options.delete(:per_environment) # already included in the temporary index_name tmp_settings = settings.dup tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings) algolia_find_in_batches(batch_size) do |group| if algolia_conditional_index?(tmp_options) # select only indexable objects group = group.select { |o| algolia_indexable?(o, tmp_options) } end objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) } tmp_index.save_objects(objects) end move_task = SafeIndex.move_index(tmp_index.name, index_name) master_index.wait_task(move_task["taskID"]) if synchronous || options[:synchronous] end nil end
ruby
{ "resource": "" }
q11504
AlgoliaSearch.SafeIndex.get_settings
train
def get_settings(*args) SafeIndex.log_or_throw(:get_settings, @raise_on_failure) do begin @index.get_settings(*args) rescue Algolia::AlgoliaError => e return {} if e.code == 404 # not fatal raise e end end end
ruby
{ "resource": "" }
q11505
Filterrific.ParamSet.define_and_assign_attr_accessors_for_each_filter
train
def define_and_assign_attr_accessors_for_each_filter(fp) model_class.filterrific_available_filters.each do |filter_name| self.class.send(:attr_accessor, filter_name) v = fp[filter_name] self.send("#{ filter_name }=", v) if v.present? end end
ruby
{ "resource": "" }
q11506
Filterrific.ActionControllerExtension.compute_filterrific_params
train
def compute_filterrific_params(model_class, filterrific_params, opts, persistence_id) opts = { "sanitize_params" => true }.merge(opts.stringify_keys) r = ( filterrific_params.presence || # start with passed in params (persistence_id && session[persistence_id].presence) || # then try session persisted params if persistence_id is present opts['default_filter_params'] || # then use passed in opts model_class.filterrific_default_filter_params # finally use model_class defaults ).stringify_keys r.slice!(*opts['available_filters'].map(&:to_s)) if opts['available_filters'] # Sanitize params to prevent reflected XSS attack if opts["sanitize_params"] r.each { |k,v| r[k] = sanitize_filterrific_param(r[k]) } end r end
ruby
{ "resource": "" }
q11507
Filterrific.ActionViewExtension.form_for_filterrific
train
def form_for_filterrific(record, options = {}, &block) options[:as] ||= :filterrific options[:html] ||= {} options[:html][:method] ||= :get options[:html][:id] ||= :filterrific_filter options[:url] ||= url_for( :controller => controller.controller_name, :action => controller.action_name ) form_for(record, options, &block) end
ruby
{ "resource": "" }
q11508
Filterrific.ActionViewExtension.filterrific_sorting_link_reverse_order
train
def filterrific_sorting_link_reverse_order(filterrific, new_sort_key, opts) # current sort column, toggle search_direction new_sort_direction = 'asc' == opts[:current_sort_direction] ? 'desc' : 'asc' new_sorting = safe_join([new_sort_key, new_sort_direction], '_') css_classes = safe_join([ opts[:active_column_class], opts[:html_attrs].delete(:class) ].compact, ' ') new_filterrific_params = filterrific.to_hash .with_indifferent_access .merge(opts[:sorting_scope_name] => new_sorting) url_for_attrs = opts[:url_for_attrs].merge(:filterrific => new_filterrific_params) link_to( safe_join([opts[:label], opts[:current_sort_direction_indicator]], ' '), url_for(url_for_attrs), opts[:html_attrs].reverse_merge(:class => css_classes, :method => :get, :remote => true) ) end
ruby
{ "resource": "" }
q11509
VagrantVbguest.Config.to_hash
train
def to_hash { :installer => installer, :installer_arguments => installer_arguments, :iso_path => iso_path, :iso_upload_path => iso_upload_path, :iso_mount_point => iso_mount_point, :auto_update => auto_update, :auto_reboot => auto_reboot, :no_install => no_install, :no_remote => no_remote, :yes => yes } end
ruby
{ "resource": "" }
q11510
VagrantVbguest.Command.execute_on_vm
train
def execute_on_vm(vm, options) check_runable_on(vm) options = options.clone _method = options.delete(:_method) _rebootable = options.delete(:_rebootable) options = vm.config.vbguest.to_hash.merge(options) machine = VagrantVbguest::Machine.new(vm, options) status = machine.state vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info)) if _method != :status machine.send(_method) end reboot!(vm, options) if _rebootable && machine.reboot? rescue VagrantVbguest::Installer::NoInstallerFoundError => e vm.env.ui.error e.message end
ruby
{ "resource": "" }
q11511
Cocoon.ViewHelpers.link_to_add_association
train
def link_to_add_association(*args, &block) if block_given? link_to_add_association(capture(&block), *args) elsif args.first.respond_to?(:object) association = args.second name = I18n.translate("cocoon.#{association}.add", default: I18n.translate('cocoon.defaults.add')) link_to_add_association(name, *args) else name, f, association, html_options = *args html_options ||= {} render_options = html_options.delete(:render_options) render_options ||= {} override_partial = html_options.delete(:partial) wrap_object = html_options.delete(:wrap_object) force_non_association_create = html_options.delete(:force_non_association_create) || false form_parameter_name = html_options.delete(:form_name) || 'f' count = html_options.delete(:count).to_i html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ') html_options[:'data-association'] = association.to_s.singularize html_options[:'data-associations'] = association.to_s.pluralize new_object = create_object(f, association, force_non_association_create) new_object = wrap_object.call(new_object) if wrap_object.respond_to?(:call) html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, form_parameter_name, render_options, override_partial).to_str).html_safe html_options[:'data-count'] = count if count > 0 link_to(name, '#', html_options) end end
ruby
{ "resource": "" }
q11512
Raven.Instance.capture
train
def capture(options = {}) if block_given? begin yield rescue Error raise # Don't capture Raven errors rescue Exception => e capture_type(e, options) raise end else install_at_exit_hook(options) end end
ruby
{ "resource": "" }
q11513
Raven.Instance.annotate_exception
train
def annotate_exception(exc, options = {}) notes = (exc.instance_variable_defined?(:@__raven_context) && exc.instance_variable_get(:@__raven_context)) || {} Raven::Utils::DeepMergeHash.deep_merge!(notes, options) exc.instance_variable_set(:@__raven_context, notes) exc end
ruby
{ "resource": "" }
q11514
Raven.SidekiqErrorHandler.filter_context
train
def filter_context(context) case context when Array context.map { |arg| filter_context(arg) } when Hash Hash[context.map { |key, value| filter_context_hash(key, value) }] else format_globalid(context) end end
ruby
{ "resource": "" }
q11515
Ohai.System.run_plugins
train
def run_plugins(safe = false, attribute_filter = nil) begin @provides_map.all_plugins(attribute_filter).each do |plugin| @runner.run_plugin(plugin) end rescue Ohai::Exceptions::AttributeNotFound, Ohai::Exceptions::DependencyCycle => e logger.error("Encountered error while running plugins: #{e.inspect}") raise end critical_failed = Ohai::Config.ohai[:critical_plugins] & @runner.failed_plugins unless critical_failed.empty? msg = "The following Ohai plugins marked as critical failed: #{critical_failed}" if @cli logger.error(msg) exit(true) else raise Ohai::Exceptions::CriticalPluginFailure, "#{msg}. Failing Chef run." end end # Freeze all strings. freeze_strings! end
ruby
{ "resource": "" }
q11516
Ohai.System.json_pretty_print
train
def json_pretty_print(item = nil) FFI_Yajl::Encoder.new(pretty: true, validate_utf8: false).encode(item || @data) end
ruby
{ "resource": "" }
q11517
Ohai.ProvidesMap.find_providers_for
train
def find_providers_for(attributes) plugins = [] attributes.each do |attribute| attrs = select_subtree(@map, attribute) raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless attrs raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs[:_plugins] plugins += attrs[:_plugins] end plugins.uniq end
ruby
{ "resource": "" }
q11518
Ohai.ProvidesMap.deep_find_providers_for
train
def deep_find_providers_for(attributes) plugins = [] attributes.each do |attribute| attrs = select_subtree(@map, attribute) unless attrs attrs = select_closest_subtree(@map, attribute) unless attrs raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" end end collect_plugins_in(attrs, plugins) end plugins.uniq end
ruby
{ "resource": "" }
q11519
Ohai.ProvidesMap.find_closest_providers_for
train
def find_closest_providers_for(attributes) plugins = [] attributes.each do |attribute| parts = normalize_and_validate(attribute) raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless @map[parts[0]] attrs = select_closest_subtree(@map, attribute) raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs plugins += attrs[:_plugins] end plugins.uniq end
ruby
{ "resource": "" }
q11520
Ohai.ProvidesMap.collect_plugins_in
train
def collect_plugins_in(provides_map, collected) provides_map.each_key do |plugin| if plugin.eql?("_plugins") collected.concat(provides_map[plugin]) else collect_plugins_in(provides_map[plugin], collected) end end collected end
ruby
{ "resource": "" }
q11521
Ohai.Loader.plugin_files_by_dir
train
def plugin_files_by_dir(plugin_dir = Ohai.config[:plugin_path]) Array(plugin_dir).map do |path| if Dir.exist?(path) Ohai::Log.trace("Searching for Ohai plugins in #{path}") escaped = ChefConfig::PathHelper.escape_glob_dir(path) Dir[File.join(escaped, "**", "*.rb")] else Ohai::Log.debug("The plugin path #{path} does not exist. Skipping...") [] end end.flatten end
ruby
{ "resource": "" }
q11522
Ohai.Loader.load_additional
train
def load_additional(from) from = [ Ohai.config[:plugin_path], from].flatten plugin_files_by_dir(from).collect do |plugin_file| logger.trace "Loading additional plugin: #{plugin_file}" plugin = load_plugin_class(plugin_file) load_v7_plugin(plugin) end end
ruby
{ "resource": "" }
q11523
Ohai.Loader.load_plugin
train
def load_plugin(plugin_path) plugin_class = load_plugin_class(plugin_path) return nil unless plugin_class.kind_of?(Class) if plugin_class < Ohai::DSL::Plugin::VersionVII load_v7_plugin(plugin_class) else raise Exceptions::IllegalPluginDefinition, "cannot create plugin of type #{plugin_class}" end end
ruby
{ "resource": "" }
q11524
Ohai.Runner.get_cycle
train
def get_cycle(plugins, cycle_start) cycle = plugins.drop_while { |plugin| !plugin.eql?(cycle_start) } names = [] cycle.each { |plugin| names << plugin.name } names end
ruby
{ "resource": "" }
q11525
Ruby2D.Triangle.contains?
train
def contains?(x, y) self_area = triangle_area(@x1, @y1, @x2, @y2, @x3, @y3) questioned_area = triangle_area(@x1, @y1, @x2, @y2, x, y) + triangle_area(@x2, @y2, @x3, @y3, x, y) + triangle_area(@x3, @y3, @x1, @y1, x, y) questioned_area <= self_area end
ruby
{ "resource": "" }
q11526
Ruby2D.Sprite.play
train
def play(opts = {}, &done_proc) animation = opts[:animation] loop = opts[:loop] flip = opts[:flip] if !@playing || (animation != @playing_animation && animation != nil) || flip != @flip @playing = true @playing_animation = animation || :default frames = @animations[@playing_animation] flip_sprite(flip) @done_proc = done_proc case frames # When animation is a range, play through frames horizontally when Range @first_frame = frames.first || @defaults[:frame] @current_frame = frames.first || @defaults[:frame] @last_frame = frames.last # When array... when Array @first_frame = 0 @current_frame = 0 @last_frame = frames.length - 1 end # Set looping @loop = loop == true || @defaults[:loop] ? true : false set_frame restart_time end end
ruby
{ "resource": "" }
q11527
Ruby2D.Sprite.set_frame
train
def set_frame frames = @animations[@playing_animation] case frames when Range reset_clipping_rect @clip_x = @current_frame * @clip_width when Array f = frames[@current_frame] @clip_x = f[:x] || @defaults[:clip_x] @clip_y = f[:y] || @defaults[:clip_y] @clip_width = f[:width] || @defaults[:clip_width] @clip_height = f[:height] || @defaults[:clip_height] @frame_time = f[:time] || @defaults[:frame_time] end end
ruby
{ "resource": "" }
q11528
Ruby2D.Line.points_distance
train
def points_distance(x1, y1, x2, y2) Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) end
ruby
{ "resource": "" }
q11529
Ruby2D.Window.set
train
def set(opts) # Store new window attributes, or ignore if nil @title = opts[:title] || @title if Color.is_valid? opts[:background] @background = Color.new(opts[:background]) end @icon = opts[:icon] || @icon @width = opts[:width] || @width @height = opts[:height] || @height @fps_cap = opts[:fps_cap] || @fps_cap @viewport_width = opts[:viewport_width] || @viewport_width @viewport_height = opts[:viewport_height] || @viewport_height @resizable = opts[:resizable] || @resizable @borderless = opts[:borderless] || @borderless @fullscreen = opts[:fullscreen] || @fullscreen @highdpi = opts[:highdpi] || @highdpi unless opts[:diagnostics].nil? @diagnostics = opts[:diagnostics] ext_diagnostics(@diagnostics) end end
ruby
{ "resource": "" }
q11530
Ruby2D.Window.add
train
def add(o) case o when nil raise Error, "Cannot add '#{o.class}' to window!" when Array o.each { |x| add_object(x) } else add_object(o) end end
ruby
{ "resource": "" }
q11531
Ruby2D.Window.remove
train
def remove(o) if o == nil raise Error, "Cannot remove '#{o.class}' from window!" end if i = @objects.index(o) @objects.delete_at(i) true else false end end
ruby
{ "resource": "" }
q11532
Ruby2D.Window.on
train
def on(event, &proc) unless @events.has_key? event raise Error, "`#{event}` is not a valid event type" end event_id = new_event_key @events[event][event_id] = proc EventDescriptor.new(event, event_id) end
ruby
{ "resource": "" }
q11533
Ruby2D.Window.key_callback
train
def key_callback(type, key) key = key.downcase # All key events @events[:key].each do |id, e| e.call(KeyEvent.new(type, key)) end case type # When key is pressed, fired once when :down @events[:key_down].each do |id, e| e.call(KeyEvent.new(type, key)) end # When key is being held down, fired every frame when :held @events[:key_held].each do |id, e| e.call(KeyEvent.new(type, key)) end # When key released, fired once when :up @events[:key_up].each do |id, e| e.call(KeyEvent.new(type, key)) end end end
ruby
{ "resource": "" }
q11534
Ruby2D.Window.mouse_callback
train
def mouse_callback(type, button, direction, x, y, delta_x, delta_y) # All mouse events @events[:mouse].each do |id, e| e.call(MouseEvent.new(type, button, direction, x, y, delta_x, delta_y)) end case type # When mouse button pressed when :down @events[:mouse_down].each do |id, e| e.call(MouseEvent.new(type, button, nil, x, y, nil, nil)) end # When mouse button released when :up @events[:mouse_up].each do |id, e| e.call(MouseEvent.new(type, button, nil, x, y, nil, nil)) end # When mouse motion / movement when :scroll @events[:mouse_scroll].each do |id, e| e.call(MouseEvent.new(type, nil, direction, nil, nil, delta_x, delta_y)) end # When mouse scrolling, wheel or trackpad when :move @events[:mouse_move].each do |id, e| e.call(MouseEvent.new(type, nil, nil, x, y, delta_x, delta_y)) end end end
ruby
{ "resource": "" }
q11535
Ruby2D.Window.controller_callback
train
def controller_callback(which, type, axis, value, button) # All controller events @events[:controller].each do |id, e| e.call(ControllerEvent.new(which, type, axis, value, button)) end case type # When controller axis motion, like analog sticks when :axis @events[:controller_axis].each do |id, e| e.call(ControllerAxisEvent.new(which, axis, value)) end # When controller button is pressed when :button_down @events[:controller_button_down].each do |id, e| e.call(ControllerButtonEvent.new(which, button)) end # When controller button is released when :button_up @events[:controller_button_up].each do |id, e| e.call(ControllerButtonEvent.new(which, button)) end end end
ruby
{ "resource": "" }
q11536
Ruby2D.Window.update_callback
train
def update_callback @update_proc.call # Accept and eval commands if in console mode if @console if STDIN.ready? cmd = STDIN.gets begin res = eval(cmd, TOPLEVEL_BINDING) STDOUT.puts "=> #{res.inspect}" STDOUT.flush rescue SyntaxError => se STDOUT.puts se STDOUT.flush rescue Exception => e STDOUT.puts e STDOUT.flush end end end end
ruby
{ "resource": "" }
q11537
Ruby2D.Window.add_object
train
def add_object(o) if !@objects.include?(o) index = @objects.index do |object| object.z > o.z end if index @objects.insert(index, o) else @objects.push(o) end true else false end end
ruby
{ "resource": "" }
q11538
Scenic.Statements.create_view
train
def create_view(name, version: nil, sql_definition: nil, materialized: false) if version.present? && sql_definition.present? raise( ArgumentError, "sql_definition and version cannot both be set", ) end if version.blank? && sql_definition.blank? version = 1 end sql_definition ||= definition(name, version) if materialized Scenic.database.create_materialized_view( name, sql_definition, no_data: no_data(materialized), ) else Scenic.database.create_view(name, sql_definition) end end
ruby
{ "resource": "" }
q11539
Scenic.Statements.drop_view
train
def drop_view(name, revert_to_version: nil, materialized: false) if materialized Scenic.database.drop_materialized_view(name) else Scenic.database.drop_view(name) end end
ruby
{ "resource": "" }
q11540
Scenic.Statements.update_view
train
def update_view(name, version: nil, sql_definition: nil, revert_to_version: nil, materialized: false) if version.blank? && sql_definition.blank? raise( ArgumentError, "sql_definition or version must be specified", ) end if version.present? && sql_definition.present? raise( ArgumentError, "sql_definition and version cannot both be set", ) end sql_definition ||= definition(name, version) if materialized Scenic.database.update_materialized_view( name, sql_definition, no_data: no_data(materialized), ) else Scenic.database.update_view(name, sql_definition) end end
ruby
{ "resource": "" }
q11541
Scenic.Statements.replace_view
train
def replace_view(name, version: nil, revert_to_version: nil, materialized: false) if version.blank? raise ArgumentError, "version is required" end if materialized raise ArgumentError, "Cannot replace materialized views" end sql_definition = definition(name, version) Scenic.database.replace_view(name, sql_definition) end
ruby
{ "resource": "" }
q11542
RubyEventStore.Event.to_h
train
def to_h { event_id: event_id, metadata: metadata.to_h, data: data, type: type, } end
ruby
{ "resource": "" }
q11543
RubyEventStore.Client.publish
train
def publish(events, stream_name: GLOBAL_STREAM, expected_version: :any) enriched_events = enrich_events_metadata(events) serialized_events = serialize_events(enriched_events) append_to_stream_serialized_events(serialized_events, stream_name: stream_name, expected_version: expected_version) enriched_events.zip(serialized_events) do |event, serialized_event| with_metadata( correlation_id: event.metadata[:correlation_id] || event.event_id, causation_id: event.event_id, ) do broker.(event, serialized_event) end end self end
ruby
{ "resource": "" }
q11544
SecureHeaders.Middleware.call
train
def call(env) req = Rack::Request.new(env) status, headers, response = @app.call(env) config = SecureHeaders.config_for(req) flag_cookies!(headers, override_secure(env, config.cookies)) unless config.cookies == OPT_OUT headers.merge!(SecureHeaders.header_hash_for(req)) [status, headers, response] end
ruby
{ "resource": "" }
q11545
SecureHeaders.Middleware.override_secure
train
def override_secure(env, config = {}) if scheme(env) != "https" && config != OPT_OUT config[:secure] = OPT_OUT end config end
ruby
{ "resource": "" }
q11546
SecureHeaders.CookiesConfig.validate_samesite_boolean_config!
train
def validate_samesite_boolean_config! if config[:samesite].key?(:lax) && config[:samesite][:lax].is_a?(TrueClass) && config[:samesite].key?(:strict) raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.") elsif config[:samesite].key?(:strict) && config[:samesite][:strict].is_a?(TrueClass) && config[:samesite].key?(:lax) raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.") end end
ruby
{ "resource": "" }
q11547
SecureHeaders.CookiesConfig.validate_exclusive_use_of_hash_constraints!
train
def validate_exclusive_use_of_hash_constraints!(conf, attribute) return unless is_hash?(conf) if conf.key?(:only) && conf.key?(:except) raise CookiesConfigError.new("#{attribute} cookie config is invalid, simultaneous use of conditional arguments `only` and `except` is not permitted.") end end
ruby
{ "resource": "" }
q11548
SecureHeaders.CookiesConfig.validate_exclusive_use_of_samesite_enforcement!
train
def validate_exclusive_use_of_samesite_enforcement!(attribute) if (intersection = (config[:samesite][:lax].fetch(attribute, []) & config[:samesite][:strict].fetch(attribute, []))).any? raise CookiesConfigError.new("samesite cookie config is invalid, cookie(s) #{intersection.join(', ')} cannot be enforced as lax and strict") end end
ruby
{ "resource": "" }
q11549
SecureHeaders.ContentSecurityPolicy.reject_all_values_if_none
train
def reject_all_values_if_none(source_list) if source_list.length > 1 source_list.reject { |value| value == NONE } else source_list end end
ruby
{ "resource": "" }
q11550
SecureHeaders.ContentSecurityPolicy.dedup_source_list
train
def dedup_source_list(sources) sources = sources.uniq wild_sources = sources.select { |source| source =~ STAR_REGEXP } if wild_sources.any? sources.reject do |source| !wild_sources.include?(source) && wild_sources.any? { |pattern| File.fnmatch(pattern, source) } end else sources end end
ruby
{ "resource": "" }
q11551
Recaptcha.ClientHelper.invisible_recaptcha_tags
train
def invisible_recaptcha_tags(options = {}) options = {callback: 'invisibleRecaptchaSubmit', ui: :button}.merge options text = options.delete(:text) html, tag_attributes = Recaptcha::ClientHelper.recaptcha_components(options) html << recaptcha_default_callback(options) if recaptcha_default_callback_required?(options) case options[:ui] when :button html << %(<button type="submit" #{tag_attributes}>#{text}</button>\n) when :invisible html << %(<div data-size="invisible" #{tag_attributes}></div>\n) when :input html << %(<input type="submit" #{tag_attributes} value="#{text}"/>\n) else raise(RecaptchaError, "ReCAPTCHA ui `#{options[:ui]}` is not valid.") end html.respond_to?(:html_safe) ? html.html_safe : html end
ruby
{ "resource": "" }
q11552
Recaptcha.Verify.verify_recaptcha
train
def verify_recaptcha(options = {}) options = {model: options} unless options.is_a? Hash return true if Recaptcha::Verify.skip?(options[:env]) model = options[:model] attribute = options[:attribute] || :base recaptcha_response = options[:response] || params['g-recaptcha-response'].to_s begin verified = if recaptcha_response.empty? || recaptcha_response.length > G_RESPONSE_LIMIT false else recaptcha_verify_via_api_call(request, recaptcha_response, options) end if verified flash.delete(:recaptcha_error) if recaptcha_flash_supported? && !model true else recaptcha_error( model, attribute, options[:message], "recaptcha.errors.verification_failed", "reCAPTCHA verification failed, please try again." ) false end rescue Timeout::Error if Recaptcha.configuration.handle_timeouts_gracefully recaptcha_error( model, attribute, options[:message], "recaptcha.errors.recaptcha_unreachable", "Oops, we failed to validate your reCAPTCHA response. Please try again." ) false else raise RecaptchaError, "Recaptcha unreachable." end rescue StandardError => e raise RecaptchaError, e.message, e.backtrace end end
ruby
{ "resource": "" }
q11553
HamlLint.Configuration.for_linter
train
def for_linter(linter) linter_name = case linter when Class linter.name.split('::').last when HamlLint::Linter linter.name end @hash['linters'].fetch(linter_name, {}).dup.freeze end
ruby
{ "resource": "" }
q11554
HamlLint.Configuration.smart_merge
train
def smart_merge(parent, child) parent.merge(child) do |_key, old, new| case old when Hash smart_merge(old, new) else new end end end
ruby
{ "resource": "" }
q11555
HamlLint.Reporter::DisabledConfigReporter.display_report
train
def display_report(report) super File.write(ConfigurationLoader::AUTO_GENERATED_FILE, config_file_contents) log.log "Created #{ConfigurationLoader::AUTO_GENERATED_FILE}." log.log "Run `haml-lint --config #{ConfigurationLoader::AUTO_GENERATED_FILE}`" \ ", or add `inherits_from: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a " \ '.haml-lint.yml file.' end
ruby
{ "resource": "" }
q11556
HamlLint.Reporter::DisabledConfigReporter.finished_file
train
def finished_file(file, lints) super if lints.any? lints.each do |lint| linters_with_lints[lint.linter.name] |= [lint.filename] linters_lint_count[lint.linter.name] += 1 end end end
ruby
{ "resource": "" }
q11557
HamlLint.Reporter::DisabledConfigReporter.config_file_contents
train
def config_file_contents output = [] output << HEADING output << 'linters:' if linters_with_lints.any? linters_with_lints.each do |linter, files| output << generate_config_for_linter(linter, files) end output.join("\n\n") end
ruby
{ "resource": "" }
q11558
HamlLint.Reporter::DisabledConfigReporter.generate_config_for_linter
train
def generate_config_for_linter(linter, files) [].tap do |output| output << " # Offense count: #{linters_lint_count[linter]}" output << " #{linter}:" # disable the linter when there are many files with offenses. # exclude the affected files otherwise. if files.count > exclude_limit output << ' enabled: false' else output << ' exclude:' files.each do |filename| output << %{ - "#{filename}"} end end end.join("\n") end
ruby
{ "resource": "" }
q11559
HamlLint.Options.load_reporter_class
train
def load_reporter_class(reporter_name) HamlLint::Reporter.const_get("#{reporter_name}Reporter") rescue NameError raise HamlLint::Exceptions::InvalidCLIOption, "#{reporter_name}Reporter does not exist" end
ruby
{ "resource": "" }
q11560
HamlLint.Linter::InstanceVariables.visit_root
train
def visit_root(node) @enabled = matcher.match(File.basename(node.file)) ? true : false end
ruby
{ "resource": "" }
q11561
HamlLint.Linter::InstanceVariables.visit_tag
train
def visit_tag(node) return unless enabled? visit_script(node) || if node.parsed_attributes.contains_instance_variables? record_lint(node, "Avoid using instance variables in #{file_types} views") end end
ruby
{ "resource": "" }
q11562
HamlLint.Runner.run
train
def run(options = {}) @config = load_applicable_config(options) @files = extract_applicable_files(config, options) @linter_selector = HamlLint::LinterSelector.new(config, options) @fail_fast = options.fetch(:fail_fast, false) report(options) end
ruby
{ "resource": "" }
q11563
HamlLint.Runner.collect_lints
train
def collect_lints(file, linter_selector, config) begin document = HamlLint::Document.new(File.read(file), file: file, config: config) rescue HamlLint::Exceptions::ParseError => e return [HamlLint::Lint.new(HamlLint::Linter::Syntax.new(config), file, e.line, e.to_s, :error)] end linter_selector.linters_for_file(file).map do |linter| linter.run(document) end.flatten end
ruby
{ "resource": "" }
q11564
HamlLint.Runner.extract_applicable_files
train
def extract_applicable_files(config, options) included_patterns = options[:files] excluded_patterns = config['exclude'] excluded_patterns += options.fetch(:excluded_files, []) HamlLint::FileFinder.new(config).find(included_patterns, excluded_patterns) end
ruby
{ "resource": "" }
q11565
HamlLint.Runner.process_files
train
def process_files(report) files.each do |file| process_file(file, report) break if report.failed? && fail_fast? end end
ruby
{ "resource": "" }
q11566
HamlLint.Runner.process_file
train
def process_file(file, report) lints = collect_lints(file, linter_selector, config) lints.each { |lint| report.add_lint(lint) } report.finish_file(file, lints) end
ruby
{ "resource": "" }
q11567
HamlLint.Runner.report
train
def report(options) report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level]) report.start(@files) process_files(report) report end
ruby
{ "resource": "" }
q11568
HamlLint.FileFinder.find
train
def find(patterns, excluded_patterns) excluded_patterns = excluded_patterns.map { |pattern| normalize_path(pattern) } extract_files_from(patterns).reject do |file| excluded_patterns.any? do |exclusion_glob| HamlLint::Utils.any_glob_matches?(exclusion_glob, file) end end end
ruby
{ "resource": "" }
q11569
HamlLint.FileFinder.extract_files_from
train
def extract_files_from(patterns) # rubocop:disable MethodLength files = [] patterns.each do |pattern| if File.file?(pattern) files << pattern else begin ::Find.find(pattern) do |file| files << file if haml_file?(file) end rescue ::Errno::ENOENT # File didn't exist; it might be a file glob pattern matches = ::Dir.glob(pattern) if matches.any? files += matches else # One of the paths specified does not exist; raise a more # descriptive exception so we know which one raise HamlLint::Exceptions::InvalidFilePath, "File path '#{pattern}' does not exist" end end end end files.uniq.sort.map { |file| normalize_path(file) } end
ruby
{ "resource": "" }
q11570
HamlLint.FileFinder.haml_file?
train
def haml_file?(file) return false unless ::FileTest.file?(file) VALID_EXTENSIONS.include?(::File.extname(file)) end
ruby
{ "resource": "" }
q11571
HamlLint.Linter::UnnecessaryStringOutput.starts_with_reserved_character?
train
def starts_with_reserved_character?(stringish) string = stringish.respond_to?(:children) ? stringish.children.first : stringish string =~ %r{\A\s*[/#-=%~]} end
ruby
{ "resource": "" }
q11572
HamlLint.Linter.run
train
def run(document) @document = document @lints = [] visit(document.tree) @lints rescue Parser::SyntaxError => e location = e.diagnostic.location @lints << HamlLint::Lint.new( HamlLint::Linter::Syntax.new(config), document.file, location.line, e.to_s, :error ) end
ruby
{ "resource": "" }
q11573
HamlLint.Linter.inline_content_is_string?
train
def inline_content_is_string?(node) tag_with_inline_content = tag_with_inline_text(node) inline_content = inline_node_content(node) index = tag_with_inline_content.rindex(inline_content) - 1 %w[' "].include?(tag_with_inline_content[index]) end
ruby
{ "resource": "" }
q11574
HamlLint.Linter.inline_node_content
train
def inline_node_content(node) inline_content = node.script if contains_interpolation?(inline_content) strip_surrounding_quotes(inline_content) else inline_content end end
ruby
{ "resource": "" }
q11575
HamlLint.Linter.next_node
train
def next_node(node) return unless node siblings = node.parent ? node.parent.children : [node] next_sibling = siblings[siblings.index(node) + 1] if siblings.count > 1 return next_sibling if next_sibling next_node(node.parent) end
ruby
{ "resource": "" }
q11576
HamlLint.RubyParser.parse
train
def parse(source) buffer = ::Parser::Source::Buffer.new('(string)') buffer.source = source @parser.reset @parser.parse(buffer) end
ruby
{ "resource": "" }
q11577
HamlLint.CLI.act_on_options
train
def act_on_options(options) configure_logger(options) if options[:help] print_help(options) Sysexits::EX_OK elsif options[:version] || options[:verbose_version] print_version(options) Sysexits::EX_OK elsif options[:show_linters] print_available_linters Sysexits::EX_OK elsif options[:show_reporters] print_available_reporters Sysexits::EX_OK else scan_for_lints(options) end end
ruby
{ "resource": "" }
q11578
HamlLint.CLI.configure_logger
train
def configure_logger(options) log.color_enabled = options.fetch(:color, log.tty?) log.summary_enabled = options.fetch(:summary, true) end
ruby
{ "resource": "" }
q11579
HamlLint.CLI.handle_exception
train
def handle_exception(exception) case exception when HamlLint::Exceptions::ConfigurationError log.error exception.message Sysexits::EX_CONFIG when HamlLint::Exceptions::InvalidCLIOption log.error exception.message log.log "Run `#{APP_NAME}` --help for usage documentation" Sysexits::EX_USAGE when HamlLint::Exceptions::InvalidFilePath log.error exception.message Sysexits::EX_NOINPUT when HamlLint::Exceptions::NoLintersError log.error exception.message Sysexits::EX_NOINPUT else print_unexpected_exception(exception) Sysexits::EX_SOFTWARE end end
ruby
{ "resource": "" }
q11580
HamlLint.CLI.reporter_from_options
train
def reporter_from_options(options) if options[:auto_gen_config] HamlLint::Reporter::DisabledConfigReporter.new(log, limit: options[:auto_gen_exclude_limit] || 15) # rubocop:disable Metrics/LineLength else options.fetch(:reporter, HamlLint::Reporter::DefaultReporter).new(log) end end
ruby
{ "resource": "" }
q11581
HamlLint.CLI.scan_for_lints
train
def scan_for_lints(options) reporter = reporter_from_options(options) report = Runner.new.run(options.merge(reporter: reporter)) report.display report.failed? ? Sysexits::EX_DATAERR : Sysexits::EX_OK end
ruby
{ "resource": "" }
q11582
HamlLint.CLI.print_available_linters
train
def print_available_linters log.info 'Available linters:' linter_names = HamlLint::LinterRegistry.linters.map do |linter| linter.name.split('::').last end linter_names.sort.each do |linter_name| log.log " - #{linter_name}" end end
ruby
{ "resource": "" }
q11583
HamlLint.CLI.print_available_reporters
train
def print_available_reporters log.info 'Available reporters:' HamlLint::Reporter.available.map(&:cli_name).sort.each do |reporter_name| log.log " - #{reporter_name}" end end
ruby
{ "resource": "" }
q11584
HamlLint.CLI.print_version
train
def print_version(options) log.log "#{HamlLint::APP_NAME} #{HamlLint::VERSION}" if options[:verbose_version] log.log "haml #{Gem.loaded_specs['haml'].version}" log.log "rubocop #{Gem.loaded_specs['rubocop'].version}" log.log RUBY_DESCRIPTION end end
ruby
{ "resource": "" }
q11585
HamlLint.CLI.print_unexpected_exception
train
def print_unexpected_exception(exception) # rubocop:disable Metrics/AbcSize log.bold_error exception.message log.error exception.backtrace.join("\n") log.warning 'Report this bug at ', false log.info HamlLint::BUG_REPORT_URL log.newline log.success 'To help fix this issue, please include:' log.log '- The above stack trace' log.log '- Haml-Lint version: ', false log.info HamlLint::VERSION log.log '- Haml version: ', false log.info Gem.loaded_specs['haml'].version log.log '- RuboCop version: ', false log.info Gem.loaded_specs['rubocop'].version log.log '- Ruby version: ', false log.info RUBY_VERSION end
ruby
{ "resource": "" }
q11586
HamlLint.Document.strip_frontmatter
train
def strip_frontmatter(source) frontmatter = / # From the start of the string \A # First-capture match --- followed by optional whitespace up # to a newline then 0 or more chars followed by an optional newline. # This matches the --- and the contents of the frontmatter (---\s*\n.*?\n?) # From the start of the line ^ # Second capture match --- or ... followed by optional whitespace # and newline. This matches the closing --- for the frontmatter. (---|\.\.\.)\s*$\n?/mx if config['skip_frontmatter'] && match = source.match(frontmatter) newlines = match[0].count("\n") source.sub!(frontmatter, "\n" * newlines) end source end
ruby
{ "resource": "" }
q11587
HamlLint::Tree.Node.disabled?
train
def disabled?(visitor) visitor.is_a?(HamlLint::Linter) && comment_configuration.disabled?(visitor.name) end
ruby
{ "resource": "" }
q11588
HamlLint::Tree.Node.each
train
def each return to_enum(__callee__) unless block_given? node = self loop do yield node break unless (node = node.next_node) end end
ruby
{ "resource": "" }
q11589
HamlLint::Tree.Node.line_numbers
train
def line_numbers return (line..line) unless @value && text end_line = line + lines.count end_line = nontrivial_end_line if line == end_line (line..end_line) end
ruby
{ "resource": "" }
q11590
HamlLint::Tree.Node.nontrivial_end_line
train
def nontrivial_end_line if (last_child = children.last) last_child.line_numbers.end - 1 elsif successor successor.line_numbers.begin - 1 else @document.source_lines.count end end
ruby
{ "resource": "" }
q11591
HamlLint::Tree.RootNode.node_for_line
train
def node_for_line(line) find(-> { HamlLint::Tree::NullNode.new }) { |node| node.line_numbers.cover?(line) } end
ruby
{ "resource": "" }
q11592
HamlLint.LinterSelector.extract_enabled_linters
train
def extract_enabled_linters(config, options) included_linters = LinterRegistry.extract_linters_from(options.fetch(:included_linters, [])) included_linters = LinterRegistry.linters if included_linters.empty? excluded_linters = LinterRegistry.extract_linters_from(options.fetch(:excluded_linters, [])) # After filtering out explicitly included/excluded linters, only include # linters which are enabled in the configuration linters = (included_linters - excluded_linters).map do |linter_class| linter_config = config.for_linter(linter_class) linter_class.new(linter_config) if linter_config['enabled'] end.compact # Highlight condition where all linters were filtered out, as this was # likely a mistake on the user's part if linters.empty? raise HamlLint::Exceptions::NoLintersError, 'No linters specified' end linters end
ruby
{ "resource": "" }
q11593
HamlLint.LinterSelector.run_linter_on_file?
train
def run_linter_on_file?(config, linter, file) linter_config = config.for_linter(linter) if linter_config['include'].any? && !HamlLint::Utils.any_glob_matches?(linter_config['include'], file) return false end if HamlLint::Utils.any_glob_matches?(linter_config['exclude'], file) return false end true end
ruby
{ "resource": "" }
q11594
HamlLint::Tree.TagNode.attributes_source
train
def attributes_source @attributes_source ||= begin _explicit_tag, static_attrs, rest = source_code.scan(/\A\s*(%[-:\w]+)?([-:\w\.\#]*)(.*)/m)[0] attr_types = { '{' => [:hash, %w[{ }]], '(' => [:html, %w[( )]], '[' => [:object_ref, %w[[ ]]], } attr_source = { static: static_attrs } while rest type, chars = attr_types[rest[0]] break unless type # Not an attribute opening character, so we're done # Can't define multiple of the same attribute type (e.g. two {...}) break if attr_source[type] attr_source[type], rest = Haml::Util.balance(rest, *chars) end attr_source end end
ruby
{ "resource": "" }
q11595
HamlLint.Linter::RuboCop.find_lints
train
def find_lints(ruby, source_map) rubocop = ::RuboCop::CLI.new filename = if document.file "#{document.file}.rb" else 'ruby_script.rb' end with_ruby_from_stdin(ruby) do extract_lints_from_offenses(lint_file(rubocop, filename), source_map) end end
ruby
{ "resource": "" }
q11596
HamlLint.Linter::RuboCop.with_ruby_from_stdin
train
def with_ruby_from_stdin(ruby, &_block) original_stdin = $stdin stdin = StringIO.new stdin.write(ruby) stdin.rewind $stdin = stdin yield ensure $stdin = original_stdin end
ruby
{ "resource": "" }
q11597
HamlLint.Utils.get_abs_and_rel_path
train
def get_abs_and_rel_path(path) original_path = Pathname.new(path) root_dir_path = Pathname.new(File.expand_path(Dir.pwd)) if original_path.absolute? [path, original_path.relative_path_from(root_dir_path)] else [root_dir_path + original_path, path] end end
ruby
{ "resource": "" }
q11598
HamlLint.Utils.extract_interpolated_values
train
def extract_interpolated_values(text) # rubocop:disable Metrics/AbcSize dumped_text = text.dump newline_positions = extract_substring_positions(dumped_text, '\\\n') Haml::Util.handle_interpolation(dumped_text) do |scan| line = (newline_positions.find_index { |marker| scan.pos <= marker } || newline_positions.size) + 1 escape_count = (scan[2].size - 1) / 2 break unless escape_count.even? dumped_interpolated_str = Haml::Util.balance(scan, '{', '}', 1)[0][0...-1] # Hacky way to turn a dumped string back into a regular string yield [eval('"' + dumped_interpolated_str + '"'), line] # rubocop:disable Eval end end
ruby
{ "resource": "" }
q11599
HamlLint.Utils.for_consecutive_items
train
def for_consecutive_items(items, satisfies, min_consecutive = 2) current_index = -1 while (current_index += 1) < items.count next unless satisfies[items[current_index]] count = count_consecutive(items, current_index, &satisfies) next unless count >= min_consecutive # Yield the chunk of consecutive items yield items[current_index...(current_index + count)] current_index += count # Skip this patch of consecutive items to find more end end
ruby
{ "resource": "" }