_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q1400
Lol.SummonerRequest.find_by_name
train
def find_by_name name name = CGI.escape name.downcase.gsub(/\s/, '') DynamicModel.new perform_request api_url "summoners/by-name/#{name}" end
ruby
{ "resource": "" }
q1401
Scriptster.Configuration.apply
train
def apply Logger.set_name @name if @name Logger.set_verbosity @verbosity if @verbosity Logger.set_file @file if @file Logger.set_format @log_format if @log_format if @colours.is_a? Proc @colours.call else ColourThemes.send @colours.to_sym end end
ruby
{ "resource": "" }
q1402
Lol.Request.api_url
train
def api_url path, params = {} url = File.join File.join(api_base_url, api_base_path), path "#{url}?#{api_query_string params}" end
ruby
{ "resource": "" }
q1403
Lol.Request.clean_url
train
def clean_url(url) uri = URI.parse(url) uri.query = CGI.parse(uri.query || '').reject { |k| k == 'api_key' }.to_query uri.to_s end
ruby
{ "resource": "" }
q1404
Lol.Request.perform_request
train
def perform_request url, verb = :get, body = nil, options = {} options_id = options.inspect can_cache = [:post, :put].include?(verb) ? false : cached? if can_cache && result = store.get("#{clean_url(url)}#{options_id}") return JSON.parse(result) end response = perform_rate_limited_...
ruby
{ "resource": "" }
q1405
Scriptster.ShellCmd.run
train
def run Open3.popen3(@cmd) do |stdin, stdout, stderr, wait_thr| stdin.close # leaving stdin open when we don't use it can cause some commands to hang stdout_buffer="" stderr_buffer="" streams = [stdout, stderr] while streams.length > 0 IO.select(streams).flatten....
ruby
{ "resource": "" }
q1406
Lol.MasteriesRequest.by_summoner_id
train
def by_summoner_id summoner_id result = perform_request api_url "masteries/by-summoner/#{summoner_id}" result["pages"].map { |p| DynamicModel.new p } end
ruby
{ "resource": "" }
q1407
SchemaModel.ClassMethods.define_writer!
train
def define_writer!(k, definition) define_method("#{k}=") do |value| # Recursively convert hash and array of hash to schematized objects value = ensure_schema value, definition[:schema] # Initial value instance_variable_set "@#{k}", value # Dirty tracking self.chan...
ruby
{ "resource": "" }
q1408
SchemaModel.InstanceMethods.check_children
train
def check_children(child_schema, value) return unless child_schema && value.present? if value.is_a? Array value.map(&:errors).reject(&:empty?) else value.errors end end
ruby
{ "resource": "" }
q1409
SchemaModel.InstanceMethods.check_validation
train
def check_validation(valid, value) return unless valid && value passes_validation = begin valid.call(value) rescue StandardError false end passes_validation ? nil : 'is invalid' end
ruby
{ "resource": "" }
q1410
SchemaModel.InstanceMethods.append!
train
def append!(errors, attr, key, val) return unless val.present? errors ||= {} errors[attr] ||= {} errors[attr][key] = val end
ruby
{ "resource": "" }
q1411
Delighted.Resource.to_hash
train
def to_hash serialized_attributes = attributes.dup self.class.expandable_attributes.each_pair.select do |attribute_name, expanded_class| if expanded_class === attributes[attribute_name] serialized_attributes[attribute_name] = serialized_attributes[attribute_name].id end end ...
ruby
{ "resource": "" }
q1412
Mailgun.Webhook.update
train
def update(id, url=default_webhook_url) params = {:url => url} Mailgun.submit :put, webhook_url(id), params end
ruby
{ "resource": "" }
q1413
Mailgun.MailingList.update
train
def update(address, new_address, options={}) params = {:address => new_address} Mailgun.submit :put, list_url(address), params.merge(options) end
ruby
{ "resource": "" }
q1414
EncryptedStrings.AsymmetricCipher.encrypt
train
def encrypt(data) raise NoPublicKeyError, "Public key file: #{public_key_file}" unless public? encrypted_data = public_rsa.public_encrypt(data) [encrypted_data].pack('m') end
ruby
{ "resource": "" }
q1415
EncryptedStrings.AsymmetricCipher.decrypt
train
def decrypt(data) raise NoPrivateKeyError, "Private key file: #{private_key_file}" unless private? decrypted_data = data.unpack('m')[0] private_rsa.private_decrypt(decrypted_data) end
ruby
{ "resource": "" }
q1416
EncryptedStrings.AsymmetricCipher.private_rsa
train
def private_rsa if password options = {:password => password} options[:algorithm] = algorithm if algorithm private_key = @private_key.decrypt(:symmetric, options) OpenSSL::PKey::RSA.new(private_key) else @private_rsa ||= OpenSSL::PKey::RSA.new...
ruby
{ "resource": "" }
q1417
EncryptedStrings.ShaCipher.encrypt
train
def encrypt(data) Digest::const_get(algorithm.upcase).hexdigest(build(data, salt)) end
ruby
{ "resource": "" }
q1418
EncryptedStrings.ShaCipher.build
train
def build(data, salt) if builder.is_a?(Proc) builder.call(data, salt) else builder.send(:build, data, salt) end end
ruby
{ "resource": "" }
q1419
Mailgun.Secure.check_request_auth
train
def check_request_auth(timestamp, token, signature, offset=-5) if offset != 0 offset = Time.now.to_i + offset * 60 return false if timestamp < offset end return signature == OpenSSL::HMAC.hexdigest( OpenSSL::Digest::Digest.new('sha256'), Mailgun.api_key, ...
ruby
{ "resource": "" }
q1420
Res.IR.json
train
def json hash = { :started => @started, :finished => @finished, :results => @results, :type => @type } # Merge in the world information if it's available hash[:world] = world if world hash[:hive_job_id] = hive_job_id if hive_job_id ...
ruby
{ "resource": "" }
q1421
EncryptedStrings.SymmetricCipher.decrypt
train
def decrypt(data) cipher = build_cipher(:decrypt) cipher.update(data.unpack('m')[0]) + cipher.final end
ruby
{ "resource": "" }
q1422
EncryptedStrings.SymmetricCipher.encrypt
train
def encrypt(data) cipher = build_cipher(:encrypt) [cipher.update(data) + cipher.final].pack('m') end
ruby
{ "resource": "" }
q1423
Mailgun.Domain.create
train
def create(domain, opts = {}) opts = {name: domain}.merge(opts) Mailgun.submit :post, domain_url, opts end
ruby
{ "resource": "" }
q1424
Perlin.GradientTable.index
train
def index(*coords) s = coords.last coords.reverse[1..-1].each do |c| s = perm(s) + c end perm(s) end
ruby
{ "resource": "" }
q1425
Mailgun.MailingList::Member.add
train
def add(member_address, options={}) params = {:address => member_address} Mailgun.submit :post, list_member_url, params.merge(options) end
ruby
{ "resource": "" }
q1426
Mailgun.MailingList::Member.update
train
def update(member_address, options={}) params = {:address => member_address} Mailgun.submit :put, list_member_url(member_address), params.merge(options) end
ruby
{ "resource": "" }
q1427
BLE.Device.cancel_pairing
train
def cancel_pairing block_given? ? @o_dev[I_DEVICE].CancelPairing(&Proc.new) : @o_dev[I_DEVICE].CancelPairing() true rescue DBus::Error => e case e.name when E_DOES_NOT_EXIST then true when E_FAILED then false else raise ScriptError end end
ruby
{ "resource": "" }
q1428
BLE.Device.is_paired?
train
def is_paired? @o_dev[I_DEVICE]['Paired'] rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject else raise ScriptError end end
ruby
{ "resource": "" }
q1429
BLE.Device.trusted=
train
def trusted=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Trusted'] = val end
ruby
{ "resource": "" }
q1430
BLE.Device.blocked=
train
def blocked=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Blocked'] = val end
ruby
{ "resource": "" }
q1431
BLE.Device.refresh!
train
def refresh! _require_connection! max_wait ||= 1.5 # Use ||= due to the retry @services = Hash[@o_dev.subnodes.map {|p_srv| p_srv = [@o_dev.path, p_srv].join '/' o_srv = BLUEZ.object(p_srv) o_srv.introspect srv = o_srv.GetAll(I_GATT_SERVICE).first ch...
ruby
{ "resource": "" }
q1432
PMScreenModule.ClassMethods.action_bar
train
def action_bar(show_action_bar, opts={}) @action_bar_options = ({show:true, back: true, icon: false}).merge(opts).merge({show: show_action_bar}) end
ruby
{ "resource": "" }
q1433
Mixpanel.Tracker.escape_object_for_js
train
def escape_object_for_js(object, i = 0) if object.kind_of? Hash # Recursive case Hash.new.tap do |h| object.each do |k, v| h[escape_object_for_js(k, i + 1)] = escape_object_for_js(v, i + 1) end end elsif object.kind_of? Enumerable # Recursive...
ruby
{ "resource": "" }
q1434
HerokuExternalDb.Configuration.db_configuration
train
def db_configuration(opts) return {} unless opts raise "ca_path for #{opts.inspect} cannot be determined from Rails root; please set it explicitly" unless ca_path config = {} [ :sslca, # Needed when using X.509 :sslcert, :sslkey, ].each do |k| if ...
ruby
{ "resource": "" }
q1435
HerokuExternalDb.Configuration.db_config
train
def db_config @db_config ||= begin raise "ENV['#{env_prefix}_DATABASE_URL'] expected but not found!" unless ENV["#{env_prefix}_DATABASE_URL"] config = parse_db_uri(ENV["#{env_prefix}_DATABASE_URL"]) if ENV["#{env_prefix}_DATABASE_CA"] config.merge!(db_configuration({ ...
ruby
{ "resource": "" }
q1436
BLE.Notifications.start_notify!
train
def start_notify!(service, characteristic) char= _find_characteristic(service, characteristic) if char.flag?('notify') char.notify! else raise OperationNotSupportedError.new("No notifications available for characteristic #{characteristic}") end end
ruby
{ "resource": "" }
q1437
BLE.Notifications.on_notification
train
def on_notification(service, characteristic, raw: false, &callback) _require_connection! char= _find_characteristic(service, characteristic) if char.flag?('notify') char.on_change(raw: raw) { |val| callback.call(val) } elsif char.flag?('encrypt-read') || char....
ruby
{ "resource": "" }
q1438
Steam.Client.get
train
def get(resource, params: {}, key: Steam.apikey) params[:key] = key response = @conn.get resource, params JSON.parse(response.body) rescue JSON::ParserError # If the steam web api returns an error it's virtually never in json, so # lets pretend that we're getting some sort of consist...
ruby
{ "resource": "" }
q1439
NdrUi.BootstrapHelper.bootstrap_tab_nav_tag
train
def bootstrap_tab_nav_tag(title, linkto, active = false) content_tag('li', link_to(title, linkto, "data-toggle": 'tab'), active ? { class: 'active' } : {}) end
ruby
{ "resource": "" }
q1440
NdrUi.BootstrapHelper.bootstrap_list_badge_and_link_to
train
def bootstrap_list_badge_and_link_to(type, count, name, path) html = content_tag(:div, bootstrap_badge_tag(type, count), class: 'pull-right') + name bootstrap_list_link_to(html, path) end
ruby
{ "resource": "" }
q1441
NdrUi.BootstrapHelper.bootstrap_progressbar_tag
train
def bootstrap_progressbar_tag(*args) percentage = args[0].to_i options = args[1] || {} options.stringify_keys! options['title'] ||= "#{percentage}%" classes = ['progress'] classes << options.delete('class') classes << 'progress-striped' type = options.delete('type').to_...
ruby
{ "resource": "" }
q1442
NdrUi.BootstrapHelper.description_list_name_value_pair
train
def description_list_name_value_pair(name, value, blank_value_placeholder = nil) # SECURE: TPG 2013-08-07: The output is sanitised by content_tag return unless value.present? || blank_value_placeholder.present? content_tag(:dt, name) + content_tag(:dd, value || content_tag(:span, blank_value_p...
ruby
{ "resource": "" }
q1443
NdrUi.BootstrapHelper.details_link
train
def details_link(path, options = {}) return unless ndr_can?(:read, path) link_to_with_icon({ icon: 'share-alt', title: 'Details', path: path }.merge(options)) end
ruby
{ "resource": "" }
q1444
NdrUi.BootstrapHelper.edit_link
train
def edit_link(path, options = {}) return unless ndr_can?(:edit, path) path = edit_polymorphic_path(path) if path.is_a?(ActiveRecord::Base) link_to_with_icon({ icon: 'pencil', title: 'Edit', path: path }.merge(options)) end
ruby
{ "resource": "" }
q1445
NdrUi.BootstrapHelper.delete_link
train
def delete_link(path, options = {}) return unless ndr_can?(:delete, path) defaults = { icon: 'trash icon-white', title: 'Delete', path: path, class: 'btn btn-xs btn-danger', method: :delete, 'data-confirm': I18n.translate(:'ndr_ui.confirm_delete', locale: options[:locale]) } ...
ruby
{ "resource": "" }
q1446
NdrUi.BootstrapHelper.link_to_with_icon
train
def link_to_with_icon(options = {}) options[:class] ||= 'btn btn-default btn-xs' icon = bootstrap_icon_tag(options.delete(:icon)) content = options.delete(:text) ? icon + ' ' + options[:title] : icon link_to content, options.delete(:path), options end
ruby
{ "resource": "" }
q1447
AsciiCharts.Chart.round_value
train
def round_value(val) remainder = val % self.step_size unprecised = if (remainder * 2) >= self.step_size (val - remainder) + self.step_size else val - remainder end if self.step_size < 1 precision = -Math.log10(...
ruby
{ "resource": "" }
q1448
BLE.Characteristic._deserialize_value
train
def _deserialize_value(val, raw: false) val = val.pack('C*') val = @desc.post_process(val) if !raw && @desc.read_processors? val end
ruby
{ "resource": "" }
q1449
NdrUi.CssHelper.css_class_options_merge
train
def css_class_options_merge(options, css_classes = [], &block) options.symbolize_keys! css_classes += options[:class].split(' ') if options.include?(:class) yield(css_classes) if block_given? options[:class] = css_classes.join(' ') unless css_classes.empty? unless css_classes == css_classe...
ruby
{ "resource": "" }
q1450
BLE.Adapter.filter
train
def filter(uuids, rssi: nil, pathloss: nil, transport: :le) unless [:auto, :bredr, :le].include?(transport) raise ArgumentError, "transport must be one of :auto, :bredr, :le" end filter = { } unless uuids.nil? || uuids.empty? filter['UUI...
ruby
{ "resource": "" }
q1451
ServiceMock.Server.stub_with_file
train
def stub_with_file(filename) return if ::ServiceMock.disable_stubs yield self if block_given? content = File.open(filename, 'rb') { |file| file.read } stub(content) end
ruby
{ "resource": "" }
q1452
ServiceMock.Server.stub_with_erb
train
def stub_with_erb(filename, hsh={}) return if ::ServiceMock.disable_stubs yield self if block_given? template = File.open(filename, 'rb') { |file| file.read } erb_content = ERB.new(template).result(data_binding(hsh)) stub(erb_content) end
ruby
{ "resource": "" }
q1453
ServiceMock.Server.count
train
def count(request_criteria) return if ::ServiceMock.disable_stubs yield self if block_given? JSON.parse(http.post('/__admin/requests/count', request_criteria).body)['count'] end
ruby
{ "resource": "" }
q1454
ServiceMock.Server.count_with_file
train
def count_with_file(filename) return if ::ServiceMock.disable_stubs yield self if block_given? content = File.open(filename, 'rb') { |file| file.read } count(content) end
ruby
{ "resource": "" }
q1455
ServiceMock.Server.count_with_erb
train
def count_with_erb(filename, hsh={}) return if ::ServiceMock.disable_stubs yield self if block_given? template = File.open(filename, 'rb') { |file| file.read } erb_content = ERB.new(template).result(data_binding(hsh)) count(erb_content) end
ruby
{ "resource": "" }
q1456
Ashton.Texture.clear
train
def clear(options = {}) options = { color: [0.0, 0.0, 0.0, 0.0], }.merge! options color = options[:color] color = color.to_opengl if color.is_a? Gosu::Color Gl.glBindFramebufferEXT Gl::GL_FRAMEBUFFER_EXT, fbo_id unless rendering? Gl.glDisable Gl::GL_BLEND # Need to repla...
ruby
{ "resource": "" }
q1457
VLC.Connection.write
train
def write(data, fire_and_forget = true) raise NotConnectedError, "no connection to server" unless connected? @socket.puts(data) @socket.flush return true if fire_and_forget read rescue Errno::EPIPE disconnect raise BrokenConnectionError, "the connection to the server is l...
ruby
{ "resource": "" }
q1458
VLC.Connection.read
train
def read(timeout=nil) timeout = read_timeout if timeout.nil? raw_data = nil Timeout.timeout(timeout) do raw_data = @socket.gets.chomp end if (data = parse_raw_data(raw_data)) data[1] else raise VLC::ProtocolError, "could not interpret the playload: #{raw_dat...
ruby
{ "resource": "" }
q1459
Gosu.Window.post_process
train
def post_process(*shaders) raise ArgumentError, "Block required" unless block_given? raise TypeError, "Can only process with Shaders" unless shaders.all? {|s| s.is_a? Ashton::Shader } # In case no shaders are passed, just run the contents of the block. unless shaders.size > 0 yield ...
ruby
{ "resource": "" }
q1460
Spidey.AbstractSpider.each_url
train
def each_url(&_block) index = 0 while index < urls.count # urls grows dynamically, don't use &:each url = urls[index] next unless url yield url, handlers[url].first, handlers[url].last index += 1 end end
ruby
{ "resource": "" }
q1461
Gosu.Image.draw_as_points
train
def draw_as_points(points, z, options = {}) color = options[:color] || DEFAULT_DRAW_COLOR scale = options[:scale] || 1.0 shader = options[:shader] mode = options[:mode] || :default if shader shader.enable z $window.gl z do shader.image = self shader.col...
ruby
{ "resource": "" }
q1462
Ashton.SignedDistanceField.sample_distance
train
def sample_distance(x, y) x = [[x, width - 1].min, 0].max y = [[y, height - 1].min, 0].max # Could be checking any of red/blue/green. @field.red((x / @scale).round, (y / @scale).round) - ZERO_DISTANCE end
ruby
{ "resource": "" }
q1463
Ashton.SignedDistanceField.sample_gradient
train
def sample_gradient(x, y) d0 = sample_distance x, y - 1 d1 = sample_distance x - 1, y d2 = sample_distance x + 1, y d3 = sample_distance x, y + 1 [(d2 - d1) / @scale, (d3 - d0) / @scale] end
ruby
{ "resource": "" }
q1464
Ashton.SignedDistanceField.sample_normal
train
def sample_normal(x, y) gradient_x, gradient_y = sample_gradient x, y length = Gosu::distance 0, 0, gradient_x, gradient_y if length == 0 [0, 0] # This could be NaN in edge cases. else [gradient_x / length, gradient_y / length] end end
ruby
{ "resource": "" }
q1465
Ashton.SignedDistanceField.line_of_sight_blocked_at
train
def line_of_sight_blocked_at(x1, y1, x2, y2) distance_to_travel = Gosu::distance x1, y1, x2, y2 distance_x, distance_y = x2 - x1, y2 - y1 distance_travelled = 0 x, y = x1, y1 loop do distance = sample_distance x, y # Blocked? return [x, y] if distance <= 0 ...
ruby
{ "resource": "" }
q1466
Ashton.SignedDistanceField.render_field
train
def render_field raise ArgumentError, "Block required" unless block_given? @mask.render do @mask.clear $window.scale 1.0 / @scale do yield self end end @shader.enable do @field.render do @mask.draw 0, 0, 0 end end nil ...
ruby
{ "resource": "" }
q1467
Ashton.SignedDistanceField.draw
train
def draw(x, y, z, options = {}) options = { mode: :add, }.merge! options $window.scale @scale do @field.draw x, y, z, options end nil end
ruby
{ "resource": "" }
q1468
Ashton.SignedDistanceField.to_a
train
def to_a width.times.map do |x| height.times.map do |y| sample_distance x, y end end end
ruby
{ "resource": "" }
q1469
VLC.Server.start
train
def start(detached = false) return @pid if running? detached ? @deamon = true : setup_traps @pid = RUBY_VERSION >= '1.9' ? process_spawn(detached) : process_spawn_ruby_1_8(detached) end
ruby
{ "resource": "" }
q1470
VLC.Server.process_spawn_ruby_1_8
train
def process_spawn_ruby_1_8(detached) rd, wr = IO.pipe if Process.fork #parent wr.close pid = rd.read.to_i rd.close return pid else #child rd.close detach if detached #daemonization wr.write(Process.pid) wr.close ...
ruby
{ "resource": "" }
q1471
Furoshiki.Configuration.merge_config
train
def merge_config(config) defaults = { name: 'Ruby App', version: '0.0.0', release: 'Rookie', ignore: 'pkg', # TODO: Establish these default icons and paths. These would be # default icons for generic Ruby apps. icons: { #osx: 'path/to/default/App.i...
ruby
{ "resource": "" }
q1472
Ashton.WindowBuffer.capture
train
def capture Gl.glBindTexture Gl::GL_TEXTURE_2D, id Gl.glCopyTexImage2D Gl::GL_TEXTURE_2D, 0, Gl::GL_RGBA8, 0, 0, width, height, 0 self end
ruby
{ "resource": "" }
q1473
Ashton.Shader.[]=
train
def []=(uniform, value) uniform = uniform_name_from_symbol(uniform) if uniform.is_a? Symbol # Ensure that the program is current before setting values. needs_use = !current? enable if needs_use set_uniform uniform_location(uniform), value disable if needs_use value end
ruby
{ "resource": "" }
q1474
Ashton.Shader.set_uniform
train
def set_uniform(location, value) raise ShaderUniformError, "Shader uniform #{location.inspect} could not be set, since shader is not current" unless current? return if location == INVALID_LOCATION # Not for end-users :) case value when true, Gl::GL_TRUE Gl.glUniform1i location, 1 ...
ruby
{ "resource": "" }
q1475
Ashton.Shader.process_source
train
def process_source(shader, extension) source = if shader.is_a? Symbol file = File.expand_path "#{shader}#{extension}", BUILT_IN_SHADER_PATH unless File.exist? file raise ShaderLoadError, "Failed to load built-in shader: #{shader.inspect}" end ...
ruby
{ "resource": "" }
q1476
Furoshiki.Util.deep_set_symbol_key
train
def deep_set_symbol_key(hash, key, value) if value.kind_of? Hash hash[key.to_sym] = value.inject({}) { |inner_hash, (inner_key, inner_value)| deep_set_symbol_key(inner_hash, inner_key, inner_value) } else hash[key.to_sym] = value end hash end
ruby
{ "resource": "" }
q1477
Furoshiki.Util.merge_with_symbolized_keys
train
def merge_with_symbolized_keys(defaults, hash) hash.inject(defaults) { |symbolized, (k, v)| deep_set_symbol_key(symbolized, k, v) } end
ruby
{ "resource": "" }
q1478
RubyExpect.Expect.expect
train
def expect *patterns, &block @logger.debug("Expecting: #{patterns.inspect}") if @logger.debug? patterns = pattern_escape(*patterns) @end_time = 0 if (@timeout != 0) @end_time = Time.now + @timeout end @before = '' matched_index = nil while (@end_time == 0 || Time...
ruby
{ "resource": "" }
q1479
RubyExpect.Expect.pattern_escape
train
def pattern_escape *patterns escaped_patterns = [] patterns.each do |pattern| if (pattern.is_a?(String)) pattern = Regexp.new(Regexp.escape(pattern)) elsif (! pattern.is_a?(Regexp)) raise "Don't know how to match on a #{pattern.class}" end ...
ruby
{ "resource": "" }
q1480
Filemaker.Server.serialize_args
train
def serialize_args(args) return {} if args.nil? args.each do |key, value| case value when DateTime, Time args[key] = value.strftime('%m/%d/%Y %H:%M:%S') when Date args[key] = value.strftime('%m/%d/%Y') else # Especially for range operator (...),...
ruby
{ "resource": "" }
q1481
C.NodeList.match?
train
def match?(arr, parser=nil) arr = arr.to_a return false if arr.length != self.length each_with_index do |node, i| node.match?(arr[i], parser) or return false end return true end
ruby
{ "resource": "" }
q1482
C.Node.assert_invariants
train
def assert_invariants(testcase) fields.each do |field| if val = send(field.reader) assert_same(self, node.parent, "field.reader is #{field.reader}") if field.child? assert_same(field, val.instance_variable_get(:@parent_field), "field.reader is #{field.reader}") en...
ruby
{ "resource": "" }
q1483
C.Node.each
train
def each(&blk) fields.each do |field| if field.child? val = self.send(field.reader) yield val unless val.nil? end end return self end
ruby
{ "resource": "" }
q1484
C.Node.swap_with
train
def swap_with node return self if node.equal? self if self.attached? if node.attached? # both attached -- use placeholder placeholder = Default.new my_parent = @parent my_parent.replace_node(self, placeholder) node.parent.replace_node(node, self) ...
ruby
{ "resource": "" }
q1485
C.Node.node_before
train
def node_before(node) node.parent.equal? self or raise ArgumentError, "node is not a child" fields = self.fields i = node.instance_variable_get(:@parent_field).index - 1 i.downto(0) do |i| f = fields[i] if f.child? && (val = self.send(f.reader)) return val ...
ruby
{ "resource": "" }
q1486
C.Node.remove_node
train
def remove_node(node) node.parent.equal? self or raise ArgumentError, "node is not a child" field = node.instance_variable_get(:@parent_field) node.instance_variable_set(:@parent, nil) node.instance_variable_set(:@parent_field, nil) self.instance_variable_set(field.var, nil) ...
ruby
{ "resource": "" }
q1487
C.Node.replace_node
train
def replace_node(node, newnode=nil) node.parent.equal? self or raise ArgumentError, "node is not a child" field = node.instance_variable_get(:@parent_field) self.send(field.writer, newnode) return self end
ruby
{ "resource": "" }
q1488
C.NodeChain.link_
train
def link_(a, nodes, b) if nodes.empty? if a.nil? @first = b else a.instance_variable_set(:@next, b) end if b.nil? @last = a else b.instance_variable_set(:@prev, a) end else # connect `a' and `b' first = n...
ruby
{ "resource": "" }
q1489
C.NodeChain.link2_
train
def link2_(a, b) if a.nil? @first = b else a.instance_variable_set(:@next, b) unless a.nil? end if b.nil? @last = a else b.instance_variable_set(:@prev, a) unless b.nil? end end
ruby
{ "resource": "" }
q1490
C.NodeChain.get_
train
def get_(i) # return a Node if i < (@length >> 1) # go from the beginning node = @first i.times{node = node.next} else # go from the end node = @last (@length - 1 - i).times{node = node.prev} end return node end
ruby
{ "resource": "" }
q1491
Resqued.Listener.exec
train
def exec socket_fd = @socket.to_i ENV['RESQUED_SOCKET'] = socket_fd.to_s ENV['RESQUED_CONFIG_PATH'] = @config_paths.join(':') ENV['RESQUED_STATE'] = (@old_workers.map { |r| "#{r[:pid]}|#{r[:queue]}" }.join('||')) ENV['RESQUED_LISTENER_ID'] = @listener_id.to_s ENV['RESQUED_...
ruby
{ "resource": "" }
q1492
ChemistryKit.Chemist.method_missing
train
def method_missing(name, *arguments) value = arguments[0] name = name.to_s if name[-1, 1] == '=' key = name[/(.+)\s?=/, 1] @data[key.to_sym] = value unless instance_variables.include? "@#{key}".to_sym else @data[name.to_sym] end end
ruby
{ "resource": "" }
q1493
Placemaker.Client.fetch!
train
def fetch! fields = POST_FIELDS.reject{|f| @options[f].nil? }.map do |f| # Change ruby-form fields to url type, e.g., document_content => documentContent cgi_param = f.to_s.gsub(/\_(.)/) {|s| s.upcase}.gsub('_', '').sub(/url/i, 'URL') Curl::PostField.content(cgi_param, @options[f]) e...
ruby
{ "resource": "" }
q1494
EffectiveEmailTemplates.LiquidResolver.decorate
train
def decorate(templates, path_info, details, locals) templates.each do |t| t.locals = locals end end
ruby
{ "resource": "" }
q1495
MentionSystem.MentionProcessor.extract_handles_from_mentioner
train
def extract_handles_from_mentioner(mentioner) content = extract_mentioner_content(mentioner) handles = content.scan(handle_regexp).map { |handle| handle.gsub("#{mention_prefix}","") } end
ruby
{ "resource": "" }
q1496
MentionSystem.MentionProcessor.process_after_callbacks
train
def process_after_callbacks(mentioner, mentionee) result = true @callbacks[:after].each do |callback| unless callback.call(mentioner, mentionee) result = false break end end result end
ruby
{ "resource": "" }
q1497
Ebayr.Request.headers
train
def headers { 'X-EBAY-API-COMPATIBILITY-LEVEL' => @compatability_level.to_s, 'X-EBAY-API-DEV-NAME' => dev_id.to_s, 'X-EBAY-API-APP-NAME' => app_id.to_s, 'X-EBAY-API-CERT-NAME' => cert_id.to_s, 'X-EBAY-API-CALL-NAME' => @command.to_s, 'X-EBAY-API-SITEID' => @site_id....
ruby
{ "resource": "" }
q1498
Ebayr.Request.http
train
def http(&block) http = Net::HTTP.new(@uri.host, @uri.port) if @uri.port == 443 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end return http.start(&block) if block_given? http end
ruby
{ "resource": "" }
q1499
RightApi.Client.retry_request
train
def retry_request(is_read_only = false) attempts = 0 begin yield rescue OpenSSL::SSL::SSLError => e raise e unless @enable_retry # These errors pertain to the SSL handshake. Since no data has been # exchanged its always safe to retry raise e if attempts >= @max...
ruby
{ "resource": "" }