_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q9100
Kharon.Processor.contains?
train
def contains?(key, values, required_values) raise_error(type: "contains.values", required: required_values, key: key) if (values & required_values) != required_values end
ruby
{ "resource": "" }
q9101
Kharon.Processor.has_keys?
train
def has_keys?(key, required_keys) raise_error(type: "contains.keys", required: required_keys, key: key) if (validator.datas[key].keys & required_keys) != required_keys end
ruby
{ "resource": "" }
q9102
LatoBlog.Interface::Tags.blog__clean_tag_parents
train
def blog__clean_tag_parents tag_parents = LatoBlog::TagParent.all tag_parents.map { |tp| tp.destroy if tp.tags.empty? } end
ruby
{ "resource": "" }
q9103
LatoBlog.Interface::Tags.blog__get_tags
train
def blog__get_tags( order: nil, language: nil, search: nil, page: nil, per_page: nil ) tags = LatoBlog::Tag.all # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' tags = _tags_filter_by_order(tags, order) tags = _tags_filter_by_language(tags, language) tags = _tags_filter_search(tags, search) # take tags uniqueness tags = tags.uniq(&:id) # save total tags total = tags.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 tags = core__paginate_array(tags, per_page, page) # return result { tags: tags && !tags.empty? ? tags.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
ruby
{ "resource": "" }
q9104
LatoBlog.Interface::Tags.blog__get_category
train
def blog__get_category(id: nil, permalink: nil) return {} unless id || permalink if id category = LatoBlog::Category.find_by(id: id.to_i) else category = LatoBlog::Category.find_by(meta_permalink: permalink) end category.serialize end
ruby
{ "resource": "" }
q9105
Redstruct.Set.random
train
def random(count: 1) list = self.connection.srandmember(@key, count) return nil if list.nil? return count == 1 ? list[0] : ::Set.new(list) end
ruby
{ "resource": "" }
q9106
Redstruct.Set.difference
train
def difference(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sdiff(@key, other.key)) else self.connection.sdiffstore(destination.key, @key, other.key) end return results end
ruby
{ "resource": "" }
q9107
Redstruct.Set.intersection
train
def intersection(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sinter(@key, other.key)) else self.connection.sinterstore(destination.key, @key, other.key) end return results end
ruby
{ "resource": "" }
q9108
Redstruct.Set.union
train
def union(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sunion(@key, other.key)) else self.connection.sunionstore(destination.key, @key, other.key) end return results end
ruby
{ "resource": "" }
q9109
ExecEnv.Env.exec
train
def exec (*args, &block) if @scope @scope.instance_variables.each do |name| instance_variable_set(name, @scope.instance_variable_get(name)) end end @ivars.each do |name, value| instance_variable_set(name, value) end instance_exec(*args, &block) end
ruby
{ "resource": "" }
q9110
Scrapah.Scraper.process_appropriate
train
def process_appropriate(doc,cmd) return process_regex(doc,cmd) if(cmd.is_a? Regexp) return process_proc(doc,cmd) if(cmd.is_a? Proc) if cmd.is_a?(String) return process_xpath(doc,cmd) if cmd.start_with?("x|") return process_css(doc,cmd) if cmd.start_with?("c|") end nil end
ruby
{ "resource": "" }
q9111
Derelict.Connection.validate!
train
def validate! logger.debug "Starting validation for #{description}" raise NotFound.new path unless File.exists? path logger.info "Successfully validated #{description}" self end
ruby
{ "resource": "" }
q9112
Seedsv.CsvSeed.seed_model
train
def seed_model(model_class, options={}) if model_class.count == 0 or options[:force] table_name = options[:file_name] || model_class.table_name puts "Seeding #{model_class.to_s.pluralize}..." csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true) seed_from_csv(model_class, csv_file) end end
ruby
{ "resource": "" }
q9113
Seedsv.CsvSeed.seed_from_csv
train
def seed_from_csv(migration_class, csv_file) migration_class.transaction do csv_file.each do |line_values| record = migration_class.new line_values.to_hash.keys.map{|attribute| record.send("#{attribute.strip}=",line_values[attribute].strip) rescue nil} record.save(:validate => false) end end end
ruby
{ "resource": "" }
q9114
Edoors.Particle.add_dsts
train
def add_dsts *dsts dsts.each do |dst| if dst.empty? or dst==Edoors::ACT_SEP or dst[0]==Edoors::PATH_SEP \ or dst=~/\/\?/ or dst=~/\/{2,}/ or dst=~/\s+/ raise Edoors::Exception.new "destination #{dst} is not acceptable" end @dsts << dst end end
ruby
{ "resource": "" }
q9115
Edoors.Particle.set_dst!
train
def set_dst! a, d @action = a if d.is_a? Edoors::Iota @dst = d else @dst = nil _split_path! d end end
ruby
{ "resource": "" }
q9116
Edoors.Particle.apply_link!
train
def apply_link! lnk init! lnk.door clear_dsts! add_dsts *lnk.dsts set_link_keys *lnk.keys end
ruby
{ "resource": "" }
q9117
Edoors.Particle.set_link_keys
train
def set_link_keys *args @link_keys.clear if not @link_keys.empty? args.compact! args.each do |lf| @link_keys << lf end @link_value = @payload.select { |k,v| @link_keys.include? k } end
ruby
{ "resource": "" }
q9118
Edoors.Particle.link_with?
train
def link_with? link return true if link.value.nil? link.value.keys.inject({}) { |h,k| h[k]=@payload[k] if @payload.has_key?(k); h }.eql? link.value end
ruby
{ "resource": "" }
q9119
Edoors.Particle.clear_merged!
train
def clear_merged! r=false @merged.each do |p| p.clear_merged! r r.release_p p if r end @merged.clear end
ruby
{ "resource": "" }
q9120
PlayOverwatch.Scraper.sr
train
def sr comp_div = @player_page.css('.competitive-rank > .h5') return -1 if comp_div.empty? content = comp_div.first.content content.to_i if Integer(content) rescue -1 end
ruby
{ "resource": "" }
q9121
PlayOverwatch.Scraper.main_qp
train
def main_qp hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
ruby
{ "resource": "" }
q9122
PlayOverwatch.Scraper.main_comp
train
def main_comp hero_img = hidden_mains_style.content.scan(/\.competitive {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
ruby
{ "resource": "" }
q9123
Spear.Request.to_xml
train
def to_xml(body) root = @api_options[:root_element].nil? ? 'Request' : @api_options[:root_element] body.to_xml(root: root, skip_instruct: true, skip_types: true) end
ruby
{ "resource": "" }
q9124
Ripl::Profiles.Runner.parse_option
train
def parse_option( option, argv ) if option =~ /(?:-p|--profile)=?(.*)/ Ripl::Profiles.load( ($1.empty? ? argv.shift.to_s : $1).split(':') ) else super end end
ruby
{ "resource": "" }
q9125
NewTime.NewTime.convert
train
def convert(point) today = Date.new(year, month, day) new_seconds = seconds + fractional + (minutes + hours * 60) * 60 # During daylight hours? if hours >= 6 && hours < 18 start = NewTime.sunrise(today, point) finish = NewTime.sunset(today, point) new_start_hour = 6 else # Is it before sunrise or after sunset? if hours < 6 start = NewTime.sunset(today - 1, point) finish = NewTime.sunrise(today, point) new_start_hour = 18 - 24 else start = NewTime.sunset(today, point) finish = NewTime.sunrise(today + 1, point) new_start_hour = 18 end end start + (new_seconds.to_f / (60 * 60) - new_start_hour) * (finish - start) / 12 end
ruby
{ "resource": "" }
q9126
Smsified.Reporting.delivery_status
train
def delivery_status(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? options[:sender_address] = options[:sender_address] || @sender_address Response.new self.class.get("/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
ruby
{ "resource": "" }
q9127
Disqussion.Threads.list
train
def list(*args) options = args.last.is_a?(Hash) ? args.pop : {} response = get('threads/list', options) end
ruby
{ "resource": "" }
q9128
Disqussion.Threads.listPosts
train
def listPosts(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = get('threads/listPosts', options) end
ruby
{ "resource": "" }
q9129
Disqussion.Threads.remove
train
def remove(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = post('threads/remove', options) end
ruby
{ "resource": "" }
q9130
Ruote.MongoDbStorage.dump
train
def dump(type) get_many(type).map{|d|d.to_s}.sort.join("\n") end
ruby
{ "resource": "" }
q9131
Kelp.Field.select_or_fill
train
def select_or_fill(field, value) case field_type(field) when :select begin select(value, :from => field) rescue Capybara::ElementNotFound raise Kelp::OptionNotFound, "Field '#{field}' has no option '#{value}'" end when :fillable_field fill_in(field, :with => value) end end
ruby
{ "resource": "" }
q9132
Kelp.Field.field_should_be_empty
train
def field_should_be_empty(field, scope={}) in_scope(scope) do _field = nice_find_field(field) if !(_field.nil? || _field.value.nil? || _field.value.strip == '') raise Kelp::Unexpected, "Expected field '#{field}' to be empty, but value is '#{_field.value}'" end end end
ruby
{ "resource": "" }
q9133
Kelp.Field.field_value
train
def field_value(field) element = find_field(field) value = (element.tag_name == 'textarea') ? element.text : element.value # If field value is an Array, take the first item if value.class == Array value = value.first end return value.to_s end
ruby
{ "resource": "" }
q9134
Kelp.Field.fields_should_contain
train
def fields_should_contain(field_values, scope={}) in_scope(scope) do field_values.each do |field, value| _field = find_field(field) # For nil/empty, check for nil field or nil value if value.nil? or value.strip.empty? field_should_be_empty(field) # If field is a dropdown elsif _field.tag_name == 'select' dropdown_should_equal(field, value) # Otherwise treat as a text field else field_should_contain(field, value) end end end end
ruby
{ "resource": "" }
q9135
Kelp.Field.field_type
train
def field_type(field) select = all(:select, field).count fillable = all(:fillable_field, field).count count = select + fillable case count when 0 raise Kelp::FieldNotFound, "No field with id, name, or label '#{field}' found" when 1 return select > 0 ? :select : :fillable_field else raise Kelp::AmbiguousField, "Field '#{field}' is ambiguous" end end
ruby
{ "resource": "" }
q9136
Octo.KafkaBridge.create_message
train
def create_message(message) begin @producer.produce(JSON.dump(message), topic: @topic) rescue Kafka::BufferOverflow Octo.logger.error 'Buffer Overflow. Sleeping for 1s' sleep 1 retry end end
ruby
{ "resource": "" }
q9137
ActsAsReferred.InstanceMethods.create_referrer
train
def create_referrer # will not respond to _get_reqref unless # reqref injected in application-controller # if self.respond_to?(:_get_reqref) if struct = _get_reqref self.create_referee( origin: struct.referrer_url, request: struct.request_url, visits: struct.visit_count ) end end end
ruby
{ "resource": "" }
q9138
Baha.Config.init_docker!
train
def init_docker! Docker.options = @options set_docker_url LOG.debug { "Docker URL: #{Docker.url}"} LOG.debug { "Docker Options: #{Docker.options.inspect}"} Docker.validate_version! end
ruby
{ "resource": "" }
q9139
Logsly::Logging182::Appenders.Buffering.immediate_at=
train
def immediate_at=( level ) @immediate.clear # get the immediate levels -- no buffering occurs at these levels, and # a log message is written to the logging destination immediately immediate_at = case level when String; level.split(',').map {|x| x.strip} when Array; level else Array(level) end immediate_at.each do |lvl| num = ::Logsly::Logging182.level_num(lvl) next if num.nil? @immediate[num] = true end end
ruby
{ "resource": "" }
q9140
MIPPeR.LinExpr.add
train
def add(other) case other when LinExpr @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 } when Variable if @terms.key? other @terms[other] += 1.0 else @terms[other] = 1.0 end else fail TypeError end self end
ruby
{ "resource": "" }
q9141
MIPPeR.LinExpr.inspect
train
def inspect @terms.map do |var, coeff| # Skip if the coefficient is zero or the value is zero value = var.value next if coeff == 0 || value == 0 || value == false coeff == 1 ? var.name : "#{var.name} * #{coeff}" end.compact.join(' + ') end
ruby
{ "resource": "" }
q9142
NsOptions.Option.value
train
def value val = self.lazy_proc?(@value) ? self.coerce(@value.call) : @value val.respond_to?(:returned_value) ? val.returned_value : val end
ruby
{ "resource": "" }
q9143
Demolisher.Node.method_missing
train
def method_missing(meth, *args, &block) # :nodoc: xpath = _xpath_for_element(meth.to_s, args.shift) return nil if xpath.empty? if block_given? xpath.each_with_index do |node, idx| @nodes.push(node) case block.arity when 1 yield idx when 2 yield self.class.new(node, @namespaces, false), idx else yield end @nodes.pop end self else node = xpath.first if node.xpath('text()').length == 1 content = node.xpath('text()').first.content case meth.to_s when /\?$/ !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content) else content end else self.class.new(node, @namespaces, false) end end end
ruby
{ "resource": "" }
q9144
XML.Mapping.write_xml
train
def write_xml(options = { mapping: :_default }) xml = save_to_xml(options) formatter = REXML::Formatters::Pretty.new formatter.compact = true io = ::StringIO.new formatter.write(xml, io) io.string end
ruby
{ "resource": "" }
q9145
CertMunger.ClassMethods.to_cert
train
def to_cert(raw_cert) logger.debug "CertMunger raw_cert:\n#{raw_cert}" new_cert = build_cert(raw_cert) logger.debug "CertMunger reformatted_cert:\n#{new_cert}" logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert' OpenSSL::X509::Certificate.new new_cert end
ruby
{ "resource": "" }
q9146
CertMunger.ClassMethods.build_cert
train
def build_cert(raw_cert) tmp_cert = ['-----BEGIN CERTIFICATE-----'] cert_contents = if raw_cert.lines.count == 1 one_line_contents(raw_cert) else multi_line_contents(raw_cert) end tmp_cert << cert_contents.flatten # put mixed space lines as own elements tmp_cert << '-----END CERTIFICATE-----' tmp_cert.join("\n").rstrip end
ruby
{ "resource": "" }
q9147
CertMunger.ClassMethods.multi_line_contents
train
def multi_line_contents(raw_cert) cert_contents = raw_cert.split(/[-](.*)[-]/)[2] cert_contents.lines.map do |line| line.lstrip.squeeze(' ').split(' ') end end
ruby
{ "resource": "" }
q9148
Love.ResourceURI.append_query
train
def append_query(base_uri, added_params = {}) base_params = base_uri.query ? CGI.parse(base_uri.query) : {} get_params = base_params.merge(added_params.stringify_keys) base_uri.dup.tap do |uri| assignments = get_params.map do |k, v| case v when Array; v.map { |val| "#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}" }.join('&') else "#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}" end end uri.query = assignments.join('&') end end
ruby
{ "resource": "" }
q9149
Love.Client.connection
train
def connection @connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http| http.use_ssl = true # http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.start end end
ruby
{ "resource": "" }
q9150
Love.Client.paged_each
train
def paged_each(uri, list_key, options = {}, &block) query_params = {} query_params[:since] = options[:since].to_date.to_s(:db) if options[:since] query_params[:page] = [options[:start_page].to_i, 1].max rescue 1 results = [] initial_result = get(append_query(uri, query_params)) # Determine the amount of pages that is going to be requested. max_page = (initial_result['total'].to_f / initial_result['per_page'].to_f).ceil end_page = options[:end_page].nil? ? max_page : [options[:end_page].to_i, max_page].min # Print out some initial debugging information Love.logger.debug "Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}." if Love.logger # Handle first page of results if initial_result[list_key].kind_of?(Array) block_given? ? initial_result[list_key].each { |record| yield(record) } : results << initial_result[list_key] sleep(sleep_between_requests) if sleep_between_requests end start_page = query_params[:page].to_i + 1 start_page.upto(end_page) do |page| query_params[:page] = page result = get(append_query(uri, query_params)) if result[list_key].kind_of?(Array) block_given? ? result[list_key].each { |record| yield(record) } : results << result[list_key] sleep(sleep_between_requests) if sleep_between_requests end end results.flatten.map {|r| OpenStruct.new(r)} unless block_given? end
ruby
{ "resource": "" }
q9151
QuickDry.QuickDryController.serialize
train
def serialize stuff if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key ) hash = JSON.parse(json) temp = [] if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key hash[get_model.model_name.route_key].each{|x| temp << x[get_model.model_name.route_key]} hash[get_model.model_name.route_key] = temp return hash.to_json end return json elsif stuff.is_a? get_model end end
ruby
{ "resource": "" }
q9152
QuickDry.QuickDryController.get_paged_search_results
train
def get_paged_search_results(params,user:nil,model:nil) params[:per_page] = 10 if params[:per_page].blank? params[:page] = 1 if params[:page].blank? # a ghetto user check, but for some reason a devise user is not a devise user... user = User.new if user.blank? or !user.class.to_s == User.to_s # get the model in question # there has got to be a better way to do this... I just can't find it # model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize if model.blank? model = request.params[:table_name].classify.constantize unless request.params[:table_name].blank? return nil if model.blank? end # initialize un-paged filtered result set result_set = model.none # create where clauses to filter result to just the customers the current user has access to customer_filter = "" user.customers.each do |cust| if model.column_names.include? "cust_id" customer_filter << "(cust_id = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank? elsif model.attribute_alias? "cust_id" customer_filter << "(#{model.attribute_alias "cust_id"} = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank? elsif model.column_names.include? "order_number" customer_filter << "(order_number like '#{cust.prefix}%') OR " unless cust.prefix.blank? elsif model.attribute_alias? "order_number" customer_filter << "(#{model.attribute_alias "order_number"} like '#{cust.prefix}%') OR " unless cust.prefix.blank? end end customer_filter << " (1=0)" # create where clauses for each search parameter if params[:columns].blank? result_set = model.where(customer_filter) else where_clause = "" params[:columns].each do |name, value| where_clause << "(#{model.table_name}.#{name} like '%#{value}%') AND " unless value.blank? end where_clause << " (1=1)" result_set = model.where(customer_filter).where(where_clause) end instances = model.paginate(page: params[:page], per_page: params[:per_page]).merge(result_set).order(updated_at: :desc) return {instances:instances,params:params} end
ruby
{ "resource": "" }
q9153
SimpleCommander.UI.converse
train
def converse(prompt, responses = {}) i, commands = 0, responses.map { |_key, value| value.inspect }.join(',') statement = responses.inject '' do |inner_statement, (key, value)| inner_statement << ( (i += 1) == 1 ? %(if response is "#{value}" then\n) : %(else if response is "#{value}" then\n) ) << %(do shell script "echo '#{key}'"\n) end applescript( %( tell application "SpeechRecognitionServer" set response to listen for {#{commands}} with prompt "#{prompt}" #{statement} end if end tell ), ).strip.to_sym end
ruby
{ "resource": "" }
q9154
RailsIdentity.ApplicationHelper.authorized_for?
train
def authorized_for?(obj) logger.debug("Checking to see if authorized to access object") if @auth_user.nil? # :nocov: return false # :nocov: elsif @auth_user.role >= Roles::ADMIN return true elsif obj.is_a? User return obj == @auth_user else return obj.try(:user) == @auth_user end end
ruby
{ "resource": "" }
q9155
RailsIdentity.ApplicationHelper.get_token_payload
train
def get_token_payload(token) # Attempt to decode without verifying. May raise DecodeError. decoded = JWT.decode token, nil, false payload = decoded[0] # At this point, we know that the token is not expired and # well formatted. Find out if the payload is well defined. if payload.nil? # :nocov: logger.error("Token payload is nil: #{token}") raise UNAUTHORIZED_ERROR, "Invalid token" # :nocov: end return payload rescue JWT::DecodeError => e logger.error("Token decode error: #{e.message}") raise UNAUTHORIZED_ERROR, "Invalid token" end
ruby
{ "resource": "" }
q9156
RailsIdentity.ApplicationHelper.verify_token
train
def verify_token(token) logger.debug("Verifying token: #{token}") # First get the payload of the token. This will also verify whether # or not the token is welformed. payload = get_token_payload(token) # Next, the payload should define user UUID and session UUID. user_uuid = payload["user_uuid"] session_uuid = payload["session_uuid"] if user_uuid.nil? || session_uuid.nil? logger.error("User or session is not specified") raise UNAUTHORIZED_ERROR, "Invalid token" end logger.debug("Token well defined: #{token}") # But, the user UUID and session UUID better be valid too. That is, # they must be real user and session, and the session must belong to # the user. auth_user = User.find_by_uuid(user_uuid) if auth_user.nil? # :nocov: logger.error("Specified user doesn't exist #{user_uuid}") raise UNAUTHORIZED_ERROR, "Invalid token" # :nocov: end auth_session = Session.find_by_uuid(session_uuid) if auth_session.nil? || auth_session.user != auth_user logger.error("Specified session doesn't exist #{session_uuid}") raise UNAUTHORIZED_ERROR, "Invalid token" end # Finally, decode the token using the secret. Also check expiration # here too. JWT.decode token, auth_session.secret, true logger.debug("Token well formatted and verified. Set cache.") # Return the corresponding session return auth_session rescue JWT::DecodeError => e logger.error(e.message) raise UNAUTHORIZED_ERROR, "Invalid token" end
ruby
{ "resource": "" }
q9157
RailsIdentity.ApplicationHelper.get_token
train
def get_token(required_role: Roles::PUBLIC) token = params[:token] # Look up the cache. If present, use it and skip the verification. # Use token itself (and not a session UUID) as part of the key so # it can be considered *verified*. @auth_session = Cache.get(kind: :session, token: token) # Cache miss. So proceed to verify the token and get user and # session data from database. Then set the cache for later. if @auth_session.nil? @auth_session = verify_token(token) @auth_session.role # NOTE: no-op Cache.set({kind: :session, token: token}, @auth_session) end # Obtained session may not have enough permission. Check here. if @auth_session.role < required_role logger.error("Not enough permission (role: #{@auth_session.role})") raise UNAUTHORIZED_ERROR, "Invalid token" end @auth_user = @auth_session.user @token = @auth_session.token return true end
ruby
{ "resource": "" }
q9158
RailsIdentity.ApplicationHelper.get_api_key
train
def get_api_key(required_role: Roles::PUBLIC) api_key = params[:api_key] if api_key.nil? # This case is not likely, but as a safeguard in case migration # has not gone well. # :nocov: raise UNAUTHORIZED_ERROR, "Invalid api key" # :nocov: end auth_user = User.find_by_api_key(api_key) if auth_user.nil? || auth_user.role < required_role raise UNAUTHORIZED_ERROR, "Invalid api key" end @auth_user = auth_user @auth_session = nil @token = nil return true end
ruby
{ "resource": "" }
q9159
RailsIdentity.ApplicationHelper.get_auth
train
def get_auth(required_role: Roles::USER) if params[:token] get_token(required_role: required_role) else get_api_key(required_role: required_role) end end
ruby
{ "resource": "" }
q9160
Disqussion.Reactions.details
train
def details(*args) options = args.last.is_a?(Hash) ? args.pop : {} if args.length == 2 options.merge!(:reaction => args[0]) options.merge!(:forum => args[1]) response = get('reactions/details', options) else puts "#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum" end end
ruby
{ "resource": "" }
q9161
BiolaLogs.ControllerExtensions.append_info_to_payload
train
def append_info_to_payload(payload) super payload[:session_id] = request.session_options[:id] payload[:uuid] = request.uuid payload[:host] = request.host end
ruby
{ "resource": "" }
q9162
GemFootprintAnalyzer.ChildContext.start
train
def start RequireSpy.spy_require(transport) error = try_require(require_string) return transport.done_and_wait_for_ack unless error transport.exit_with_error(error) exit(1) end
ruby
{ "resource": "" }
q9163
Gumdrop.SpecialContentList.find
train
def find(uri) _try_variations_of(uri) do |path| content= get path return [content] unless content.nil? end unless uri.nil? [] end
ruby
{ "resource": "" }
q9164
Bixby.JsonRequest.to_s
train
def to_s(include_params=true) s = [] s << "JsonRequest:#{self.object_id}" s << " operation: #{self.operation}" s << " params: " + MultiJson.dump(self.params) if include_params s.join("\n") end
ruby
{ "resource": "" }
q9165
BalancingAct.Server.valid_params?
train
def valid_params?(name, size) return raise TypeError.new("A 'name' should be a string") if name.class != String return raise TypeError.new("A 'size' should be an integer") if size.class != Integer true end
ruby
{ "resource": "" }
q9166
RsUserPolicy.AuditLog.add_entry
train
def add_entry(email, account, action, changes) @audit_log[email] = [] unless audit_log[email] @audit_log[email] << { :account => account, :action => action, :changes => changes } end
ruby
{ "resource": "" }
q9167
Slackdraft.Base.send!
train
def send! # Send the request request = HTTParty.post(self.target, :body => { :payload => generate_payload.to_json }) unless request.code.eql? 200 false end true end
ruby
{ "resource": "" }
q9168
Templatr.Template.common_fields_attributes=
train
def common_fields_attributes=(nested_attributes) nested_attributes.values.each do |attributes| common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build assign_to_or_mark_for_destruction(common_field, attributes, true, {}) end end
ruby
{ "resource": "" }
q9169
ChromeDebugger.Document.start_time
train
def start_time @start_time ||= @events.select { |event| event.is_a?(RequestWillBeSent) }.select { |event| event.request['url'] == @url }.map { |event| event.timestamp }.first end
ruby
{ "resource": "" }
q9170
ChromeDebugger.Document.encoded_bytes
train
def encoded_bytes(resource_type) @events.select {|e| e.is_a?(ResponseReceived) && e.resource_type == resource_type }.map { |e| e.request_id }.map { |request_id| data_received_for_request(request_id) }.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length } end
ruby
{ "resource": "" }
q9171
ChromeDebugger.Document.bytes
train
def bytes(resource_type) @events.select {|e| e.is_a?(ResponseReceived) && e.resource_type == resource_type }.map { |e| e.request_id }.map { |request_id| data_received_for_request(request_id) }.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length } end
ruby
{ "resource": "" }
q9172
ChromeDebugger.Document.request_count_by_resource
train
def request_count_by_resource(resource_type) @events.select {|n| n.is_a?(ResponseReceived) && n.resource_type == resource_type }.size end
ruby
{ "resource": "" }
q9173
Scholar.Search.to_hash
train
def to_hash hash = {} instance_variables.each do |v| hash[v.to_s[1..-1].to_sym] = instance_variable_get(v) end hash[:results].each do |c| hash[:results][hash[:results].index(c)] = c.to_hash end hash end
ruby
{ "resource": "" }
q9174
SlackBotManager.Commands.on_close
train
def on_close(data, *args) options = args.extract_options! options[:code] ||= (data && data.code) || '1000' disconnect fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s) end
ruby
{ "resource": "" }
q9175
OxMlk.ClassMethods.ox_attr
train
def ox_attr(name,o={},&block) new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block) @ox_attrs << new_attr ox_accessor new_attr.accessor end
ruby
{ "resource": "" }
q9176
OxMlk.ClassMethods.ox_elem
train
def ox_elem(name,o={},&block) new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block) @ox_elems << new_elem ox_accessor new_elem.accessor end
ruby
{ "resource": "" }
q9177
OxMlk.ClassMethods.ox_tag
train
def ox_tag(tag=nil,&block) raise 'you can only set tag or a block, not both.' if tag && block @base_tag ||= self.to_s.split('::').last @ox_tag ||= case tag when String tag when Proc, Symbol, nil @tag_proc = (block || tag || :to_s).to_proc @tag_proc.call(@base_tag) rescue tag.to_s else raise 'you passed something weird' end end
ruby
{ "resource": "" }
q9178
OxMlk.ClassMethods.from_xml
train
def from_xml(data) xml = XML::Node.from(data) raise 'invalid XML' unless xml.name == ox_tag returning new do |ox| (ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))} ox.send(:after_parse) if ox.respond_to?(:after_parse) end end
ruby
{ "resource": "" }
q9179
OxMlk.ClassMethods.to_xml
train
def to_xml(data) ox = XML::Node.new(ox_tag) wrappers = {} ox_elems.each do |elem| if elem.in wrappers[elem.in] ||= XML::Node.new elem.in elem.to_xml(data).each {|e| wrappers[elem.in] << e} else elem.to_xml(data).each {|e| ox << e} end end wrappers.each {|k,v| ox << v} ox_attrs.each do |a| val = data.send(a.accessor).to_s ox[a.tag]= val if val.present? end ox end
ruby
{ "resource": "" }
q9180
Probably.Distribution.pick
train
def pick tst = rand sum = 0 @map.each do |value, prob| sum += prob return value,prob if tst < sum end return nil end
ruby
{ "resource": "" }
q9181
Probably.Distribution.variance
train
def variance expected = self.expectation @map.reduce(0) {|sum, (value,p)| tmp = (value.to_f - expectation) sum + tmp * tmp * p } end
ruby
{ "resource": "" }
q9182
Smoke.Origin.transform
train
def transform(*keys) raise ArgumentError, "requires a block" unless block_given? keys.each do |key| items.each do |item| item[key] = yield(item[key]) || item[key] end end end
ruby
{ "resource": "" }
q9183
Smoke.Origin.method_missing
train
def method_missing(symbol, *args, &block) ivar = "@#{symbol}" if args.empty? return instance_variable_get(ivar) || super else instance_variable_set(ivar, args.pop) end return self end
ruby
{ "resource": "" }
q9184
Smoke.Origin.sort
train
def sort(key) @items = @items.sort_by{|i| i[key] } rescue NoMethodError => e Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set" end
ruby
{ "resource": "" }
q9185
Smoke.Origin.keep
train
def keep(key, matcher) @items.reject! {|i| (i[key] =~ matcher) ? false : true } end
ruby
{ "resource": "" }
q9186
Smoke.Origin.discard
train
def discard(key, matcher) @items.reject! {|i| (i[key] =~ matcher) ? true : false } end
ruby
{ "resource": "" }
q9187
Roy.Context.prepare!
train
def prepare!(env) @env = env @request = Rack::Request.new(env) @response = Rack::Response.new @headers = @response.header @params = @request.GET.merge(@request.POST) @params.default_proc = proc do |hash, key| hash[key.to_s] if Symbol === key end end
ruby
{ "resource": "" }
q9188
Slackdraft.Attachment.generate_attachment
train
def generate_attachment payload = {} payload[:fallback] = self.fallback unless self.fallback.nil? payload[:color] = self.color unless self.color.nil? payload[:pretext] = self.pretext unless self.pretext.nil? payload[:author_name] = self.author_name unless self.author_name.nil? payload[:author_link] = self.author_link unless self.author_link.nil? payload[:author_icon] = self.author_icon unless self.author_icon.nil? payload[:title] = self.title unless self.title.nil? payload[:title_link] = self.title_link unless self.title_link.nil? payload[:text] = self.message unless self.message.nil? unless self.fields.nil? payload[:fields] = self.fields if self.fields.length > 0 end payload[:image_url] = self.image_url unless self.image_url.nil? payload end
ruby
{ "resource": "" }
q9189
DCPU16.Screen.frame
train
def frame return @frame if @frame chars = [] # 4 corners chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) # BottomLeft chars << Char.new(0x23, @x_offset + @width, @y_offset + @height) # BottomRight # horiz @width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset - 1) } @width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset + @height) } # vertical @height.times { |y| chars << Char.new(0x7c, @x_offset - 1, y + @y_offset) } @height.times { |y| chars << Char.new(0x7c, @x_offset + @width, y + @y_offset) } @frame = "" @frame << chars.join end
ruby
{ "resource": "" }
q9190
DCPU16.Screen.update
train
def update(offset, value) return unless (memory_offset..memory_offset_end).include?(offset) @to_s = nil diff = offset - @memory_offset h = diff / @width w = diff % @width @chars[diff] = Char.new(value, w + @x_offset, h + @y_offset) print @chars[diff] changed notify_observers(self) print @chars[diff] end
ruby
{ "resource": "" }
q9191
Bumbleworks.Configuration.add_storage_adapter
train
def add_storage_adapter(adapter) raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless [:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) } @storage_adapters << adapter @storage_adapters end
ruby
{ "resource": "" }
q9192
Bumbleworks.Configuration.storage_adapter
train
def storage_adapter @storage_adapter ||= begin all_adapters = storage_adapters raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty? adapter = all_adapters.detect do |potential_adapter| potential_adapter.use?(storage) end raise UndefinedSetting, "Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}" unless adapter adapter end end
ruby
{ "resource": "" }
q9193
Bumbleworks.Configuration.look_up_configured_path
train
def look_up_configured_path(path_type, options = {}) return @cached_paths[path_type] if @cached_paths.has_key?(path_type) if user_defined_path = user_configured_path(path_type) if path_resolves?(user_defined_path, :file => options[:file]) return user_defined_path else raise Bumbleworks::InvalidSetting, "#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})" end end first_existing_default_path(options[:defaults], :file => options[:file]) end
ruby
{ "resource": "" }
q9194
HashKeywordArgs.Hash.keyword_args
train
def keyword_args(*args) argshash = args[-1].is_a?(Hash) ? args.pop : {} argshash = args.hashify(:optional).merge(argshash) others_OK = argshash.delete(:OTHERS) ret = {} # defaults, required, and checked required = [] check = {} argshash.each do |key, val| # construct fleshed-out attribute hash for all args attrs = case val when Hash val[:default] ||= [] if val[:enumerable] val when :required { :required => true } when :optional {} when :enumerable { :enumerable => true, :default => [] } when Array { :valid => val } when Class, Module { :valid => val } else { :default => val } end # extract required flag, validity checks, and default vlues from attribute hash required << key if attrs[:required] check[key] = case valid = attrs[:valid] when Enumerable [:one_of, valid] when Class, Module [:is_a, valid] else [:ok] end check[key][2] = [:allow_nil, :enumerable].select{|mod| attrs[mod]} ret[key] = attrs[:default] if attrs.include?(:default) end # check validity of keys unless others_OK or (others = self.keys - argshash.keys).empty? raise ArgumentError, "Invalid keyword arg#{others.length>1 && "s" or ""} #{others.collect{|a| a.inspect}.join(', ')}", caller end # process values, checking validity self.each do |key, val| code, valid, mods = check[key] mods ||= [] val = [ val ] unless mods.include?(:enumerable) and val.is_a?(Enumerable) ok = val.all? { |v| if mods.include?(:allow_nil) and v.nil? true else case code when nil then true # for OTHERS args, there's no code when :ok then true when :one_of then valid.include?(v) when :is_a then v.is_a?(valid) end end } val = val.first unless mods.include?(:enumerable) raise ArgumentError, "Invalid value for keyword arg #{key.inspect} => #{val.inspect}", caller unless ok ret[key] = val required.delete(key) end unless required.empty? raise ArgumentError, "Missing required keyword arg#{required.length>1 && "s" or ""} #{required.collect{|a| a.inspect}.join(', ')}", caller end (class << ret ; self ; end).class_eval do argshash.keys.each do |key| define_method(key) do self[key] end end end ret end
ruby
{ "resource": "" }
q9195
ActionPager.Pager.near_pages
train
def near_pages @near_pages ||= begin if current_page <= near + 1 upper_page = shown_page_count >= last_page ? last_page : shown_page_count 1..upper_page elsif current_page >= last_page - near - 1 bottom_page = last_page - shown_page_count + 1 (bottom_page > 1 ? bottom_page : 1)..last_page else bottom_page = current_page - near upper_page = current_page + near (bottom_page > 1 ? bottom_page : 1)..(upper_page < last_page ? upper_page : last_page) end end end
ruby
{ "resource": "" }
q9196
WallLeecher.Leecher.prep_file
train
def prep_file(url, dir) parts = url.split('/') File.join(dir, parts[-1]) end
ruby
{ "resource": "" }
q9197
WallLeecher.Fetcher.get
train
def get schedule do inc_io @@log.info("Requesting: #{@url}") http = EM::HttpRequest.new(@url).get :redirects => 5 http.callback do |h| succeed http.response dec_io end http.headers do |headers| unless OK_ERROR_CODES.include?(headers.status) fail("Error (#{headers.status}) with url:#{@url}") dec_io end end http.errback do fail("Error downloading #{@url}") dec_io end end self # Fluent interface end
ruby
{ "resource": "" }
q9198
Npolar::Api::Client.JsonApiClient.valid
train
def valid(condition=true) all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)} end
ruby
{ "resource": "" }
q9199
Npolar::Api::Client.JsonApiClient.multi_request
train
def multi_request(method, paths, body=nil, param=nil, header=nil) @multi = true # Response storage, if not already set if @responses.nil? @responses = [] end # Handle one or many paths if paths.is_a? String or paths.is_a? URI paths = [paths] end # Handle (URI) objects paths = paths.map {|p| p.to_s } log.debug "Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }" paths.each do | path | multi_request = request(path, method.downcase.to_sym, body, param, header) multi_request.on_complete do | response | log.debug "Multi-#{method} [#{paths.size}]: "+log_message(response) @responses << response end hydra.queue(multi_request) end hydra end
ruby
{ "resource": "" }