_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q400
Tandem.PagesHelper.tandem_navigation_tag
train
def tandem_navigation_tag(active_page, pages_collection = nil, html_options = {}) html_options, pages_collection = pages_collection, nil if pages_collection.is_a?(Hash) html_options[:class] ||= 'nav' page_groups = (pages_collection || Page.all).inject({}) do |groups, page| if groups[page.parent_id.to_s] groups[page.parent_id.to_s] << page else groups[page.parent_id.to_s] = [page] end groups end # generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope generate = nil iterate = Proc.new do |parent_id| #very important to delete the group from the collection, or it is possible users can create looping relationships (page_groups.delete(parent_id.to_s) || {}).inject(''.html_safe) do |buffer, page| buffer + generate.call(page) end end generate = Proc.new do |page| content_tag_for(:li, page, :tandem, class: "#{page == active_page ? 'active' : ''}") do link_to(page.link_label, tandem.page_path(page), class: "#{page == active_page ? 'active' : ''}") + content_tag(:ul) do iterate.call(page.id) end end end content_tag(:ul, html_options) do iterate.call(page_groups.keys.first) end end
ruby
{ "resource": "" }
q401
Cryptoprocessing.Connection.get
train
def get(path, params = {}) uri = path if params.count > 0 uri += "?#{URI.encode_www_form(params)}" end headers = {} request('GET', uri, nil, headers) do |resp| if params[:fetch_all] == true && resp.body.has_key?('pagination') && resp.body['pagination']['next_uri'] != nil params[:starting_after] = resp.body['data'].last['id'] get(path, params) do |page| body = resp.body body['data'] += page.data resp.body = body yield(resp) if block_given? end else yield(resp) if block_given? end end end
ruby
{ "resource": "" }
q402
Cryptoprocessing.Connection.put
train
def put(path, params) headers = {} request('PUT', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
ruby
{ "resource": "" }
q403
Cryptoprocessing.Connection.post
train
def post(path, params) headers = {} request('POST', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
ruby
{ "resource": "" }
q404
Cryptoprocessing.Connection.delete
train
def delete(path, params) headers = {} request('DELETE', path, nil, headers) do |resp| yield(resp) if block_given? end end
ruby
{ "resource": "" }
q405
Pollster.Api.charts_slug_get
train
def charts_slug_get(slug, opts = {}) data, _status_code, _headers = charts_slug_get_with_http_info(slug, opts) return data end
ruby
{ "resource": "" }
q406
Pollster.Api.polls_slug_get
train
def polls_slug_get(slug, opts = {}) data, _status_code, _headers = polls_slug_get_with_http_info(slug, opts) return data end
ruby
{ "resource": "" }
q407
CurrencyConverter.XE.exchange_rate
train
def exchange_rate url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}" uri = URI.parse('https://www.xe.com') request = Net::HTTP.new(uri.host, uri.port) request.use_ssl = true response = request.get(url) doc = Nokogiri::HTML(response.body) result = doc.css('span.uccResultAmount').text regexp = Regexp.new('(\\d+(?:\\.\\d+)?)') regexp.match result return $1 rescue Timeout::Error raise StandardError, 'Please check your internet connection' end
ruby
{ "resource": "" }
q408
Krikri.Logger.log
train
def log(priority, msg) @logger.tagged(Time.now.to_s, Process.pid, to_s) do @logger.send(priority, msg) end end
ruby
{ "resource": "" }
q409
Breasal.LatLng.to_WGS84
train
def to_WGS84 if @type == :ie @a = 6377340.189 @b = 6356034.447 else @a = 6377563.396 @b = 6356256.909 end @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @phi = deg_to_rad(@latitude) @lambda = deg_to_rad(@longitude) @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phi))) @H = 0 @x = (@v + @H) * Math.cos(@phi) * Math.cos(@lambda) @y = (@v + @H) * Math.cos(@phi) * Math.sin(@lambda) @z = ((1 - @eSquared) * @v + @H) * Math.sin(@phi) @tx = 446.448 @ty = -124.157 @tz = 542.060 @s = -0.0000204894 @rx = deg_to_rad( 0.00004172222) @ry = deg_to_rad( 0.00006861111) @rz = deg_to_rad( 0.00023391666) @xB = @tx + (@x * (1 + @s)) + (-@rx * @y) + (@ry * @z) @yB = @ty + (@rz * @x) + (@y * (1 + @s)) + (-@rx * @z) @zB = @tz + (-@ry * @x) + (@rx * @y) + (@z * (1 + @s)) @a = 6378137.000 @b = 6356752.3141 @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @lambdaB = rad_to_deg(Math.atan(@yB / @xB)) @p = Math.sqrt((@xB * @xB) + (@yB * @yB)) @phiN = Math.atan(@zB / (@p * (1 - @eSquared))) (1..10).each do |i| @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phiN))) @phiN1 = Math.atan((@zB + (@eSquared * @v * Math.sin(@phiN))) / @p) @phiN = @phiN1 end @phiB = rad_to_deg(@phiN) { :latitude => @phiB, :longitude => @lambdaB } end
ruby
{ "resource": "" }
q410
Krikri::Enrichments.TimespanSplit.populate_timespan
train
def populate_timespan(timespan) return timespan unless (timespan.begin.empty? || timespan.end.empty?) && !timespan.providedLabel.empty? parsed = parse_labels(timespan.providedLabel) return timespan if parsed.empty? parsed.each do |date| begin_date, end_date = span_from_date(date) timespan.begin << begin_date timespan.end << end_date end reduce_to_largest_span(timespan) return timespan end
ruby
{ "resource": "" }
q411
Krikri::Enrichments.TimespanSplit.span_from_date
train
def span_from_date(date) return [nil, nil] if date.nil? if date.is_a?(Date) return [date, date] if date.precision == :day return [date, (date.succ - 1)] end [(date.respond_to?(:first) ? date.first : date.from), (date.respond_to?(:last) ? date.last : date.to)] end
ruby
{ "resource": "" }
q412
Krikri::Enrichments.TimespanSplit.reduce_to_largest_span
train
def reduce_to_largest_span(timespan) timespan.begin = timespan.begin.sort.first timespan.end = timespan.end.sort.last timespan end
ruby
{ "resource": "" }
q413
Krikri.Activity.run
train
def run if block_given? update_attribute(:end_time, nil) if ended? Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is running") set_start_time begin yield agent_instance, rdf_subject rescue => e Krikri::Logger.log(:error, "Error performing Activity: #{id}\n" \ "#{e.message}\n#{e.backtrace}") raise e ensure set_end_time Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is done") end end end
ruby
{ "resource": "" }
q414
Emailvision.Api.close_connection
train
def close_connection if connected? get.connect.close.call else return false end rescue Emailvision::Exception => e ensure invalidate_token! not connected? end
ruby
{ "resource": "" }
q415
Prowly.Interface.call
train
def call(command, params) @command = command request = Net::HTTP::Get.new(uri.request_uri + "?" + params) response = http.request(request) Response.new(response.body, response) end
ruby
{ "resource": "" }
q416
Krikri.SearchIndexDocument.aggregation
train
def aggregation agg = DPLA::MAP::Aggregation.new(id) return nil unless agg.exists? agg.get agg end
ruby
{ "resource": "" }
q417
RenderInheritable.ClassMethods.find_inheritable_template_folder
train
def find_inheritable_template_folder(view_context, name, partial, formats, param = nil) find_inheritable_template_folder_cached(view_context, name, partial, formats, param) do find_inheritable_artifact(param) do |folder| view_context.template_exists?(name, folder, partial) end end end
ruby
{ "resource": "" }
q418
RenderInheritable.ClassMethods.inheritance_lookup_path
train
def inheritance_lookup_path path = [self] until path.last == inheritable_root_controller path << path.last.superclass end path.collect(&:controller_path) end
ruby
{ "resource": "" }
q419
RenderInheritable.ClassMethods.find_inheritable_template_folder_cached
train
def find_inheritable_template_folder_cached(view_context, name, partial, formats, param = nil) prefix = inheritable_cache_get(formats, name, partial, param) return prefix if prefix prefix = yield if prefix template = view_context.find_template_without_lookup(name, prefix, partial) inheritable_cache_set(template.formats, name, partial, param, prefix) end prefix end
ruby
{ "resource": "" }
q420
RenderInheritable.ClassMethods.inheritable_cache
train
def inheritable_cache #:nodoc: # do not store keys on each access, only return default structure @inheritable_cache ||= Hash.new do |h1, k1| Hash.new do |h2, k2| Hash.new do |h3, k3| Hash.new end end end end
ruby
{ "resource": "" }
q421
RenderInheritable.ClassMethods.inheritable_cache_get
train
def inheritable_cache_get(formats, name, partial, param) prefixes = formats.collect { |format| inheritable_cache[format.to_sym][partial][name][param] } prefixes.compact! prefixes.empty? ? nil : prefixes.first end
ruby
{ "resource": "" }
q422
RenderInheritable.ClassMethods.inheritable_cache_set
train
def inheritable_cache_set(formats, name, partial, param, prefix) formats.each do |format| # assign hash default values to respective key inheritable_cache[format.to_sym] = hf = inheritable_cache[format.to_sym] hf[partial] = hp = hf[partial] hp[name] = hn = hp[name] # finally store prefix in the deepest hash hn[param] = prefix end end
ruby
{ "resource": "" }
q423
RenderInheritable.View.find_template_with_lookup
train
def find_template_with_lookup(name, prefix = nil, partial = false) if prefix == controller_path folder = controller.find_inheritable_template_folder(name, partial) prefix = folder if folder end find_template_without_lookup(name, prefix, partial) end
ruby
{ "resource": "" }
q424
MeterCat.Cache.add
train
def add(name, value, created_on) meter = fetch(name, nil) # If the name isn't cached, cache it and return return cache(name, value, created_on) unless meter # If the cached value is for a different day, flush it, cache the new value and return if meter.created_on != created_on flush(name) cache(name, value, created_on) return end # Add the new value to the cached value and flush if expired meter.value += value flush(name) if meter.expired? end
ruby
{ "resource": "" }
q425
MeterCat.Cache.cache
train
def cache(name, value, created_on) meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now) store(name, meter) end
ruby
{ "resource": "" }
q426
Krikri.MappingDSL.add_child
train
def add_child(name, opts = {}, &block) delete_property(name) properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block) end
ruby
{ "resource": "" }
q427
Krikri.MappingDSL.add_property
train
def add_property(name, value = nil, &block) delete_property(name) properties << PropertyDeclaration.new(name, value, &block) end
ruby
{ "resource": "" }
q428
Nesser.Packet.to_bytes
train
def to_bytes() packer = Packer.new() full_flags = ((@qr << 15) & 0x8000) | ((@opcode << 11) & 0x7800) | ((@flags << 7) & 0x0780) | ((@rcode << 0) & 0x000F) packer.pack('nnnnnn', @trn_id, # trn_id full_flags, # qr, opcode, flags, rcode @questions.length(), # qdcount @answers.length(), # ancount 0, # nscount (we don't handle) 0, # arcount (we don't handle) ) questions.each do |q| q.pack(packer) end answers.each do |a| a.pack(packer) end return packer.get() end
ruby
{ "resource": "" }
q429
EspnRb.Headline.get_results
train
def get_results(resource, method) http = Net::HTTP.new("api.espn.com") request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}") HeadlineResponse.new JSON.parse(http.request(request).body) end
ruby
{ "resource": "" }
q430
Krikri::Util.ExtendedDateParser.parse
train
def parse(date_str, allow_interval = false) str = preprocess(date_str.dup) date = parse_interval(str) if allow_interval date ||= parse_m_d_y(str) date ||= Date.edtf(str.gsub('.', '-')) date ||= partial_edtf(str) date ||= decade_hyphen(str) date ||= month_year(str) date ||= decade_s(str) date ||= hyphenated_partial_range(str) date ||= parse_date(str) # Only do this if certian letters are present to avoid infinite loops. date ||= circa(str) if str.match(/[circabout]/i) date = date.first if date.is_a? EDTF::Set date || nil end
ruby
{ "resource": "" }
q431
Krikri::Util.ExtendedDateParser.range_match
train
def range_match(str) str = str.gsub('to', '-').gsub('until', '-') regexp = %r{ ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) \s*[-\.]+\s* ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) }x regexp.match(str) do |m| [m[1], m[2]] end end
ruby
{ "resource": "" }
q432
Krikri::Util.ExtendedDateParser.preprocess
train
def preprocess(str) str.gsub!(/late/i, '') str.gsub!(/early/i, '') str.strip! str.gsub!(/\s+/, ' ') str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/) str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/) str end
ruby
{ "resource": "" }
q433
Krikri::Util.ExtendedDateParser.circa
train
def circa(str) run = str.gsub!(/.*c[irca\.]*/i, '') run ||= str.gsub!(/.*about/i, '') date = parse(str) if run return nil if date.nil? # The EDTF grammar does not support uncertainty on masked precision dates if date.respond_to? :uncertain! date.uncertain! elsif date.is_a? EDTF::Interval # Interval uncertainty is scoped to the begin and end dates; # to be safe, we mark both. date.from = date.from.uncertain! if date.from.respond_to? :uncertain! date.to = date.to.uncertain! if date.to.respond_to? :uncertain! end date end
ruby
{ "resource": "" }
q434
ShadowPuppet.Manifest.execute
train
def execute(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e false else not transaction.any_failed? ensure @executed = true end
ruby
{ "resource": "" }
q435
ShadowPuppet.Manifest.execute!
train
def execute!(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e raise e else not transaction.any_failed? ensure @executed = true end
ruby
{ "resource": "" }
q436
ShadowPuppet.Manifest.evaluate_recipes
train
def evaluate_recipes self.class.recipes.each do |meth, args| case arity = method(meth).arity when 1, -1 send(meth, args) else send(meth) end end end
ruby
{ "resource": "" }
q437
ShadowPuppet.Manifest.reference
train
def reference(type, title, params = {}) Puppet::Resource.new(type.name.to_s.capitalize, title.to_s) end
ruby
{ "resource": "" }
q438
ShadowPuppet.Manifest.add_resource
train
def add_resource(type, title, params = {}) catalog.add_resource(new_resource(type, title, params)) end
ruby
{ "resource": "" }
q439
Krikri.ReportsController.index
train
def index @current_provider = params[:provider] report = Krikri::ValidationReport.new report.provider_id = @current_provider @validation_reports = report.all if @current_provider @provider = Krikri::Provider.find(@current_provider) @qa_reports = Array(Krikri::QAReport.find_by(provider: @current_provider)) else @qa_reports = Krikri::QAReport.all end end
ruby
{ "resource": "" }
q440
AlphaCard.Order.attributes_for_request
train
def attributes_for_request(*) attributes = filled_attributes.dup billing = attributes.delete(:billing) attributes.merge!(billing.attributes_for_request) if billing shipping = attributes.delete(:shipping) attributes.merge!(shipping.attributes_for_request) if shipping super(attributes) end
ruby
{ "resource": "" }
q441
EasyRSA.Revoke.revoke!
train
def revoke!(cakey=nil, crl=nil, next_update=36000) if cakey.nil? fail EasyRSA::Revoke::MissingCARootKey, 'Please provide the root CA cert for the CRL' end # Get cert details if it's in a file unless cakey.is_a? OpenSSL::PKey::RSA if cakey.include?('BEGIN RSA PRIVATE KEY') cakey = OpenSSL::PKey::RSA.new cakey else begin cakey = OpenSSL::PKey::RSA.new File.read cakey rescue OpenSSL::PKey::RSAError => e fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end end end # This is not a private key unless cakey.private? fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end # Create or load the CRL unless crl.nil? begin @crl = OpenSSL::X509::CRL.new crl rescue fail EasyRSA::Revoke::InvalidCertificateRevocationList, 'Invalid CRL provided.' end else @crl = OpenSSL::X509::CRL.new end # Add the revoked cert @crl.add_revoked(@revoked) # Needed CRL options @crl.last_update = @revoked.time @crl.next_update = Time.now + next_update @crl.version = 1 # Update the CRL issuer @crl.issuer = EasyRSA::gen_issuer # Sign the CRL @updated_crl = @crl.sign(cakey, OpenSSL::Digest::SHA256.new) @updated_crl end
ruby
{ "resource": "" }
q442
Dux.Enum.with_return_type
train
def with_return_type(value) if value.nil? && allow_nil? if allow_nil? nil else # :nocov: raise ArgumentError, "Cannot return `nil` without allow_nil: true" # :nocov: end elsif @return_type == :symbol value.to_sym elsif @return_type == :string value.to_s end end
ruby
{ "resource": "" }
q443
Dux.Enum.valid_fallback?
train
def valid_fallback?(fallback) return true if fallback.nil? && allow_nil? return true if include? fallback false end
ruby
{ "resource": "" }
q444
Dux.Enum.set_default
train
def set_default(fallback) if valid_fallback?(fallback) || fallback == NO_DEFAULT @default = fallback else raise InvalidFallback, "Cannot set #{fallback.inspect} as default", caller end end
ruby
{ "resource": "" }
q445
ActiveProfiling.GCStatistics.gc_statistics
train
def gc_statistics(*args) options = Rails.application.config.active_profiling.gc_statistics.merge(args.extract_options!) result, gc_report = gc_statistics_report(options) do yield end ActiveSupport::Notifications.instrument('gc_statistics.active_profiling', { :report => gc_report, :title => options[:title] || args.first }) result end
ruby
{ "resource": "" }
q446
Zack.Server.process_request
train
def process_request(control, sym, args) instance = factory.call(control) instance.send(sym, *args) end
ruby
{ "resource": "" }
q447
Zack.Server.exception_handling
train
def exception_handling(exception_handler, control) begin yield rescue => exception # If we have an exception handler, it gets handed all the exceptions. # No exceptions stop the operation. if exception_handler exception_handler.call(exception, control) else raise end end end
ruby
{ "resource": "" }
q448
Krikri::LDP.RdfSource.save_with_provenance
train
def save_with_provenance(activity_uri) predicate = exists? ? REVISED_URI : GENERATED_URI self << RDF::Statement(self, predicate, activity_uri) save end
ruby
{ "resource": "" }
q449
Krikri.EntityConsumer.assign_generator_activity!
train
def assign_generator_activity!(opts) if opts.include?(:generator_uri) generator_uri = opts.delete(:generator_uri) @entity_source = @generator_activity = Krikri::Activity.from_uri(generator_uri) end end
ruby
{ "resource": "" }
q450
DeepClonable.InstanceMethods.deep_vars
train
def deep_vars instance_variables.select do |var| value = instance_variable_get(var) value.kind_of?(Array) or value.kind_of?(Hash) or value.kind_of?(DeepClonable::InstanceMethods) end end
ruby
{ "resource": "" }
q451
GoogleReaderApi.Api.post_request
train
def post_request(url,args) uri = URI.parse(url) req = Net::HTTP::Post.new(uri.path) req.set_form_data(args) request(uri,req) end
ruby
{ "resource": "" }
q452
Rubinius.Tuple.swap
train
def swap(a, b) temp = at(a) put a, at(b) put b, temp end
ruby
{ "resource": "" }
q453
Vnstat.Utils.system_call
train
def system_call(*args) result = SystemCall.call(*args) return result.success_result if result.success? return yield(result.error_result) if block_given? result.error_result end
ruby
{ "resource": "" }
q454
Splib.Monitor.signal
train
def signal synchronize do while(t = @threads.shift) if(t && t.alive? && t.stop?) t.wakeup break else next end end end end
ruby
{ "resource": "" }
q455
Splib.Monitor.broadcast
train
def broadcast synchronize do @threads.dup.each do |t| t.wakeup if t.alive? && t.stop? end end end
ruby
{ "resource": "" }
q456
Splib.Monitor.try_lock
train
def try_lock locked = false Thread.exclusive do clean unless(locked?(false)) do_lock locked = true else locked = owner?(Thread.current) end end locked end
ruby
{ "resource": "" }
q457
Splib.Monitor.clean
train
def clean @locks.delete_if{|t|!t.alive?} if(@lock_owner && !@lock_owner.alive?) @lock_owner = @locks.empty? ? nil : @locks.shift @lock_owner.wakeup if @lock_owner && !owner?(Thread.current) end end
ruby
{ "resource": "" }
q458
Splib.Monitor.do_unlock
train
def do_unlock unless(owner?(Thread.current)) raise ThreadError.new("Thread #{Thread.current} is not the current owner: #{@lock_owner}") end Thread.exclusive do @locks.delete_if{|t|!t.alive?} unless(@locks.empty?) old_owner = @lock_owner @lock_owner = @locks.shift @lock_owner.wakeup unless old_owner == @lock_owner else @lock_owner = nil end end end
ruby
{ "resource": "" }
q459
Splib.Monitor.start_timer
train
def start_timer @timer = Thread.new do begin until(@stop) do cur = [] t = 0.0 Thread.exclusive do t = @timers.values.min cur = @timers.dup end t = 0.0 if !t.nil? && t < 0.0 a = 0.0 begin a = Splib.sleep(t) rescue Wakeup # do nothing of importance ensure next if t.nil? Thread.exclusive do cur.each_pair do |thread, value| value -= a if(value <= 0.0) thread.wakeup @timers.delete(thread) else @timers[thread] = value end end end end end rescue retry end end end
ruby
{ "resource": "" }
q460
AlphaCard.Resource.attributes_for_request
train
def attributes_for_request(attrs = filled_attributes) return attrs if self.class::ORIGIN_TRANSACTION_VARIABLES.empty? attrs.each_with_object({}) do |(attr, value), request_attrs| request_attrs[self.class::ORIGIN_TRANSACTION_VARIABLES.fetch(attr, attr)] = value end end
ruby
{ "resource": "" }
q461
AlphaCard.Resource.validate_required_attributes!
train
def validate_required_attributes! unless required_attributes? blank_attribute = required_attributes.detect { |attr| self[attr].nil? || self[attr].empty? } raise ValidationError, "#{blank_attribute} can't be blank" end end
ruby
{ "resource": "" }
q462
Elastics.UtilityMethods.dump_one
train
def dump_one(*vars) refresh_index(*vars) document = search_by_id({:params => {:_source => '*'}}, *vars) document.delete('_score') document end
ruby
{ "resource": "" }
q463
Elastics.UtilityMethods.post_bulk_collection
train
def post_bulk_collection(collection, options={}) raise ArgumentError, "Array expected as :collection, got #{collection.inspect}" \ unless collection.is_a?(Array) bulk_string = '' collection.each do |d| bulk_string << build_bulk_string(d, options) end post_bulk_string(:bulk_string => bulk_string) unless bulk_string.empty? end
ruby
{ "resource": "" }
q464
DictionaryRB.Dictionary.examples
train
def examples @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @example_results ||= @doc.css('.exsentences').map{ |x| x.text.strip }.reject(&:empty?).flatten @example_results #to prevent above computations on repeated call on object end
ruby
{ "resource": "" }
q465
DictionaryRB.Dictionary.similar_words
train
def similar_words @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @similar_words = @doc.css("#relatedwords .fla a").map(&:text).reject(&:empty?) @similar_words end
ruby
{ "resource": "" }
q466
Krikri.RandomSearchIndexDocumentBuilder.query_params
train
def query_params params = { :id => '*:*', :sort => "random_#{rand(9999)} desc", :rows => 1 } return params unless provider_id.present? provider = RDF::URI(Krikri::Provider.base_uri) / provider_id params[:fq] = "provider_id:\"#{provider}\"" params end
ruby
{ "resource": "" }
q467
Krikri.RecordsHelper.random_record_id
train
def random_record_id(provider_id) doc = Krikri::RandomSearchIndexDocumentBuilder.new do self.provider_id = provider_id end.document doc.present? ? local_name(doc.id) : nil end
ruby
{ "resource": "" }
q468
Sprockets.Pathname.find
train
def find(location, kind = :file) location = File.join(absolute_location, location) File.send("#{kind}?", location) ? Pathname.new(environment, location) : nil end
ruby
{ "resource": "" }
q469
Krikri.SearchResultsHelperBehavior.render_enriched_record
train
def render_enriched_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? JSON.pretty_generate(agg.to_jsonld['@graph']) end
ruby
{ "resource": "" }
q470
Krikri.SearchResultsHelperBehavior.render_original_record
train
def render_original_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? begin original_record = agg.original_record rescue StandardError => e logger.error e.message return error_msg(e.message) end return error_msg('Original record not found.') unless original_record.present? prettify_string(original_record.to_s, original_record.content_type) end
ruby
{ "resource": "" }
q471
CookieAlert.CookiesController.cookie_accepted
train
def cookie_accepted # Get the visitor's current page URL or, if nil?, default to the application root. Resue block needed for bots visitor_current_url = begin cookies.signed[CookieAlert.config.cookie_name.to_sym].split(CookieAlert.config.cookie_value_text_separator)[1] rescue main_app.root_path end # Set the Cookie value to 'accepted' if CookieAlert.config.cookie_type == 'permanent' # Set a permanent cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' elsif CookieAlert.config.cookie_type == 'fixed_duration' # Set a fixed duration cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = { value: 'accepted', expires: CookieAlert.config.num_days_until_cookie_expires.days.from_now } else # Set a session cookie cookies.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' end # If the request is HTML then redirect the visitor back to their original page # If the request is javascript then render the javascript partial respond_to do |format| format.html { redirect_to(visitor_current_url) } format.js { render template: "cookie_alert/cookies/cookie_accepted" } end end
ruby
{ "resource": "" }
q472
TerminalChess.Board.check?
train
def check?(color, proposed_manifest = @piece_locations, recurse_for_checkmate = false) enemy_attack_vectors = {} player_attack_vectors = {} king_loc = [] enemy_color = opposing_color(color) proposed_manifest.each do |piece, details| if details[:color] == enemy_color enemy_attack_vectors[piece] = possible_moves(piece, proposed_manifest) elsif details[:color] == color begin player_attack_vectors[piece] = possible_moves(piece, proposed_manifest) rescue # TODO: Fix possible_moves() so it doesn't throw exceptions # This happens because it is searching board for where pieces # will be, as as a result some pieces are nil end end king_loc = piece if details[:color] == color && details[:type] == :king end danger_vector = enemy_attack_vectors.values.flatten.uniq defence_vector = player_attack_vectors.values.flatten.uniq king_positions = possible_moves(king_loc, proposed_manifest) # The King is in the attackable locations by the opposing player return false unless danger_vector.include? king_loc # If all the positions the king piece can move to is also attackable by the opposing player if recurse_for_checkmate && (king_positions - danger_vector).empty? is_in_check = [] player_attack_vectors.each do |piece_index, piece_valid_moves| piece_valid_moves.each do |possible_new_location| # Check if board is still in check after piece moves to its new location @new_piece_locations = @piece_locations.clone @new_piece_locations[possible_new_location] = @new_piece_locations[piece_index] @new_piece_locations[piece_index] = { type: nil, number: nil, color: nil } is_in_check << check?(color, @new_piece_locations) end end return false if is_in_check.include?(false) @checkmate = true end true end
ruby
{ "resource": "" }
q473
Cryptoprocessing.Account.transactions
train
def transactions(options = {}) agent.transactions(self['id'], options) do |data, resp| yield(data, resp) if block_given? end end
ruby
{ "resource": "" }
q474
Cryptoprocessing.Account.transactions_by_address
train
def transactions_by_address(address, options = {}) agent.transactions_by_address(self['id'], address, options) do |data, resp| yield(data, resp) if block_given? end end
ruby
{ "resource": "" }
q475
Vnstat.InterfaceCollection.[]
train
def [](id) interfaces_hash.fetch(id.to_s) do raise UnknownInterface.new(id.to_s), "Unknown interface: #{id}" end end
ruby
{ "resource": "" }
q476
EasyRSA.Certificate.gen_subject
train
def gen_subject subject_name = "/C=#{EasyRSA::Config.country}" subject_name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? subject_name += "/L=#{EasyRSA::Config.city}" subject_name += "/O=#{EasyRSA::Config.company}" subject_name += "/OU=#{EasyRSA::Config.orgunit}" subject_name += "/CN=#{@id}" subject_name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? subject_name += "/emailAddress=#{@email}" @cert.subject = OpenSSL::X509::Name.parse(subject_name) end
ruby
{ "resource": "" }
q477
Vnstat.Interface.nick=
train
def nick=(nick) success = Utils.call_executable_returning_status( '-i', id, '--nick', nick, '--update' ) unless success raise Error, "Unable to set nickname for interface (#{id}). " \ 'Please make sure the vnstat daemon is not running while ' \ 'performing this operation.' end @nick = nick end
ruby
{ "resource": "" }
q478
WampRails.Client.open
train
def open # Create the background thread self.thread = Thread.new do EM.tick_loop do unless self.cmd_queue.empty? command = self.cmd_queue.pop self._execute_command(command) end end self.wamp.open end end
ruby
{ "resource": "" }
q479
WampRails.Client.add_procedure
train
def add_procedure(procedure, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_procedure" must be called BEFORE "open"') if self.thread self.registrations << WampRails::Command::Register.new(procedure, klass, options, self) end
ruby
{ "resource": "" }
q480
WampRails.Client.add_subscription
train
def add_subscription(topic, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_subscription" must be called BEFORE "open"') if self.thread self.subscriptions << WampRails::Command::Subscribe.new(topic, klass, options, self) end
ruby
{ "resource": "" }
q481
WampRails.Client.call
train
def call(procedure, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Call.new(procedure, args, kwargs, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q482
WampRails.Client.publish
train
def publish(topic, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Publish.new(topic, args, kwargs, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q483
WampRails.Client.register
train
def register(procedure, klass, options={}, &callback) command = WampRails::Command::Register.new(procedure, klass, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q484
WampRails.Client.subscribe
train
def subscribe(topic, klass, options={}, &callback) command = WampRails::Command::Subscribe.new(topic, klass, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q485
WampRails.Client._queue_command
train
def _queue_command(command, callback=nil) # If the current thread is the EM thread, execute the command. Else put it in the queue if self.thread == Thread.current self._execute_command(command) else self.cmd_queue.push(command) end # If the callback is defined, block until it finishes if callback callback_args = command.queue.pop callback.call(callback_args.result, callback_args.error, callback_args.details) end end
ruby
{ "resource": "" }
q486
Elastics.LiveReindex.track_external_change
train
def track_external_change(app_id, action, document) return unless Conf.redis Conf.redis.rpush("#{KEYS[:changes]}-#{app_id}", MultiJson.encode([action, document])) end
ruby
{ "resource": "" }
q487
Appium.Lint.report
train
def report data return nil if data.nil? || data.empty? result = '' data.each do |file_name, analysis| rel_path = File.join('.', File.expand_path(file_name).sub(Dir.pwd, '')) result += "\n#{rel_path}\n" analysis.each do |line_number, warning| result += " #{line_number}: #{warning.join(',')}\n" end end result.strip! result.empty? ? nil : result end
ruby
{ "resource": "" }
q488
Dux.Blankness.blankish?
train
def blankish?(value) case value when nil, false true when Dux[:nan?] true when String, Symbol value.empty? || value =~ WHITESPACE_ONLY when Dux[:blank?] value.blank? when Hash value.empty? when Array, Enumerable Dux.attempt(value, :empty?) || value.all? { |val| blankish?(val) } when Dux[:empty?] value.empty? else false end end
ruby
{ "resource": "" }
q489
Krikri.QAQueryClient.build_optional_patterns
train
def build_optional_patterns(predicates) return [[TYPE, predicates, VALUE]] unless predicates.is_a? Enumerable var1 = TYPE patterns = predicates.each_with_object([]) do |predicate, ps| var2 = (ps.count == predicates.size - 1) ? VALUE : "obj#{ps.count}".to_sym ps << [var1, predicate, var2] var1 = var2 end end
ruby
{ "resource": "" }
q490
TerminalChess.Move.possible_moves
train
def possible_moves(p1, manifest, castling = false) return [] if manifest[p1][:type].nil? allowed = [] type = manifest[p1][:type] my_color = manifest[p1][:color] constants(manifest, my_color, type) return [] if unoccupied?(p1) if type == :king allowed += [move_lateral(p1, 1)].flatten allowed += [move_diagonal(p1, 1)].flatten allowed += [castle(p1)].flatten if castling elsif type == :queen allowed += [move_lateral(p1)].flatten allowed += [move_diagonal(p1)].flatten elsif type == :rook allowed += [move_lateral(p1)].flatten elsif type == :bishop allowed += [move_diagonal(p1)].flatten elsif type == :pawn allowed += [move_pawn(p1)].flatten elsif type == :knight allowed += [move_knight(p1)].flatten end allowed end
ruby
{ "resource": "" }
q491
TerminalChess.Move.move_pawn
train
def move_pawn(p1) col = get_col_from_index(p1) valid = [] # Piece color defines direction of travel. Enemy presence defines # the validity of diagonal movements if Move.color == :red valid << (p1 - 8) if unoccupied?(p1 - 8) valid << (p1 - 7) if piece_color(p1 - 7) == Move.enemy_color && col < 8 valid << (p1 - 9) if piece_color(p1 - 9) == Move.enemy_color && col > 1 # Only if the pieces is unmoved, can it move forward two rows valid << (p1 - 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 - 8) && unoccupied?(p1 - 16) elsif Move.color == :black valid << (p1 + 8) if unoccupied?(p1 + 8) valid << (p1 + 7) if piece_color(p1 + 7) == Move.enemy_color && col > 1 valid << (p1 + 9) if piece_color(p1 + 9) == Move.enemy_color && col < 8 valid << (p1 + 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 + 8) && unoccupied?(p1 + 16) end valid end
ruby
{ "resource": "" }
q492
TerminalChess.Move.move_knight
train
def move_knight(p1) row = get_row_from_index(p1) col = get_col_from_index(p1) valid = [] valid_moves_no_friendly_fire = [] # Valid knight moves based on its board position valid << (p1 + 17) if row < 7 && col < 8 valid << (p1 + 15) if row < 7 && col > 1 valid << (p1 + 10) if row < 8 && col < 7 valid << (p1 + 6) if row < 8 && col > 2 valid << (p1 - 6) if row > 1 && col < 7 valid << (p1 - 10) if row > 1 && col > 2 valid << (p1 - 15) if row > 2 && col < 8 valid << (p1 - 17) if row > 2 && col > 1 # All possible moves for the knight based on board boundaries will added # This iterator filters for friendly fire, and removes indexes pointing to same color pices valid.each do |pos| valid_moves_no_friendly_fire << pos unless piece_color(pos) == Move.color end valid_moves_no_friendly_fire end
ruby
{ "resource": "" }
q493
ActsAsScd.ClassMethods.find_by_identity
train
def find_by_identity(identity, at_date=nil) # (at_date.nil? ? current : at(at_date)).where(IDENTITY_COLUMN=>identity).first if at_date.nil? q = current else q = at(at_date) end q = q.where(IDENTITY_COLUMN=>identity) q.first end
ruby
{ "resource": "" }
q494
ActsAsScd.ClassMethods.create_identity
train
def create_identity(attributes, start=nil) start ||= START_OF_TIME create(attributes.merge(START_COLUMN=>start || START_OF_TIME)) end
ruby
{ "resource": "" }
q495
EasyRSA.CA.gen_issuer
train
def gen_issuer name = "/C=#{EasyRSA::Config.country}" name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? name += "/L=#{EasyRSA::Config.city}" name += "/O=#{EasyRSA::Config.company}" name += "/OU=#{EasyRSA::Config.orgunit}" name += "/CN=#{EasyRSA::Config.server}" name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? name += "/name=#{EasyRSA::Config.orgunit}" if !EasyRSA::Config.name || EasyRSA::Config.name.empty? name += "/emailAddress=#{EasyRSA::Config.email}" @ca_cert.issuer = OpenSSL::X509::Name.parse(name) end
ruby
{ "resource": "" }
q496
EasyRSA.CA.add_extensions
train
def add_extensions ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = @ca_cert ef.issuer_certificate = @ca_cert @ca_cert.add_extension ef.create_extension('subjectKeyIdentifier', 'hash') @ca_cert.add_extension ef.create_extension('basicConstraints', 'CA:TRUE', true) @ca_cert.add_extension ef.create_extension('keyUsage', 'cRLSign,keyCertSign', true) end
ruby
{ "resource": "" }
q497
SortingTableFor.TableBuilder.render_tbody
train
def render_tbody if @lines and @lines.size > 0 return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join))) return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' })) end '' end
ruby
{ "resource": "" }
q498
SortingTableFor.TableBuilder.render_total_entries
train
def render_total_entries if self.show_total_entries total_entries = @collection.total_entries rescue @collection.size header_total_cells = @header_line ? @header_line.total_cells : 0 max_cells = (@lines.first.total_cells > header_total_cells) ? @lines.first.total_cells : header_total_cells return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :value => total_entries), {:colspan => max_cells}), { :class => 'total-entries' })) end '' end
ruby
{ "resource": "" }
q499
Krikri.SearchIndex.bulk_update_from_activity
train
def bulk_update_from_activity(activity) all_aggs = entities_as_json_hashes(activity) agg_batches = bulk_update_batches(all_aggs) agg_batches.each do |batch| index_with_error_handling(activity) { bulk_add(batch) } end end
ruby
{ "resource": "" }