_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q12600
I18n.Config.missing_interpolation_argument_handler
train
def missing_interpolation_argument_handler @@missing_interpolation_argument_handler ||= lambda do |missing_key, provided_hash, string| raise MissingInterpolationArgument.new(missing_key, provided_hash, string) end end
ruby
{ "resource": "" }
q12601
I18n.Base.translate
train
def translate(key = nil, *, throw: false, raise: false, locale: nil, **options) # TODO deprecate :raise locale ||= config.locale raise Disabled.new('t') if locale == false enforce_available_locales!(locale) backend = config.backend result = catch(:exception) do if key.is_a?(Array) key.map { |k| backend.translate(locale, k, options) } else backend.translate(locale, key, options) end end if result.is_a?(MissingTranslation) handle_exception((throw && :throw || raise && :raise), result, locale, key, options) else result end end
ruby
{ "resource": "" }
q12602
I18n.Base.exists?
train
def exists?(key, _locale = nil, locale: _locale) locale ||= config.locale raise Disabled.new('exists?') if locale == false raise I18n::ArgumentError if key.is_a?(String) && key.empty? config.backend.exists?(locale, key) end
ruby
{ "resource": "" }
q12603
I18n.Base.localize
train
def localize(object, locale: nil, format: nil, **options) locale ||= config.locale raise Disabled.new('l') if locale == false enforce_available_locales!(locale) format ||= :default config.backend.localize(locale, object, format, options) end
ruby
{ "resource": "" }
q12604
I18n.Base.normalize_keys
train
def normalize_keys(locale, key, scope, separator = nil) separator ||= I18n.default_separator keys = [] keys.concat normalize_key(locale, separator) keys.concat normalize_key(scope, separator) keys.concat normalize_key(key, separator) keys end
ruby
{ "resource": "" }
q12605
I18n.Base.enforce_available_locales!
train
def enforce_available_locales!(locale) if locale != false && config.enforce_available_locales raise I18n::InvalidLocale.new(locale) if !locale_available?(locale) end end
ruby
{ "resource": "" }
q12606
JekyllFeed.Generator.generate
train
def generate(site) @site = site collections.each do |name, meta| Jekyll.logger.info "Jekyll Feed:", "Generating feed for #{name}" (meta["categories"] + [nil]).each do |category| path = feed_path(:collection => name, :category => category) next if file_exists?(path) @site.pages << make_page(path, :collection => name, :category => category) end end end
ruby
{ "resource": "" }
q12607
JekyllFeed.Generator.normalize_posts_meta
train
def normalize_posts_meta(hash) hash["posts"] ||= {} hash["posts"]["path"] ||= config["path"] hash["posts"]["categories"] ||= config["categories"] config["path"] ||= hash["posts"]["path"] hash end
ruby
{ "resource": "" }
q12608
Hashie.Rash.all
train
def all(query) return to_enum(:all, query) unless block_given? if @hash.include? query yield @hash[query] return end case query when String optimize_if_necessary! # see if any of the regexps match the string @regexes.each do |regex| match = regex.match(query) next unless match @regex_counts[regex] += 1 value = @hash[regex] if value.respond_to? :call yield value.call(match) else yield value end end when Numeric # see if any of the ranges match the integer @ranges.each do |range| yield @hash[range] if range.cover? query end when Regexp # Reverse operation: `rash[/regexp/]` returns all the hash's string keys which match the regexp @hash.each do |key, val| yield val if key.is_a?(String) && query =~ key end end end
ruby
{ "resource": "" }
q12609
Hashie.Mash.custom_reader
train
def custom_reader(key) default_proc.call(self, key) if default_proc && !key?(key) value = regular_reader(convert_key(key)) yield value if block_given? value end
ruby
{ "resource": "" }
q12610
Hashie.Mash.custom_writer
train
def custom_writer(key, value, convert = true) #:nodoc: key_as_symbol = (key = convert_key(key)).to_sym log_built_in_message(key_as_symbol) if log_collision?(key_as_symbol) regular_writer(key, convert ? convert_value(value) : value) end
ruby
{ "resource": "" }
q12611
Hashie.Mash.initializing_reader
train
def initializing_reader(key) ck = convert_key(key) regular_writer(ck, self.class.new) unless key?(ck) regular_reader(ck) end
ruby
{ "resource": "" }
q12612
Hashie.Mash.underbang_reader
train
def underbang_reader(key) ck = convert_key(key) if key?(ck) regular_reader(ck) else self.class.new end end
ruby
{ "resource": "" }
q12613
Hashie.Mash.deep_update
train
def deep_update(other_hash, &blk) other_hash.each_pair do |k, v| key = convert_key(k) if v.is_a?(::Hash) && key?(key) && regular_reader(key).is_a?(Mash) custom_reader(key).deep_update(v, &blk) else value = convert_value(v, true) value = convert_value(yield(key, self[k], value), true) if blk && key?(k) custom_writer(key, value, false) end end self end
ruby
{ "resource": "" }
q12614
CounterCulture.Extensions._update_counts_after_update
train
def _update_counts_after_update self.class.after_commit_counter_cache.each do |counter| # figure out whether the applicable counter cache changed (this can happen # with dynamic column names) counter_cache_name_was = counter.counter_cache_name_for(counter.previous_model(self)) counter_cache_name = counter.counter_cache_name_for(self) if counter.first_level_relation_changed?(self) || (counter.delta_column && counter.attribute_changed?(self, counter.delta_column)) || counter_cache_name != counter_cache_name_was # increment the counter cache of the new value counter.change_counter_cache(self, :increment => true, :counter_column => counter_cache_name) # decrement the counter cache of the old value counter.change_counter_cache(self, :increment => false, :was => true, :counter_column => counter_cache_name_was) end end end
ruby
{ "resource": "" }
q12615
CounterCulture.Extensions.destroyed_for_counter_culture?
train
def destroyed_for_counter_culture? if respond_to?(:paranoia_destroyed?) paranoia_destroyed? elsif defined?(Discard::Model) && self.class.include?(Discard::Model) discarded? else false end end
ruby
{ "resource": "" }
q12616
CounterCulture.Counter.change_counter_cache
train
def change_counter_cache(obj, options) change_counter_column = options.fetch(:counter_column) { counter_cache_name_for(obj) } # default to the current foreign key value id_to_change = foreign_key_value(obj, relation, options[:was]) # allow overwriting of foreign key value by the caller id_to_change = foreign_key_values.call(id_to_change) if foreign_key_values if id_to_change && change_counter_column delta_magnitude = if delta_column (options[:was] ? attribute_was(obj, delta_column) : obj.public_send(delta_column)) || 0 else counter_delta_magnitude_for(obj) end # increment or decrement? operator = options[:increment] ? '+' : '-' # we don't use Rails' update_counters because we support changing the timestamp quoted_column = model.connection.quote_column_name(change_counter_column) updates = [] # this updates the actual counter updates << "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{delta_magnitude}" # and here we update the timestamp, if so desired if touch current_time = obj.send(:current_time_from_proper_timezone) timestamp_columns = obj.send(:timestamp_attributes_for_update_in_model) timestamp_columns << touch if touch != true timestamp_columns.each do |timestamp_column| updates << "#{timestamp_column} = '#{current_time.to_formatted_s(:db)}'" end end klass = relation_klass(relation, source: obj, was: options[:was]) primary_key = relation_primary_key(relation, source: obj, was: options[:was]) if @with_papertrail instance = klass.where(primary_key => id_to_change).first if instance if instance.paper_trail.respond_to?(:save_with_version) # touch_with_version is deprecated starting in PaperTrail 9.0.0 current_time = obj.send(:current_time_from_proper_timezone) timestamp_columns = obj.send(:timestamp_attributes_for_update_in_model) timestamp_columns.each do |timestamp_column| instance.send("#{timestamp_column}=", current_time) end instance.paper_trail.save_with_version(validate: false) else instance.paper_trail.touch_with_version end end end klass.where(primary_key => id_to_change).update_all updates.join(', ') end end
ruby
{ "resource": "" }
q12617
CounterCulture.Counter.foreign_key_value
train
def foreign_key_value(obj, relation, was = false) relation = relation.is_a?(Enumerable) ? relation.dup : [relation] first_relation = relation.first if was first = relation.shift foreign_key_value = attribute_was(obj, relation_foreign_key(first)) klass = relation_klass(first, source: obj, was: was) if foreign_key_value value = klass.where( "#{klass.table_name}.#{relation_primary_key(first, source: obj, was: was)} = ?", foreign_key_value).first end else value = obj end while !value.nil? && relation.size > 0 value = value.send(relation.shift) end return value.try(relation_primary_key(first_relation, source: obj, was: was).try(:to_sym)) end
ruby
{ "resource": "" }
q12618
CounterCulture.Counter.relation_reflect
train
def relation_reflect(relation) relation = relation.is_a?(Enumerable) ? relation.dup : [relation] # go from one relation to the next until we hit the last reflect object klass = model while relation.size > 0 cur_relation = relation.shift reflect = klass.reflect_on_association(cur_relation) raise "No relation #{cur_relation} on #{klass.name}" if reflect.nil? if relation.size > 0 # not necessary to do this at the last link because we won't use # klass again. not calling this avoids the following causing an # exception in the now-supported one-level polymorphic counter cache klass = reflect.klass end end return reflect end
ruby
{ "resource": "" }
q12619
CounterCulture.Counter.relation_klass
train
def relation_klass(relation, source: nil, was: false) reflect = relation_reflect(relation) if reflect.options.key?(:polymorphic) raise "Can't work out relation's class without being passed object (relation: #{relation}, reflect: #{reflect})" if source.nil? raise "Can't work out polymorhpic relation's class with multiple relations yet" unless (relation.is_a?(Symbol) || relation.length == 1) # this is the column that stores the polymorphic type, aka the class name type_column = reflect.foreign_type.to_sym # so now turn that into the class that we're looking for here if was attribute_was(source, type_column).try(:constantize) else source.public_send(type_column).try(:constantize) end else reflect.klass end end
ruby
{ "resource": "" }
q12620
CounterCulture.Counter.relation_primary_key
train
def relation_primary_key(relation, source: nil, was: false) reflect = relation_reflect(relation) klass = nil if reflect.options.key?(:polymorphic) raise "can't handle multiple keys with polymorphic associations" unless (relation.is_a?(Symbol) || relation.length == 1) raise "must specify source for polymorphic associations..." unless source return relation_klass(relation, source: source, was: was).try(:primary_key) end reflect.association_primary_key(klass) end
ruby
{ "resource": "" }
q12621
EraJa.Conversion.to_era
train
def to_era(format = "%o%E.%m.%d", era_names: ERA_NAME_DEFAULTS) raise EraJa::DateOutOfRangeError unless era_convertible? @era_format = format.gsub(/%J/, "%J%") str_time = strftime(@era_format) if @era_format =~ /%([EOo]|1O)/ case when self.to_time < ::Time.mktime(1912,7,30) str_time = era_year(year - 1867, :meiji, era_names) when self.to_time < ::Time.mktime(1926,12,25) str_time = era_year(year - 1911, :taisho, era_names) when self.to_time < ::Time.mktime(1989,1,8) str_time = era_year(year - 1925, :showa, era_names) when self.to_time < ::Time.mktime(2019, 5, 1) str_time = era_year(year - 1988, :heisei, era_names) else str_time = era_year(year - 2018, :reiwa, era_names) end end str_time.gsub(/%J(\d+)/) { to_kanzi($1) } end
ruby
{ "resource": "" }
q12622
IStats.Utils.abs_thresholds
train
def abs_thresholds(scale, max_value) at = [] scale.each { |v| at.push(v * max_value) } return at end
ruby
{ "resource": "" }
q12623
Cliver.Dependency.open?
train
def open? ProcTable.ps.any? { |p| p.comm == path } # See https://github.com/djberg96/sys-proctable/issues/44 rescue ArgumentError false end
ruby
{ "resource": "" }
q12624
Google.Auth.get_application_default
train
def get_application_default scope = nil, options = {} creds = DefaultCredentials.from_env(scope, options) || DefaultCredentials.from_well_known_path(scope, options) || DefaultCredentials.from_system_default_path(scope, options) return creds unless creds.nil? unless GCECredentials.on_gce? options # Clear cache of the result of GCECredentials.on_gce? GCECredentials.unmemoize_all raise NOT_FOUND_ERROR end GCECredentials.new end
ruby
{ "resource": "" }
q12625
Sprockets.DirectiveProcessor.extract_directives
train
def extract_directives(header) processed_header = String.new("") directives = [] header.lines.each_with_index do |line, index| if directive = line[DIRECTIVE_PATTERN, 1] name, *args = Shellwords.shellwords(directive) if respond_to?("process_#{name}_directive", true) directives << [index + 1, name, *args] # Replace directive line with a clean break line = "\n" end end processed_header << line end processed_header.chomp! # Ensure header ends in a new line like before it was processed processed_header << "\n" if processed_header.length > 0 && header[-1] == "\n" return processed_header, directives end
ruby
{ "resource": "" }
q12626
Rake.SprocketsTask.log_level=
train
def log_level=(level) if level.is_a?(Integer) @logger.level = level else @logger.level = Logger.const_get(level.to_s.upcase) end end
ruby
{ "resource": "" }
q12627
Rake.SprocketsTask.with_logger
train
def with_logger if env = manifest.environment old_logger = env.logger env.logger = @logger end yield ensure env.logger = old_logger if env end
ruby
{ "resource": "" }
q12628
Sprockets.Processing.register_pipeline
train
def register_pipeline(name, proc = nil, &block) proc ||= block self.config = hash_reassoc(config, :pipeline_exts) do |pipeline_exts| pipeline_exts.merge(".#{name}".freeze => name.to_sym) end self.config = hash_reassoc(config, :pipelines) do |pipelines| pipelines.merge(name.to_sym => proc) end end
ruby
{ "resource": "" }
q12629
Sprockets.Paths.prepend_path
train
def prepend_path(path) self.config = hash_reassoc(config, :paths) do |paths| path = File.expand_path(path, config[:root]).freeze paths.unshift(path) end end
ruby
{ "resource": "" }
q12630
Sprockets.Paths.append_path
train
def append_path(path) self.config = hash_reassoc(config, :paths) do |paths| path = File.expand_path(path, config[:root]).freeze paths.push(path) end end
ruby
{ "resource": "" }
q12631
Sprockets.Context.depend_on
train
def depend_on(path) if environment.absolute_path?(path) && environment.stat(path) @dependencies << environment.build_file_digest_uri(path) else resolve(path) end nil end
ruby
{ "resource": "" }
q12632
Sprockets.Context.base64_asset_data_uri
train
def base64_asset_data_uri(asset) data = Rack::Utils.escape(EncodingUtils.base64(asset.source)) "data:#{asset.content_type};base64,#{data}" end
ruby
{ "resource": "" }
q12633
Sprockets.Context.optimize_svg_for_uri_escaping!
train
def optimize_svg_for_uri_escaping!(svg) # Remove comments, xml meta, and doctype svg.gsub!(/<!--.*?-->|<\?.*?\?>|<!.*?>/m, '') # Replace consecutive whitespace and newlines with a space svg.gsub!(/\s+/, ' ') # Collapse inter-tag whitespace svg.gsub!('> <', '><') # Replace " with ' svg.gsub!(/([\w:])="(.*?)"/, "\\1='\\2'") svg.strip! end
ruby
{ "resource": "" }
q12634
Sprockets.Context.optimize_quoted_uri_escapes!
train
def optimize_quoted_uri_escapes!(escaped) escaped.gsub!('%3D', '=') escaped.gsub!('%3A', ':') escaped.gsub!('%2F', '/') escaped.gsub!('%27', "'") escaped.tr!('+', ' ') end
ruby
{ "resource": "" }
q12635
Sprockets.Manifest.compile
train
def compile(*args) unless environment raise Error, "manifest requires environment for compilation" end filenames = [] concurrent_exporters = [] assets_to_export = Concurrent::Array.new find(*args) do |asset| assets_to_export << asset end assets_to_export.each do |asset| mtime = Time.now.iso8601 files[asset.digest_path] = { 'logical_path' => asset.logical_path, 'mtime' => mtime, 'size' => asset.bytesize, 'digest' => asset.hexdigest, # Deprecated: Remove beta integrity attribute in next release. # Callers should DigestUtils.hexdigest_integrity_uri to compute the # digest themselves. 'integrity' => DigestUtils.hexdigest_integrity_uri(asset.hexdigest) } assets[asset.logical_path] = asset.digest_path filenames << asset.filename promise = nil exporters_for_asset(asset) do |exporter| next if exporter.skip?(logger) if promise.nil? promise = Concurrent::Promise.new(executor: executor) { exporter.call } concurrent_exporters << promise.execute else concurrent_exporters << promise.then { exporter.call } end end end # make sure all exporters have finished before returning the main thread concurrent_exporters.each(&:wait!) save filenames end
ruby
{ "resource": "" }
q12636
Sprockets.Manifest.remove
train
def remove(filename) path = File.join(dir, filename) gzip = "#{path}.gz" logical_path = files[filename]['logical_path'] if assets[logical_path] == filename assets.delete(logical_path) end files.delete(filename) FileUtils.rm(path) if File.exist?(path) FileUtils.rm(gzip) if File.exist?(gzip) save logger.info "Removed #{filename}" nil end
ruby
{ "resource": "" }
q12637
Sprockets.Manifest.clean
train
def clean(count = 2, age = 3600) asset_versions = files.group_by { |_, attrs| attrs['logical_path'] } asset_versions.each do |logical_path, versions| current = assets[logical_path] versions.reject { |path, _| path == current }.sort_by { |_, attrs| # Sort by timestamp Time.parse(attrs['mtime']) }.reverse.each_with_index.drop_while { |(_, attrs), index| _age = [0, Time.now - Time.parse(attrs['mtime'])].max # Keep if under age or within the count limit _age < age || index < count }.each { |(path, _), _| # Remove old assets remove(path) } end end
ruby
{ "resource": "" }
q12638
Sprockets.Manifest.save
train
def save data = json_encode(@data) FileUtils.mkdir_p File.dirname(@filename) PathUtils.atomic_write(@filename) do |f| f.write(data) end end
ruby
{ "resource": "" }
q12639
Sprockets.Manifest.exporters_for_asset
train
def exporters_for_asset(asset) exporters = [Exporters::FileExporter] environment.exporters.each do |mime_type, exporter_list| next unless asset.content_type next unless environment.match_mime_type? asset.content_type, mime_type exporter_list.each do |exporter| exporters << exporter end end exporters.uniq! exporters.each do |exporter| yield exporter.new(asset: asset, environment: environment, directory: dir) end end
ruby
{ "resource": "" }
q12640
Sprockets.Server.call
train
def call(env) start_time = Time.now.to_f time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i } unless ALLOWED_REQUEST_METHODS.include? env['REQUEST_METHOD'] return method_not_allowed_response end msg = "Served asset #{env['PATH_INFO']} -" # Extract the path from everything after the leading slash path = Rack::Utils.unescape(env['PATH_INFO'].to_s.sub(/^\//, '')) unless path.valid_encoding? return bad_request_response(env) end # Strip fingerprint if fingerprint = path_fingerprint(path) path = path.sub("-#{fingerprint}", '') end # URLs containing a `".."` are rejected for security reasons. if forbidden_request?(path) return forbidden_response(env) end if fingerprint if_match = fingerprint elsif env['HTTP_IF_MATCH'] if_match = env['HTTP_IF_MATCH'][/"(\w+)"$/, 1] end if env['HTTP_IF_NONE_MATCH'] if_none_match = env['HTTP_IF_NONE_MATCH'][/"(\w+)"$/, 1] end # Look up the asset. asset = find_asset(path) if asset.nil? status = :not_found elsif fingerprint && asset.etag != fingerprint status = :not_found elsif if_match && asset.etag != if_match status = :precondition_failed elsif if_none_match && asset.etag == if_none_match status = :not_modified else status = :ok end case status when :ok logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)" ok_response(asset, env) when :not_modified logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)" not_modified_response(env, if_none_match) when :not_found logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)" not_found_response(env) when :precondition_failed logger.info "#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)" precondition_failed_response(env) end rescue Exception => e logger.error "Error compiling asset #{path}:" logger.error "#{e.class.name}: #{e.message}" case File.extname(path) when ".js" # Re-throw JavaScript asset exceptions to the browser logger.info "#{msg} 500 Internal Server Error\n\n" return javascript_exception_response(e) when ".css" # Display CSS asset exceptions in the browser logger.info "#{msg} 500 Internal Server Error\n\n" return css_exception_response(e) else raise end end
ruby
{ "resource": "" }
q12641
Sprockets.Server.ok_response
train
def ok_response(asset, env) if head_request?(env) [ 200, headers(env, asset, 0), [] ] else [ 200, headers(env, asset, asset.length), asset ] end end
ruby
{ "resource": "" }
q12642
Refinery.Image.thumbnail
train
def thumbnail(options = {}) options = { geometry: nil, strip: false }.merge(options) geometry = convert_to_geometry(options[:geometry]) thumbnail = image thumbnail = thumbnail.thumb(geometry) if geometry thumbnail = thumbnail.strip if options[:strip] thumbnail end
ruby
{ "resource": "" }
q12643
Refinery.Image.thumbnail_dimensions
train
def thumbnail_dimensions(geometry) dimensions = ThumbnailDimensions.new(geometry, image.width, image.height) { width: dimensions.width, height: dimensions.height } end
ruby
{ "resource": "" }
q12644
Refinery.Page.reposition_parts!
train
def reposition_parts! reload.parts.each_with_index do |part, index| part.update_columns position: index end end
ruby
{ "resource": "" }
q12645
Refinery.Page.path
train
def path(path_separator: ' - ', ancestors_first: true) return title if root? chain = ancestors_first ? self_and_ancestors : self_and_ancestors.reverse chain.map(&:title).join(path_separator) end
ruby
{ "resource": "" }
q12646
Refinery.SiteBarHelper.site_bar_switch_link
train
def site_bar_switch_link link_to_if(admin?, t('.switch_to_your_website', site_bar_translate_locale_args), refinery.root_path(site_bar_translate_locale_args), 'data-turbolinks' => false) do link_to t('.switch_to_your_website_editor', site_bar_translate_locale_args), Refinery::Core.backend_path, 'data-turbolinks' => false end end
ruby
{ "resource": "" }
q12647
Refinery.ImageHelper.image_fu
train
def image_fu(image, geometry = nil, options = {}) return nil if image.blank? thumbnail_args = options.slice(:strip) thumbnail_args[:geometry] = geometry if geometry image_tag_args = (image.thumbnail_dimensions(geometry) rescue {}) image_tag_args[:alt] = image.respond_to?(:title) ? image.title : image.image_name image_tag(image.thumbnail(thumbnail_args).url, image_tag_args.merge(options)) end
ruby
{ "resource": "" }
q12648
Draper.Factory.decorate
train
def decorate(object, options = {}) return nil if object.nil? Worker.new(decorator_class, object).call(options.reverse_merge(default_options)) end
ruby
{ "resource": "" }
q12649
Draper.QueryMethods.method_missing
train
def method_missing(method, *args, &block) return super unless strategy.allowed? method object.send(method, *args, &block).decorate end
ruby
{ "resource": "" }
q12650
FriendlyId.Configuration.use
train
def use(*modules) modules.to_a.flatten.compact.map do |object| mod = get_module(object) mod.setup(@model_class) if mod.respond_to?(:setup) @model_class.send(:include, mod) unless uses? object end end
ruby
{ "resource": "" }
q12651
FriendlyId.Slugged.normalize_friendly_id
train
def normalize_friendly_id(value) value = value.to_s.parameterize value = value[0...friendly_id_config.slug_limit] if friendly_id_config.slug_limit value end
ruby
{ "resource": "" }
q12652
FriendlyId.Base.friendly_id
train
def friendly_id(base = nil, options = {}, &block) yield friendly_id_config if block_given? friendly_id_config.dependent = options.delete :dependent friendly_id_config.use options.delete :use friendly_id_config.send :set, base ? options.merge(:base => base) : options include Model end
ruby
{ "resource": "" }
q12653
FriendlyId.FinderMethods.find
train
def find(*args) id = args.first return super if args.count != 1 || id.unfriendly_id? first_by_friendly_id(id).tap {|result| return result unless result.nil?} return super if potential_primary_key?(id) raise_not_found_exception id end
ruby
{ "resource": "" }
q12654
NameEntity.PermitAlterations.valid_for_deletion?
train
def valid_for_deletion? return false if(id.nil? || sync_token.nil?) id.to_i > 0 && !sync_token.to_s.empty? && sync_token.to_i >= 0 end
ruby
{ "resource": "" }
q12655
Typhoeus.EasyFactory.get
train
def get begin easy.http_request( request.base_url.to_s, request.options.fetch(:method, :get), sanitize(request.options) ) rescue Ethon::Errors::InvalidOption => e help = provide_help(e.message.match(/:\s(\w+)/)[1]) raise $!, "#{$!}#{help}", $!.backtrace end set_callback easy end
ruby
{ "resource": "" }
q12656
Typhoeus.EasyFactory.set_callback
train
def set_callback if request.streaming? response = nil easy.on_headers do |easy| response = Response.new(Ethon::Easy::Mirror.from_easy(easy).options) request.execute_headers_callbacks(response) end request.on_body.each do |callback| easy.on_body do |chunk, easy| callback.call(chunk, response) end end else easy.on_headers do |easy| request.execute_headers_callbacks(Response.new(Ethon::Easy::Mirror.from_easy(easy).options)) end end request.on_progress.each do |callback| easy.on_progress do |dltotal, dlnow, ultotal, ulnow, easy| callback.call(dltotal, dlnow, ultotal, ulnow, response) end end easy.on_complete do |easy| request.finish(Response.new(easy.mirror.options)) Typhoeus::Pool.release(easy) if hydra && !hydra.queued_requests.empty? hydra.dequeue_many end end end
ruby
{ "resource": "" }
q12657
Typhoeus.Request.url
train
def url easy = EasyFactory.new(self).get url = easy.url Typhoeus::Pool.release(easy) url end
ruby
{ "resource": "" }
q12658
Typhoeus.Request.fuzzy_hash_eql?
train
def fuzzy_hash_eql?(left, right) return true if (left == right) (left.count == right.count) && left.inject(true) do |res, kvp| res && (kvp[1] == right[kvp[0]]) end end
ruby
{ "resource": "" }
q12659
Typhoeus.Request.set_defaults
train
def set_defaults default_user_agent = Config.user_agent || Typhoeus::USER_AGENT options[:headers] = {'User-Agent' => default_user_agent}.merge(options[:headers] || {}) options[:headers]['Expect'] ||= '' options[:verbose] = Typhoeus::Config.verbose if options[:verbose].nil? && !Typhoeus::Config.verbose.nil? options[:maxredirs] ||= 50 options[:proxy] = Typhoeus::Config.proxy unless options.has_key?(:proxy) || Typhoeus::Config.proxy.nil? end
ruby
{ "resource": "" }
q12660
Typhoeus.Expectation.and_return
train
def and_return(response=nil, &block) new_response = (response.nil? ? block : response) responses.push(*new_response) end
ruby
{ "resource": "" }
q12661
Typhoeus.Expectation.response
train
def response(request) response = responses.fetch(@response_counter, responses.last) if response.respond_to?(:call) response = response.call(request) end @response_counter += 1 response.mock = @from || true response end
ruby
{ "resource": "" }
q12662
Typhoeus.Expectation.options_match?
train
def options_match?(request) (options ? options.all?{ |k,v| request.original_options[k] == v || request.options[k] == v } : true) end
ruby
{ "resource": "" }
q12663
Typhoeus.Expectation.url_match?
train
def url_match?(request_url) case base_url when String base_url == request_url when Regexp base_url === request_url when nil true else false end end
ruby
{ "resource": "" }
q12664
Fae.FormHelper.list_order
train
def list_order(f, attribute, options) if is_association?(f, attribute) && !options[:collection] begin options[:collection] = to_class(attribute).for_fae_index rescue NameError raise "Fae::MissingCollection: `#{attribute}` isn't an orderable class, define your order using the `collection` option." end end end
ruby
{ "resource": "" }
q12665
Fae.FormHelper.set_prompt
train
def set_prompt(f, attribute, options) options[:prompt] = 'Select One' if is_association?(f, attribute) && f.object.class.reflect_on_association(attribute).macro == :belongs_to && options[:prompt].nil? && !options[:two_pane] end
ruby
{ "resource": "" }
q12666
Fae.FormHelper.language_support
train
def language_support(f, attribute, options) return if Fae.languages.blank? attribute_array = attribute.to_s.split('_') language_suffix = attribute_array.pop return unless Fae.languages.has_key?(language_suffix.to_sym) || Fae.languages.has_key?(language_suffix) label = attribute_array.push("(#{language_suffix})").join(' ').titleize options[:label] = label unless options[:label].present? if options[:wrapper_html].present? options[:wrapper_html].deep_merge!({ data: { language: language_suffix } }) else options[:wrapper_html] = { data: { language: language_suffix } } end end
ruby
{ "resource": "" }
q12667
Fae.Cloneable.update_cloneable_associations
train
def update_cloneable_associations associations_for_cloning.each do |association| type = @klass.reflect_on_association(association) through_record = type.through_reflection if through_record.present? clone_join_relationships(through_record.plural_name) else clone_has_one_relationship(association,type) if type.macro == :has_one clone_has_many_relationships(association) if type.macro == :has_many end end end
ruby
{ "resource": "" }
q12668
Savon.GlobalOptions.log_level
train
def log_level(level) levels = { :debug => 0, :info => 1, :warn => 2, :error => 3, :fatal => 4 } unless levels.include? level raise ArgumentError, "Invalid log level: #{level.inspect}\n" \ "Expected one of: #{levels.keys.inspect}" end @options[:logger].level = levels[level] end
ruby
{ "resource": "" }
q12669
Sunspot.Session.new_search
train
def new_search(*types, &block) types.flatten! search = Search::StandardSearch.new( connection, setup_for_types(types), Query::StandardQuery.new(types), @config ) search.build(&block) if block search end
ruby
{ "resource": "" }
q12670
Sunspot.Session.new_more_like_this
train
def new_more_like_this(object, *types, &block) types[0] ||= object.class mlt = Search::MoreLikeThisSearch.new( connection, setup_for_types(types), Query::MoreLikeThisQuery.new(object, types), @config ) mlt.build(&block) if block mlt end
ruby
{ "resource": "" }
q12671
Sunspot.Session.more_like_this
train
def more_like_this(object, *types, &block) mlt = new_more_like_this(object, *types, &block) mlt.execute end
ruby
{ "resource": "" }
q12672
Sunspot.Session.atomic_update
train
def atomic_update(clazz, updates = {}) @adds += updates.keys.length indexer.add_atomic_update(clazz, updates) end
ruby
{ "resource": "" }
q12673
Sunspot.Session.remove
train
def remove(*objects, &block) if block types = objects conjunction = Query::Connective::Conjunction.new if types.length == 1 conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::EqualTo, types.first) else conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::AnyOf, types) end dsl = DSL::Scope.new(conjunction, setup_for_types(types)) Util.instance_eval_or_call(dsl, &block) indexer.remove_by_scope(conjunction) else objects.flatten! @deletes += objects.length objects.each do |object| indexer.remove(object) end end end
ruby
{ "resource": "" }
q12674
Sunspot.Session.remove_by_id
train
def remove_by_id(clazz, *ids) class_name = if clazz.is_a?(Class) clazz.name else clazz.to_s end indexer.remove_by_id(class_name, ids) end
ruby
{ "resource": "" }
q12675
Sunspot.Session.remove_all
train
def remove_all(*classes) classes.flatten! if classes.empty? @deletes += 1 indexer.remove_all else @deletes += classes.length classes.each { |clazz| indexer.remove_all(clazz) } end end
ruby
{ "resource": "" }
q12676
Sunspot.Session.connection
train
def connection @connection ||= self.class.connection_class.connect( url: config.solr.url, read_timeout: config.solr.read_timeout, open_timeout: config.solr.open_timeout, proxy: config.solr.proxy, update_format: config.solr.update_format || :xml ) end
ruby
{ "resource": "" }
q12677
Sunspot.Schema.dynamic_fields
train
def dynamic_fields fields = [] variant_combinations.each do |field_variants| FIELD_TYPES.each do |type| fields << DynamicField.new(type, field_variants) end end fields end
ruby
{ "resource": "" }
q12678
Sunspot.Schema.to_xml
train
def to_xml template_path = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'schema.xml.erb') template_text = File.read(template_path) erb = if RUBY_VERSION >= '2.6' ERB.new(template_text, trim_mode: '-') else ERB.new(template_text, nil, '-') end erb.result(binding) end
ruby
{ "resource": "" }
q12679
Sunspot.Schema.variant_combinations
train
def variant_combinations combinations = [] 0.upto(2 ** FIELD_VARIANTS.length - 1) do |b| combinations << combination = [] FIELD_VARIANTS.each_with_index do |variant, i| combination << variant if b & 1<<i > 0 end end combinations end
ruby
{ "resource": "" }
q12680
Sunspot.CompositeSetup.text_fields
train
def text_fields(field_name) if text_fields = text_fields_hash[field_name.to_sym] text_fields.to_a else raise( UnrecognizedFieldError, "No text field configured for #{@types * ', '} with name '#{field_name}'" ) end end
ruby
{ "resource": "" }
q12681
Sunspot.CompositeSetup.text_fields_hash
train
def text_fields_hash @text_fields_hash ||= setups.inject({}) do |hash, setup| setup.all_text_fields.each do |text_field| (hash[text_field.name] ||= Set.new) << text_field end hash end end
ruby
{ "resource": "" }
q12682
Sunspot.CompositeSetup.fields_hash
train
def fields_hash @fields_hash ||= begin field_sets_hash = Hash.new { |h, k| h[k] = Set.new } @types.each do |type| Setup.for(type).fields.each do |field| field_sets_hash[field.name.to_sym] << field end end fields_hash = {} field_sets_hash.each_pair do |field_name, set| if set.length == 1 fields_hash[field_name] = set.to_a.first end end fields_hash end end
ruby
{ "resource": "" }
q12683
Sunspot.Setup.add_text_field_factory
train
def add_text_field_factory(name, options = {}, &block) stored, more_like_this = options[:stored], options[:more_like_this] field_factory = FieldFactory::Static.new(name, Type::TextType.instance, options, &block) @text_field_factories[name] = field_factory @text_field_factories_cache[field_factory.name] = field_factory if stored @stored_field_factories_cache[field_factory.name] << field_factory end if more_like_this @more_like_this_field_factories_cache[field_factory.name] << field_factory end end
ruby
{ "resource": "" }
q12684
Sunspot.Setup.add_dynamic_field_factory
train
def add_dynamic_field_factory(name, type, options = {}, &block) stored, more_like_this = options[:stored], options[:more_like_this] field_factory = FieldFactory::Dynamic.new(name, type, options, &block) @dynamic_field_factories[field_factory.signature] = field_factory @dynamic_field_factories_cache[field_factory.name] = field_factory if stored @stored_field_factories_cache[field_factory.name] << field_factory end if more_like_this @more_like_this_field_factories_cache[field_factory.name] << field_factory end end
ruby
{ "resource": "" }
q12685
Sunspot.Setup.all_more_like_this_fields
train
def all_more_like_this_fields @more_like_this_field_factories_cache.values.map do |field_factories| field_factories.map { |field_factory| field_factory.build } end.flatten end
ruby
{ "resource": "" }
q12686
Sunspot.Setup.all_field_factories
train
def all_field_factories all_field_factories = [] all_field_factories.concat(field_factories).concat(text_field_factories).concat(dynamic_field_factories) all_field_factories end
ruby
{ "resource": "" }
q12687
Sunspot.Indexer.add_atomic_update
train
def add_atomic_update(clazz, updates={}) documents = updates.map { |id, m| prepare_atomic_update(clazz, id, m) } add_batch_documents(documents) end
ruby
{ "resource": "" }
q12688
Sunspot.Indexer.remove
train
def remove(*models) @connection.delete_by_id( models.map { |model| Adapters::InstanceAdapter.adapt(model).index_id } ) end
ruby
{ "resource": "" }
q12689
Sunspot.Indexer.remove_by_id
train
def remove_by_id(class_name, *ids) ids.flatten! @connection.delete_by_id( ids.map { |id| Adapters::InstanceAdapter.index_id_for(class_name, id) } ) end
ruby
{ "resource": "" }
q12690
Sunspot.Indexer.prepare_full_update
train
def prepare_full_update(model) document = document_for_full_update(model) setup = setup_for_object(model) if boost = setup.document_boost_for(model) document.attrs[:boost] = boost end setup.all_field_factories.each do |field_factory| field_factory.populate_document(document, model) end document end
ruby
{ "resource": "" }
q12691
Sunspot.Indexer.document_for_full_update
train
def document_for_full_update(model) RSolr::Xml::Document.new( id: Adapters::InstanceAdapter.adapt(model).index_id, type: Util.superclasses_for(model.class).map(&:name) ) end
ruby
{ "resource": "" }
q12692
Phonelib.PhoneAnalyzer.analyze
train
def analyze(phone, passed_country) country = country_or_default_country passed_country result = parse_country(phone, country) d_result = case when result && result.values.find { |e| e[:valid].any? } # all is good, return result when passed_country.nil? # trying for all countries if no country was passed detect_and_parse(phone, country) when country_can_dp?(country) # if country allows double prefix trying modified phone parse_country(changed_dp_phone(country, phone), country) end better_result(result, d_result) end
ruby
{ "resource": "" }
q12693
Phonelib.PhoneAnalyzer.better_result
train
def better_result(base_result, result = nil) base_result ||= {} return base_result unless result return result unless base_result.values.find { |e| e[:possible].any? } return result if result.values.find { |e| e[:valid].any? } base_result end
ruby
{ "resource": "" }
q12694
Phonelib.PhoneAnalyzer.with_replaced_national_prefix
train
def with_replaced_national_prefix(phone, data) return phone unless data[Core::NATIONAL_PREFIX_TRANSFORM_RULE] pattern = cr("^(?:#{data[Core::NATIONAL_PREFIX_FOR_PARSING]})") match = phone.match pattern if match && match.captures.compact.size > 0 phone.gsub(pattern, data[Core::NATIONAL_PREFIX_TRANSFORM_RULE]) else phone end end
ruby
{ "resource": "" }
q12695
Phonelib.PhoneAnalyzer.parse_country
train
def parse_country(phone, country) data = Phonelib.phone_data[country] return nil unless data # if country was provided and it's a valid country, trying to # create e164 representation of phone number, # kind of normalization for parsing e164 = convert_to_e164 with_replaced_national_prefix(phone, data), data # if phone starts with international prefix of provided # country try to reanalyze without international prefix for # all countries return analyze(e164[1..-1], nil) if Core::PLUS_SIGN == e164[0] # trying to parse number for provided country parse_single_country e164, data end
ruby
{ "resource": "" }
q12696
Phonelib.PhoneAnalyzer.parse_single_country
train
def parse_single_country(e164, data) valid_match = phone_match_data?(e164, data) if valid_match national_and_data(data, valid_match) else possible_match = phone_match_data?(e164, data, true) possible_match && national_and_data(data, possible_match, true) end end
ruby
{ "resource": "" }
q12697
Phonelib.PhoneAnalyzer.detect_and_parse
train
def detect_and_parse(phone, country) result = {} Phonelib.phone_data.each do |key, data| parsed = parse_single_country(phone, data) if (!Phonelib.strict_double_prefix_check || key == country) && double_prefix_allowed?(data, phone, parsed && parsed[key]) parsed = parse_single_country(changed_dp_phone(key, phone), data) end result.merge!(parsed) unless parsed.nil? end result end
ruby
{ "resource": "" }
q12698
Phonelib.PhoneAnalyzer.convert_to_e164
train
def convert_to_e164(phone, data) match = phone.match full_regex_for_data(data, Core::VALID_PATTERN, !original_starts_with_plus?) case when match "#{data[Core::COUNTRY_CODE]}#{match.to_a.last}" when phone.match(cr("^#{data[Core::INTERNATIONAL_PREFIX]}")) phone.sub(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"), Core::PLUS_SIGN) when original_starts_with_plus? && phone.start_with?(data[Core::COUNTRY_CODE]) phone else "#{data[Core::COUNTRY_CODE]}#{phone}" end end
ruby
{ "resource": "" }
q12699
Phonelib.PhoneAnalyzer.national_and_data
train
def national_and_data(data, country_match, not_valid = false) result = data.select { |k, _v| k != :types && k != :formats } phone = country_match.to_a.last result[:national] = phone result[:format] = number_format(phone, data[Core::FORMATS]) result.merge! all_number_types(phone, data[Core::TYPES], not_valid) result[:valid] = [] if not_valid { result[:id] => result } end
ruby
{ "resource": "" }