_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q3600
RETS4R.Client.get_object
train
def get_object(resource, type, id, location = false) #:yields: data_object header = { 'Accept' => mimemap.keys.join(',') } data = { 'Resource' => resource, 'Type' => type, 'ID' => id, 'Location' => location ? '1' : '0' } response = request(@urls.objects, data, header) results = block_given? ? 0 : [] if response['content-type'] && response['content-type'].include?('text/xml') # This probably means that there was an error. # Response parser will likely raise an exception. # TODO: test this rr = ResponseDocument.safe_parse(response.body).validate!.to_transaction return rr elsif response['content-type'] && response['content-type'].include?('multipart/parallel') content_type = process_content_type(response['content-type']) # TODO: log this # puts "SPLIT ON #{content_type['boundary']}" boundary = content_type['boundary'] if boundary =~ /\s*'([^']*)\s*/ boundary = $1 end parts = response.body.split("\r\n--#{boundary}") parts.shift # Get rid of the initial boundary # TODO: log this # puts "GOT PARTS #{parts.length}" parts.each do |part| (raw_header, raw_data) = part.split("\r\n\r\n") # TODO: log this # puts raw_data.nil? next unless raw_data data_header = process_header(raw_header) data_object = DataObject.new(data_header, raw_data) if block_given? yield data_object results += 1 else results << data_object end end else info = { 'content-type' => response['content-type'], # Compatibility shim. Deprecated. 'Content-Type' => response['content-type'], 'Object-ID' => response['Object-ID'], 'Content-ID' => response['Content-ID'] } if response['Transfer-Encoding'].to_s.downcase == "chunked" || response['Content-Length'].to_i > 100 then data_object = DataObject.new(info, response.body) if block_given? yield data_object results += 1 else results << data_object end end end results end
ruby
{ "resource": "" }
q3601
RETS4R.Client.search
train
def search(search_type, klass, query, options = false) header = {} # Required Data data = { 'SearchType' => search_type, 'Class' => klass, 'Query' => query, 'QueryType' => 'DMQL2', 'Format' => format, 'Count' => '0' } # Options #-- # We might want to switch this to merge!, but I've kept it like this for now because it # explicitly casts each value as a string prior to performing the search, so we find out now # if can't force a value into the string context. I suppose it doesn't really matter when # that happens, though... #++ options.each { |k,v| data[k] = v.to_s } if options response = request(@urls.search, data, header) # TODO: make parser configurable results = RETS4R::Client::CompactNokogiriParser.new(response.body) if block_given? results.each {|result| yield result} else return results.to_a end end
ruby
{ "resource": "" }
q3602
XcodeInstaller.Install.cp_r
train
def cp_r(src, dest, options = {}) # fu_check_options options, OPT_TABLE['cp_r'] # fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] options = options.dup options[:dereference_root] = true unless options.key?(:dereference_root) fu_each_src_dest(src, dest) do |s, d| copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination] end end
ruby
{ "resource": "" }
q3603
Jobbr.Ohm.models
train
def models(parent = nil) model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"] model_paths.each{ |path| require path } sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') } model_constants = sanitized_model_paths.map do |path| path.split('/').map { |token| token.camelize }.join('::').constantize end model_constants.select { |model| superclasses(model).include?(::Ohm::Model) } if parent model_constants.select { |model| model.included_modules.include?(parent) } else model_constants end end
ruby
{ "resource": "" }
q3604
Jobbr.Ohm.superclasses
train
def superclasses(klass) super_classes = [] while klass != Object klass = klass.superclass super_classes << klass end super_classes end
ruby
{ "resource": "" }
q3605
WADL.HasDocs.define_singleton
train
def define_singleton(r, sym, method) name = r.send(sym) if name && name !~ /\W/ && !r.respond_to?(name) && !respond_to?(name) instance_eval(%Q{def #{name}\n#{method}('#{name}')\nend}) end end
ruby
{ "resource": "" }
q3606
WebkitRemote.Process.start
train
def start return self if running? unless @pid = ::Process.spawn(*@cli) # The launch failed. stop return nil end (@timeout * 20).times do # Check if the browser exited. begin break if ::Process.wait(@pid, ::Process::WNOHANG) rescue SystemCallError # no children break end # Check if the browser finished starting up. begin browser = WebkitRemote::Browser.new process: self @running = true return browser rescue SystemCallError # most likely ECONNREFUSED Kernel.sleep 0.05 end end # The browser failed, or was too slow to start. stop nil end
ruby
{ "resource": "" }
q3607
WebkitRemote.Process.stop
train
def stop return self unless running? if @pid begin ::Process.kill 'TERM', @pid ::Process.wait @pid rescue SystemCallError # Process died on its own. ensure @pid = nil end end FileUtils.rm_rf @data_dir if File.exist?(@data_dir) @running = false self end
ruby
{ "resource": "" }
q3608
WADL.ResponseFormat.build
train
def build(http_response) # Figure out which fault or representation to use. status = http_response.status[0] unless response_format = faults.find { |f| f.dereference.status == status } # Try to match the response to a response format using a media # type. response_media_type = http_response.content_type response_format = representations.find { |f| t = f.dereference.mediaType and response_media_type.index(t) == 0 } # If an exact media type match fails, use the mime-types gem to # match the response to a response format using the underlying # subtype. This will match "application/xml" with "text/xml". response_format ||= begin mime_type = MIME::Types[response_media_type] raw_sub_type = mime_type[0].raw_sub_type if mime_type && !mime_type.empty? representations.find { |f| if t = f.dereference.mediaType response_mime_type = MIME::Types[t] response_raw_sub_type = response_mime_type[0].raw_sub_type if response_mime_type && !response_mime_type.empty? response_raw_sub_type == raw_sub_type end } end # If all else fails, try to find a response that specifies no # media type. TODO: check if this would be valid WADL. response_format ||= representations.find { |f| !f.dereference.mediaType } end body = http_response.read if response_format && response_format.mediaType =~ /xml/ begin body = REXML::Document.new(body) # Find the appropriate element of the document if response_format.element # TODO: don't strip the damn namespace. I'm not very good at # namespaces and I don't see how to deal with them here. element = response_format.element.sub(/.*:/, '') body = REXML::XPath.first(body, "//#{element}") end rescue REXML::ParseException end body.extend(XMLRepresentation) body.representation_of(response_format) end klass = response_format.is_a?(FaultFormat) ? response_format.subclass : Response obj = klass.new(http_response.status, http_response.headers, body, response_format) obj.is_a?(Exception) ? raise(obj) : obj end
ruby
{ "resource": "" }
q3609
I3.IPC.handle_response
train
def handle_response(type) # reads 14 bytes # length of "i3-ipc" + 4 bytes length + 4 bytes type buffer = read 14 raise WrongMagicCode unless buffer[0, (MAGIC_STRING.length)] == MAGIC_STRING len, recv_type = buffer[6..-1].unpack("LL") raise WrongType unless recv_type == type answer = read len ::JSON.parse(answer) end
ruby
{ "resource": "" }
q3610
WADL.ResourceAndAddress.method_missing
train
def method_missing(name, *args, &block) if @resource.respond_to?(name) result = @resource.send(name, *args, &block) result.is_a?(Resource) ? ResourceAndAddress.new(result, @address.dup) : result else super end end
ruby
{ "resource": "" }
q3611
WADL.ResourceAndAddress.resource
train
def resource(*args, &block) resource = @resource.resource(*args, &block) resource && ResourceAndAddress.new(resource, @address) end
ruby
{ "resource": "" }
q3612
Jobbr.Whenever.schedule_jobs
train
def schedule_jobs(job_list) Jobbr::Ohm.models(Jobbr::Scheduled).each do |job| if job.every job_list.every job.every[0], job.every[1] do job_list.jobbr job.task_name end end end end
ruby
{ "resource": "" }
q3613
Sunrise.ActivitiesHelper.timeago_tag
train
def timeago_tag(time, options = {}) options[:class] ||= "timeago" content_tag(:abbr, time.to_s, options.merge(:title => time.getutc.iso8601)) if time end
ruby
{ "resource": "" }
q3614
Sunrise.ActivitiesHelper.link_to_trackable
train
def link_to_trackable(object, object_type) model_name = object_type.downcase if object link_to(model_name, edit_path(:model_name => model_name.pluralize, :id => object.id)) else "a #{model_name} which does not exist anymore" end end
ruby
{ "resource": "" }
q3615
WADL.Address.deep_copy
train
def deep_copy address = Address.new( _deep_copy_array(@path_fragments), _deep_copy_array(@query_vars), _deep_copy_hash(@headers), @path_params.dup, @query_params.dup, @header_params.dup ) @auth.each { |header, value| address.auth(header, value) } address end
ruby
{ "resource": "" }
q3616
WADL.Address.bind!
train
def bind!(args = {}) path_var_values = args[:path] || {} query_var_values = args[:query] || {} header_var_values = args[:headers] || {} @auth.each { |header, value| header_var_values[header] = value }.clear # Bind variables found in the path fragments. path_params_to_delete = [] path_fragments.each { |fragment| if fragment.respond_to?(:to_str) # This fragment is a string which might contain {} substitutions. # Make any substitutions available to the provided path variables. self.class.embedded_param_names(fragment).each { |name| value = path_var_values[name] || path_var_values[name.to_sym] value = if param = path_params[name] path_params_to_delete << param param % value else Param.default.format(value, name) end fragment.gsub!("{#{name}}", value) } else # This fragment is an array of Param objects (style 'matrix' # or 'plain') which may be bound to strings. As substitutions # happen, the array will become a mixed array of Param objects # and strings. fragment.each_with_index { |param, i| next unless param.respond_to?(:name) name = param.name value = path_var_values[name] || path_var_values[name.to_sym] value = param % value fragment[i] = value if value path_params_to_delete << param } end } # Delete any embedded path parameters that are now bound from # our list of unbound parameters. path_params_to_delete.each { |p| path_params.delete(p.name) } # Bind query variable values to query parameters query_var_values.each { |name, value| param = query_params.delete(name.to_s) query_vars << param % value if param } # Bind header variables to header parameters header_var_values.each { |name, value| if param = header_params.delete(name.to_s) headers[name] = param % value else warn %Q{Ignoring unknown header parameter "#{name}"!} end } self end
ruby
{ "resource": "" }
q3617
Launchpad.Interaction.start
train
def start(opts = nil) logger.debug "starting Launchpad::Interaction##{object_id}" opts = { :detached => false }.merge(opts || {}) @active = true @reader_thread ||= Thread.new do begin while @active do @device.read_pending_actions.each do |action| action_thread = Thread.new(action) do |action| respond_to_action(action) end @action_threads.add(action_thread) end sleep @latency# if @latency > 0.0 end rescue Portmidi::DeviceError => e logger.fatal "could not read from device, stopping to read actions" raise CommunicationError.new(e) rescue Exception => e logger.fatal "error causing action reading to stop: #{e.inspect}" raise e ensure @device.reset end end @reader_thread.join unless opts[:detached] end
ruby
{ "resource": "" }
q3618
Launchpad.Interaction.stop
train
def stop logger.debug "stopping Launchpad::Interaction##{object_id}" @active = false if @reader_thread # run (resume from sleep) and wait for @reader_thread to end @reader_thread.run if @reader_thread.alive? @reader_thread.join @reader_thread = nil end ensure @action_threads.list.each do |thread| begin thread.kill thread.join rescue Exception => e logger.error "error when killing action thread: #{e.inspect}" end end nil end
ruby
{ "resource": "" }
q3619
Launchpad.Interaction.response_to
train
def response_to(types = :all, state = :both, opts = nil, &block) logger.debug "setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}" types = Array(types) opts ||= {} no_response_to(types, state) if opts[:exclusive] == true Array(state == :both ? %w(down up) : state).each do |state| types.each do |type| combined_types(type, opts).each do |combined_type| responses[combined_type][state.to_sym] << block end end end nil end
ruby
{ "resource": "" }
q3620
Launchpad.Interaction.no_response_to
train
def no_response_to(types = nil, state = :both, opts = nil) logger.debug "removing response to #{types.inspect} for state #{state.inspect}" types = Array(types) Array(state == :both ? %w(down up) : state).each do |state| types.each do |type| combined_types(type, opts).each do |combined_type| responses[combined_type][state.to_sym].clear end end end nil end
ruby
{ "resource": "" }
q3621
Launchpad.Interaction.grid_range
train
def grid_range(range) return nil if range.nil? Array(range).flatten.map do |pos| pos.respond_to?(:to_a) ? pos.to_a : pos end.flatten.uniq end
ruby
{ "resource": "" }
q3622
WebkitRemote.Event.matches?
train
def matches?(conditions) conditions.all? do |key, value| case key when :class, :type kind_of? value when :name name == value else # Simple cop-out. send(key) == value end end end
ruby
{ "resource": "" }
q3623
RailsStuff.Statusable.statusable_methods
train
def statusable_methods # Include generated methods with a module, not right in class. @statusable_methods ||= Module.new.tap do |m| m.const_set :ClassMethods, Module.new include m extend m::ClassMethods end end
ruby
{ "resource": "" }
q3624
Sunrise.AbstractModel.build_record
train
def build_record record = model.new record.send("#{parent_association.name}=", parent_record) if parent_record record.build_defaults if record.respond_to?(:build_defaults) record end
ruby
{ "resource": "" }
q3625
Sunrise.AbstractModel.apply_scopes
train
def apply_scopes(params = nil, pagination = true) raise ::AbstractController::ActionNotFound.new("List config is turn off") if without_index? params ||= @request_params scope = default_scope(params) if current_list == :tree scope = scope.roots elsif pagination scope = page_scope(scope, params[:page], params[:per]) end scope end
ruby
{ "resource": "" }
q3626
I3.Manpage.manpage
train
def manpage(name) return "** Can't find groff(1)" unless groff? require 'open3' out = nil Open3.popen3(groff_command) do |stdin, stdout, _| stdin.puts raw_manpage(name) stdin.close out = stdout.read.strip end out end
ruby
{ "resource": "" }
q3627
I3.Manpage.raw_manpage
train
def raw_manpage(name) if File.exists? file = File.dirname(__FILE__) + "/../../man/#{name}.1" File.read(file) else DATA.read end end
ruby
{ "resource": "" }
q3628
RailsStuff.RSpecHelpers.clear_logs
train
def clear_logs ::RSpec.configure do |config| config.add_setting :clear_log_file config.clear_log_file = Rails.root.join('log', 'test.log') if defined?(Rails.root) config.add_setting :clear_log_file_proc config.clear_log_file_proc = ->(file) do next unless file && File.exist?(file) FileUtils.cp(file, "#{file}.last") File.open(file, 'w').close end config.after(:suite) do instance_exec(config.clear_log_file, &config.clear_log_file_proc) unless ENV['KEEP_LOG'] end end end
ruby
{ "resource": "" }
q3629
WADL.RequestFormat.uri
train
def uri(resource, args = {}) uri = resource.uri(args) query_values = args[:query] || {} header_values = args[:headers] || {} params.each { |param| name = param.name if param.style == 'header' value = header_values[name] || header_values[name.to_sym] value = param % value uri.headers[name] = value if value else value = query_values[name] || query_values[name.to_sym] value = param.format(value, nil, 'query') uri.query << value if value && !value.empty? end } uri end
ruby
{ "resource": "" }
q3630
Launchpad.Device.change
train
def change(type, opts = nil) opts ||= {} status = %w(up down left right session user1 user2 mixer).include?(type.to_s) ? Status::CC : Status::ON output(status, note(type, opts), velocity(opts)) end
ruby
{ "resource": "" }
q3631
Launchpad.Device.change_all
train
def change_all(*colors) # ensure that colors is at least and most 80 elements long colors = colors.flatten[0..79] colors += [0] * (80 - colors.size) if colors.size < 80 # send normal MIDI message to reset rapid LED change pointer # in this case, set mapping mode to x-y layout (the default) output(Status::CC, Status::NIL, GridLayout::XY) # send colors in slices of 2 messages = [] colors.each_slice(2) do |c1, c2| messages << message(Status::MULTI, velocity(c1), velocity(c2)) end output_messages(messages) end
ruby
{ "resource": "" }
q3632
Launchpad.Device.buffering_mode
train
def buffering_mode(opts = nil) opts = { :display_buffer => 0, :update_buffer => 0, :copy => false, :flashing => false }.merge(opts || {}) data = opts[:display_buffer] + 4 * opts[:update_buffer] + 32 data += 16 if opts[:copy] data += 8 if opts[:flashing] output(Status::CC, Status::NIL, data) end
ruby
{ "resource": "" }
q3633
Launchpad.Device.output_messages
train
def output_messages(messages) if @output.nil? logger.error "trying to write to device that's not been initialized for output" raise NoOutputAllowedError end logger.debug "writing messages to launchpad:\n #{messages.join("\n ")}" if logger.debug? @output.write(messages) nil end
ruby
{ "resource": "" }
q3634
Impressbox.Provisioner.provision
train
def provision mass_loader('provision').each do |configurator| next unless configurator.can_be_configured?(@machine, @@__loaded_config) @machine.ui.info configurator.description if configurator.description configurator.configure @machine, @@__loaded_config end end
ruby
{ "resource": "" }
q3635
Impressbox.Provisioner.run_primaty_configuration
train
def run_primaty_configuration(root_config) old_root = root_config.dup old_loaded = @@__loaded_config.dup mass_loader('primary').each do |configurator| next unless configurator.can_be_configured?(old_root, old_loaded) @machine.ui.info configurator.description if configurator.description configurator.configure root_config, old_loaded end end
ruby
{ "resource": "" }
q3636
Impressbox.Provisioner.mass_loader
train
def mass_loader(type) namespace = 'Impressbox::Configurators::' + ucfirst(type) path = File.join('..', 'configurators', type) Impressbox::Objects::MassFileLoader.new namespace, path end
ruby
{ "resource": "" }
q3637
Impressbox.Provisioner.xaml_config
train
def xaml_config require_relative File.join('objects', 'config_file') file = detect_file(config.file) @machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file) Impressbox::Objects::ConfigFile.new file end
ruby
{ "resource": "" }
q3638
WebkitRemote.Client.wait_for
train
def wait_for(conditions) unless WebkitRemote::Event.can_receive? self, conditions raise ArgumentError, "Cannot receive event with #{conditions.inspect}" end events = [] each_event do |event| events << event break if event.matches?(conditions) end events end
ruby
{ "resource": "" }
q3639
Passphrase.Language.validate
train
def validate(language_list) language_list.each do |l| matches_language = @languages.any? { |language| language.match("^#{l}") } raise "No language match for #{l}" unless matches_language end end
ruby
{ "resource": "" }
q3640
YPetri::Agent::SimulationAspect.SimulationPoint.identify
train
def identify( name: nil, net: nil, cc: nil, imc: nil, ssc: nil, **nn ) name || { net: net, cc: cc, imc: imc, ssc: ssc }.merge( nn ) end
ruby
{ "resource": "" }
q3641
Danger.DangerConflictChecker.check_conflict_and_comment
train
def check_conflict_and_comment() results = check_conflict() results.each do |result| next if result[:mergeable] message = "<p>This PR conflicts with <a href=\"#{result[:pull_request][:html_url]}\">##{result[:pull_request][:number]}</a>.</p>" table = '<table><thead><tr><th width="100%">File</th><th>Line</th></tr></thead><tbody>' + result[:conflicts].map do |conflict| file = conflict[:file] line = conflict[:line] line_link = "#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}" "<tr><td>#{file}</td><td><a href=\"#{line_link}\">#L#{line}</a></td></tr>" end.join('') + '</tbody></table>' puts (message + table) warn("<div>" + message + table + "</div>") end results end
ruby
{ "resource": "" }
q3642
Ankusa.CassandraStorage.init_tables
train
def init_tables # Do nothing if keyspace already exists if @cassandra.keyspaces.include?(@keyspace) @cassandra.keyspace = @keyspace else freq_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "classes"}) # word => {classname => count} summary_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "totals"}) # class => {wordcount => count} ks_def = Cassandra::Keyspace.new({ :name => @keyspace, :strategy_class => 'org.apache.cassandra.locator.SimpleStrategy', :replication_factor => 1, :cf_defs => [freq_table, summary_table] }) @cassandra.add_keyspace ks_def @cassandra.keyspace = @keyspace end end
ruby
{ "resource": "" }
q3643
Ankusa.CassandraStorage.get_word_counts
train
def get_word_counts(word) # fetch all (class,count) pairs for a given word row = @cassandra.get(:classes, word.to_s) return row.to_hash if row.empty? row.inject({}){|counts, col| counts[col.first.to_sym] = [col.last.to_f,0].max; counts} end
ruby
{ "resource": "" }
q3644
Ankusa.CassandraStorage.incr_total_word_count
train
def incr_total_word_count(klass, count) klass = klass.to_s wordcount = @cassandra.get(:totals, klass, "wordcount").values.last.to_i wordcount += count @cassandra.insert(:totals, klass, {"wordcount" => wordcount.to_s}) @klass_word_counts[klass.to_sym] = wordcount end
ruby
{ "resource": "" }
q3645
Ankusa.CassandraStorage.incr_doc_count
train
def incr_doc_count(klass, count) klass = klass.to_s doc_count = @cassandra.get(:totals, klass, "doc_count").values.last.to_i doc_count += count @cassandra.insert(:totals, klass, {"doc_count" => doc_count.to_s}) @klass_doc_counts[klass.to_sym] = doc_count end
ruby
{ "resource": "" }
q3646
Ankusa.CassandraStorage.get_summary
train
def get_summary(name) counts = {} @cassandra.get_range(:totals, {:start => '', :finish => '', :count => @max_classes}).each do |key_slice| # keyslice is a clunky thrift object, map into a ruby hash row = key_slice.columns.inject({}){|hsh, c| hsh[c.column.name] = c.column.value; hsh} counts[key_slice.key.to_sym] = row[name].to_f end counts end
ruby
{ "resource": "" }
q3647
CrossValidation.Runner.valid?
train
def valid? @errors = [] @critical_keys.each do |k| any_error = public_send(k).nil? @errors << k if any_error end @errors.size == 0 end
ruby
{ "resource": "" }
q3648
CrossValidation.Runner.run
train
def run fail_if_invalid partitions = Partitioner.subset(documents, k) results = partitions.map.with_index do |part, i| training_samples = Partitioner.exclude_index(documents, i) classifier_instance = classifier.call() train(classifier_instance, training_samples) # fetch confusion keys part.each do |x| prediction = classify(classifier_instance, x) matrix.store(prediction, fetch_sample_class.call(x)) end end matrix end
ruby
{ "resource": "" }
q3649
Medium.Publications.create_post
train
def create_post(publication, opts) response = @client.post "publications/#{publication['id']}/posts", build_request_with(opts) Medium::Client.validate response end
ruby
{ "resource": "" }
q3650
Okta.Jwt.sign_in_user
train
def sign_in_user(username:, password:, client_id:, client_secret:, scope: 'openid') client(issuer).post do |req| req.url "/oauth2/#{auth_server_id}/v1/token" req.headers['Content-Type'] = 'application/x-www-form-urlencoded' req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}") req.body = URI.encode_www_form username: username, password: password, scope: scope, grant_type: 'password' end end
ruby
{ "resource": "" }
q3651
Okta.Jwt.sign_in_client
train
def sign_in_client(client_id:, client_secret:, scope:) client(issuer).post do |req| req.url "/oauth2/#{auth_server_id}/v1/token" req.headers['Content-Type'] = 'application/x-www-form-urlencoded' req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}") req.body = URI.encode_www_form scope: scope, grant_type: 'client_credentials' end end
ruby
{ "resource": "" }
q3652
Okta.Jwt.verify_token
train
def verify_token(token, issuer:, audience:, client_id:) header, payload = token.split('.').first(2).map{|encoded| JSON.parse(Base64.decode64(encoded))} # validate claims raise InvalidToken.new('Invalid issuer') if payload['iss'] != issuer raise InvalidToken.new('Invalid audience') if payload['aud'] != audience raise InvalidToken.new('Invalid client') if !Array(client_id).include?(payload['cid']) raise InvalidToken.new('Token is expired') if payload['exp'].to_i <= Time.now.to_i # validate signature jwk = JSON::JWK.new(get_jwk(header, payload)) JSON::JWT.decode(token, jwk.to_key) end
ruby
{ "resource": "" }
q3653
Okta.Jwt.get_jwk
train
def get_jwk(header, payload) kid = header['kid'] # cache hit return JWKS_CACHE[kid] if JWKS_CACHE[kid] # fetch jwk logger.info("[Okta::Jwt] Fetching public key: kid => #{kid} ...") if logger jwks_response = client(payload['iss']).get do |req| req.url get_metadata(payload)['jwks_uri'] end jwk = JSON.parse(jwks_response.body)['keys'].find do |key| key.dig('kid') == kid end # cache and return the key jwk.tap{JWKS_CACHE[kid] = jwk} end
ruby
{ "resource": "" }
q3654
CrossValidation.ConfusionMatrix.store
train
def store(actual, truth) key = @keys_for.call(truth, actual) if @values.key?(key) @values[key] += 1 else fail IndexError, "#{key} not found in confusion matrix" end self end
ruby
{ "resource": "" }
q3655
CrossValidation.ConfusionMatrix.fscore
train
def fscore(beta) b2 = Float(beta**2) ((b2 + 1) * precision * recall) / (b2 * precision + recall) end
ruby
{ "resource": "" }
q3656
EvalHook.HookHandler.packet
train
def packet(code) @global_variable_name = nil partialruby_packet = partialruby_context.packet(code) @all_packets ||= [] newpacket = EvalHook::Packet.new(partialruby_packet, @global_variable_name) @all_packets << newpacket newpacket end
ruby
{ "resource": "" }
q3657
Fastr.Application.boot
train
def boot Thread.new do sleep 1 until EM.reactor_running? begin log.info "Loading application..." app_init load_settings Fastr::Plugin.load(self) load_app_classes setup_router setup_watcher log.info "Application loaded successfully." @booting = false plugin_after_boot rescue Exception => e log.error "#{e}" puts e.backtrace log.fatal "Exiting due to previous errors..." exit(1) end end end
ruby
{ "resource": "" }
q3658
Fastr.Application.load_app_classes
train
def load_app_classes @@load_paths.each do |name, path| log.debug "Loading #{name} classes..." Dir["#{self.app_path}/#{path}"].each do |f| log.debug "Loading: #{f}" load(f) end end end
ruby
{ "resource": "" }
q3659
Fastr.Application.setup_watcher
train
def setup_watcher this = self Handler.send(:define_method, :app) do this end @@load_paths.each do |name, path| Dir["#{self.app_path}/#{path}"].each do |f| EM.watch_file(f, Handler) end end end
ruby
{ "resource": "" }
q3660
Datomic.Client.transact
train
def transact(dbname, data) data = transmute_data(data) RestClient.post(db_url(dbname) + "/", {"tx-data" => data}, :Accept => 'application/edn', &HANDLE_RESPONSE) end
ruby
{ "resource": "" }
q3661
Datomic.Client.query
train
def query(query, args_or_dbname, params = {}) query = transmute_data(query) args = args_or_dbname.is_a?(String) ? [db_alias(args_or_dbname)] : args_or_dbname args = transmute_data(args) get root_url("api/query"), params.merge(:q => query, :args => args) end
ruby
{ "resource": "" }
q3662
LatoView.ApplicationHelper.view
train
def view(*names) # mantain compatibility with old cells (lato_view 1.0) if names.length === 1 puts "YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE" old_cell = "LatoView::CellsV1::#{names.first.capitalize}::Cell".constantize return old_cell end # return correct cell cell_class = "LatoView::" names.each do |name| cell_class = "#{cell_class}#{name.capitalize}::" end cell_class = "#{cell_class}Cell".constantize return cell_class end
ruby
{ "resource": "" }
q3663
LatoView.Interface::Images.view_getSidebarLogo
train
def view_getSidebarLogo return VIEW_SIDEBARLOGO if defined? VIEW_SIDEBARLOGO dir = "#{Rails.root}/app/assets/images/lato/" if File.exist?("#{dir}/sidebar_logo.svg") return "lato/sidebar_logo.svg" end if File.exist?("#{dir}/sidebar_logo.png") return "lato/sidebar_logo.png" end if File.exist?("#{dir}/sidebar_logo.jpg") return "lato/sidebar_logo.jpg" end if File.exist?("#{dir}/sidebar_logo.gif") return "lato/sidebar_logo.gif" end return view_getApplicationLogo end
ruby
{ "resource": "" }
q3664
LatoView.Interface::Images.view_getLoginLogo
train
def view_getLoginLogo return VIEW_LOGINLOGO if defined? VIEW_LOGINLOGO dir = "#{Rails.root}/app/assets/images/lato/" if File.exist?("#{dir}/login_logo.svg") return "lato/login_logo.svg" end if File.exist?("#{dir}/login_logo.png") return "lato/login_logo.png" end if File.exist?("#{dir}/login_logo.jpg") return "lato/login_logo.jpg" end if File.exist?("#{dir}/login_logo.gif") return "lato/login_logo.gif" end return view_getApplicationLogo end
ruby
{ "resource": "" }
q3665
LatoView.Interface::Images.view_getApplicationLogo
train
def view_getApplicationLogo return VIEW_APPLOGO if defined? VIEW_APPLOGO dir = "#{Rails.root}/app/assets/images/lato/" if File.exist?("#{dir}/logo.svg") return "lato/logo.svg" end if File.exist?("#{dir}/logo.png") return "lato/logo.png" end if File.exist?("#{dir}/logo.jpg") return "lato/logo.jpg" end if File.exist?("#{dir}/logo.gif") return "lato/logo.gif" end return false end
ruby
{ "resource": "" }
q3666
Fastr.Dispatch.dispatch
train
def dispatch(env) return [500, {'Content-Type' => 'text/plain'}, ["Server Not Ready"]] if @booting begin new_env = plugin_before_dispatch(env) plugin_after_dispatch(new_env, do_dispatch(new_env)) rescue Exception => e bt = e.backtrace.join("\n") [500, {'Content-Type' => 'text/plain'}, ["Exception: #{e}\n\n#{bt}"]] end end
ruby
{ "resource": "" }
q3667
Fastr.Dispatch.do_dispatch
train
def do_dispatch(env) path = env['PATH_INFO'] # Try to serve a public file ret = dispatch_public(env, path) return ret if not ret.nil? log.debug "Checking for routes that match: #{path}" route = router.match(env) if route.has_key? :ok dispatch_controller(route, env) else [404, {"Content-Type" => "text/plain"}, ["404 Not Found: #{path}"]] end end
ruby
{ "resource": "" }
q3668
Fastr.Dispatch.setup_controller
train
def setup_controller(controller, env, vars) controller.env = env controller.headers = {} setup_controller_params(controller, env, vars) controller.cookies = Fastr::HTTP.parse_cookies(env) controller.app = self end
ruby
{ "resource": "" }
q3669
Fastr.Dispatch.setup_controller_params
train
def setup_controller_params(controller, env, vars) if Fastr::HTTP.method?(env, :get) controller.get_params = Fastr::HTTP.parse_query_string(env['QUERY_STRING']) controller.params = controller.get_params.merge(vars) elsif Fastr::HTTP.method?(env, :post) controller.post_params = {} controller.post_params = Fastr::HTTP.parse_query_string(env['rack.input'].read) if env['rack.input'] controller.params = controller.post_params.merge(vars) else controller.params = vars end end
ruby
{ "resource": "" }
q3670
Fastr.Dispatch.plugin_before_dispatch
train
def plugin_before_dispatch(env) new_env = env self.plugins.each do |plugin| if plugin.respond_to? :before_dispatch new_env = plugin.send(:before_dispatch, self, env) end end new_env end
ruby
{ "resource": "" }
q3671
Fastr.Dispatch.plugin_after_dispatch
train
def plugin_after_dispatch(env, response) new_response = response self.plugins.each do |plugin| if plugin.respond_to? :after_dispatch new_response = plugin.send(:after_dispatch, self, env, response) end end new_response end
ruby
{ "resource": "" }
q3672
Filepreviews.CLI.options
train
def options(opts) opts.version = Filepreviews::VERSION opts.banner = BANNER opts.set_program_name 'Filepreviews.io' opts.on('-k', '--api_key [key]', String, 'use API key from Filepreviews.io') do |api_key| Filepreviews.api_key = api_key end opts.on('-s', '--secret_key [key]', String, 'use Secret key from Filepreviews.io') do |secret_key| Filepreviews.secret_key = secret_key end opts.on('-m', '--metadata', 'load metadata response') do @metadata = true end opts.on_tail('-v', '--version', 'display the version of Filepreviews') do puts opts.version exit end opts.on_tail('-h', '--help', 'print this help') do puts opts.help exit end end
ruby
{ "resource": "" }
q3673
Filepreviews.CLI.parse
train
def parse opts = OptionParser.new(&method(:options)) opts.parse!(@args) return opts.help if @args.last.nil? file_preview = Filepreviews.generate(@args.last) @metadata ? file_preview.metadata(js: true) : file_preview end
ruby
{ "resource": "" }
q3674
Ownlan.Configuration.source_mac
train
def source_mac @source_mac ||= if self.victim_ip ::ServiceObjects::NetworkInformation.self_mac(interface) else gateway_ip = ServiceObjects::NetworkInformation.gateway_ip mac = ::Ownlan::Attack::Base.new(self).ip_to_mac(gateway_ip) end end
ruby
{ "resource": "" }
q3675
Passphrase.DicewareRandom.die_rolls
train
def die_rolls(number_of_words) # The Diceware method specifies five rolls of the die for each word. die_rolls_per_word = 5 total_die_rolls = number_of_words * die_rolls_per_word die_roll_sequence = generate_random_numbers(total_die_rolls, 6, 1) group_die_rolls(die_roll_sequence, number_of_words, die_rolls_per_word) end
ruby
{ "resource": "" }
q3676
Filepreviews.Utils.process_params
train
def process_params(params) parameters = { url: CGI.unescape(params.url) } if params.metadata parameters[:metadata] = extract_metadata(params.metadata) end parameters end
ruby
{ "resource": "" }
q3677
Fastr.Router.match
train
def match(env) self.routes.each do |info| # If the route didn't specify method(s) to limit by, then all HTTP methods are valid. # If the route specified method(s), we check the request's HTTP method and validate # that it exists in that list. next unless info[:methods].nil? or info[:methods].include?(env["REQUEST_METHOD"].downcase.to_sym) match = env['PATH_INFO'].match(info[:regex]) # See if a route matches if not match.nil? # Map any parameters in our matched string vars = {} info[:vars].each_index do |i| var = info[:vars][i] vars[var] = match[i+1] end return {:ok => vars.merge!(info[:hash]) } end end {:error => :not_found} end
ruby
{ "resource": "" }
q3678
Fastr.Router.for
train
def for(path, *args) arg = args[0] log.debug "Adding route, path: #{path}, args: #{args.inspect}" match = get_regex_for_route(path, arg) hash = get_to_hash(arg) route_info = {:regex => match[:regex], :args => arg, :vars => match[:vars], :hash => hash} # Add the HTTP methods for this route if they exist in options route_info[:methods] = arg[:methods] if not arg.nil? and arg.has_key? :methods self.routes.push(route_info) end
ruby
{ "resource": "" }
q3679
URI.Redis.conf
train
def conf hsh = { :host => host, :port => port, :db => db }.merge parse_query(query) hsh[:password] = password if password hsh end
ruby
{ "resource": "" }
q3680
LatoView.Interface::Themes.view_getCurrentTemplateName
train
def view_getCurrentTemplateName return VIEW_CURRENTTEMPLATENAME if defined? VIEW_CURRENTTEMPLATENAME directory = core_getCacheDirectory if File.exist? "#{directory}/view.yml" # accedo al view.yml config = YAML.load( File.read(File.expand_path("#{directory}/view.yml", __FILE__)) ) # verifico esistenza dati if !config || !config['template'] return false end # verifico che il template sia valido unless VIEW_TEMPLATES.include? config['template'] raise 'Template value is not correct on view.yml config file' and return false end # ritorno nome template return config['template'] else return false end end
ruby
{ "resource": "" }
q3681
RapGenius.Artist.songs
train
def songs(options = {page: 1}) songs_url = "/artists/#{@id}/songs/?page=#{options[:page]}" fetch(songs_url)["response"]["songs"].map do |song| Song.new( artist: Artist.new( name: song["primary_artist"]["name"], id: song["primary_artist"]["id"], type: :primary ), title: song["title"], id: song["id"] ) end end
ruby
{ "resource": "" }
q3682
LatoView.Interface::Assets.view_getApplicationsAssetsItems
train
def view_getApplicationsAssetsItems return VIEW_APPASSETS if defined? VIEW_APPASSETS # inizializzo la lista delle voci della navbar assets = [] directory = core_getCacheDirectory if File.exist? "#{directory}/view.yml" # accedo al view.yml config = YAML.load( File.read(File.expand_path("#{directory}/view.yml", __FILE__)) ) # estraggo i dati dallo yaml data = getConfigAssets(config) # aggiungo i dati nella risposta data.each do |single_asset| assets.push(single_asset) end end # ritorno il risultato return assets end
ruby
{ "resource": "" }
q3683
Filepreviews.HTTP.default_connection
train
def default_connection(url = BASE_URL, debug = false) Faraday.new(url: url) do |conn| conn.adapter :typhoeus conn.headers[:user_agent] = USER_AGENT conn.headers[:content_type] = 'application/json' configure_api_auth_header(conn.headers) configure_logger(conn) if debug end end
ruby
{ "resource": "" }
q3684
Filepreviews.HTTP.prepare_request
train
def prepare_request(params) request = process_params(params) request.store(:sizes, [extract_size(params.size)]) if params.size request.store(:format, params.format) if params.format request.store(:data, params.data) if params.data request.store(:uploader, params.uploader) if params.uploader request.store(:pages, params.pages) if params.pages request end
ruby
{ "resource": "" }
q3685
Filepreviews.HTTP.fetch
train
def fetch(params, endpoint_path = 'previews') options = prepare_request(params) response = default_connection(BASE_URL, params.debug) .post do |req| req.url("/v2/#{endpoint_path}/") req.body = JSON.generate(options) end parse(response.body) end
ruby
{ "resource": "" }
q3686
SkyJam.Client.loadalltracks
train
def loadalltracks uri = URI(@service_url + 'loadalltracks') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true req = Net::HTTP::Post.new(uri.path) req.set_form_data('u' => 0, 'xt' => @cookie) req['Authorization'] = 'GoogleLogin auth=%s' % @auth res = http.request(req) unless res.is_a? Net::HTTPSuccess fail Error, 'loadalltracks failed: #{res.code}' end JSON.parse(res.body) end
ruby
{ "resource": "" }
q3687
SkyJam.Client.mac_addr
train
def mac_addr case RUBY_PLATFORM when /darwin/ if (m = `ifconfig en0`.match(/ether (\S{17})/)) m[1].upcase end when /linux/ devices = Dir['/sys/class/net/*/address'].reject { |a| a =~ %r{/lo/} } dev = devices.first File.read(dev).chomp.upcase end end
ruby
{ "resource": "" }
q3688
Rediska.Driver.zscan_each
train
def zscan_each(key, *args, &block) data_type_check(key, ZSet) return [] unless data[key] return to_enum(:zscan_each, key, options) unless block_given? cursor = 0 loop do cursor, values = zscan(key, cursor, options) values.each(&block) break if cursor == '0' end end
ruby
{ "resource": "" }
q3689
Storexplore.WalkerPage.get_all
train
def get_all(selector, separator) elements = @mechanize_page.search(selector) throw_if_empty(elements, "elements", selector) (elements.map &:text).join(separator) end
ruby
{ "resource": "" }
q3690
TaskMapper::Provider.Helper.easy_finder
train
def easy_finder(api, symbol, options, at_index = 0) if api.is_a? Class return api if options.length == 0 and symbol == :first options.insert(at_index, symbol) if options[at_index].is_a?(Hash) api.find(*options) else raise TaskMapper::Exception.new("#{Helper.name}::#{this_method} method must be implemented by the provider") end end
ruby
{ "resource": "" }
q3691
TaskMapper::Provider.Helper.search_by_attribute
train
def search_by_attribute(things, options = {}, limit = 1000) things.find_all do |thing| options.inject(true) do |memo, kv| break unless memo key, value = kv begin memo &= thing.send(key) == value rescue NoMethodError memo = false end memo end and (limit -= 1) > 0 end end
ruby
{ "resource": "" }
q3692
Daemonizer::Stats.MemoryStats.determine_private_dirty_rss
train
def determine_private_dirty_rss(pid) total = 0 File.read("/proc/#{pid}/smaps").split("\n").each do |line| line =~ /^(Private)_Dirty: +(\d+)/ if $2 total += $2.to_i end end if total == 0 return nil else return total end rescue Errno::EACCES, Errno::ENOENT return nil end
ruby
{ "resource": "" }
q3693
Ankusa.Classifier.train
train
def train(klass, text) th = TextHash.new(text) th.each { |word, count| @storage.incr_word_count klass, word, count yield word, count if block_given? } @storage.incr_total_word_count klass, th.word_count doccount = (text.kind_of? Array) ? text.length : 1 @storage.incr_doc_count klass, doccount @classnames << klass unless @classnames.include? klass # cache is now dirty of these vars @doc_count_totals = nil @vocab_sizes = nil th end
ruby
{ "resource": "" }
q3694
Trakt.Show.unseen
train
def unseen(title) all = seasons title episodes_per_season = {} episodes_to_remove = [] all.each do |season_info| season_num = season_info['season'] next if season_num == 0 # dont need to remove specials episodes = season_info['episodes'] 1.upto(episodes) do |episode| episodes_to_remove << { season: season_num, episode: episode } end end episode_unseen tvdb_id: title, episodes: episodes_to_remove end
ruby
{ "resource": "" }
q3695
Colorist.Color.+
train
def +(other_color) other_color = Colorist::Color.from(other_color) color = self.dup color.r += other_color.r color.g += other_color.g color.b += other_color.b color end
ruby
{ "resource": "" }
q3696
Colorist.Color.to_hsv
train
def to_hsv red, green, blue = *[r, g, b].collect {|x| x / 255.0} max = [red, green, blue].max min = [red, green, blue].min if min == max hue = 0 elsif max == red hue = 60 * ((green - blue) / (max - min)) elsif max == green hue = 60 * ((blue - red) / (max - min)) + 120 elsif max == blue hue = 60 * ((red - green) / (max - min)) + 240 end saturation = (max == 0) ? 0 : (max - min) / max [hue % 360, saturation, max] end
ruby
{ "resource": "" }
q3697
Colorist.Color.gradient_to
train
def gradient_to(color, steps = 10) color_to = Colorist::Color.from(color) red = color_to.r - r green = color_to.g - g blue = color_to.b - b result = (1..(steps - 3)).to_a.collect do |step| percentage = step.to_f / (steps - 1) Color.from_rgb(r + (red * percentage), g + (green * percentage), b + (blue * percentage)) end # Add first and last colors to result, avoiding uneccessary calculation and rounding errors result.unshift(self.dup) result.push(color.dup) result end
ruby
{ "resource": "" }
q3698
Gematria.TableManager.add_table
train
def add_table(name, table) if table.is_a? Hash tables[name.to_sym] = table else raise TypeError, 'Invalid table format' end end
ruby
{ "resource": "" }
q3699
Debugger.FrameFunctions.get_pr_arguments_with_xml
train
def get_pr_arguments_with_xml(mark, *args) res = get_pr_arguments_without_xml((!!mark).to_s, *args) res[:file] = File.expand_path(res[:file]) res end
ruby
{ "resource": "" }