_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q7600
Rack::AcceptHeaders.MediaType.params_match?
train
def params_match?(params, match) return true if params == match parsed = parse_range_params(params) parsed == parsed.merge(parse_range_params(match)) end
ruby
{ "resource": "" }
q7601
Moby.PartsOfSpeech.words
train
def words(pos_name) pos.select {|w, c| c.include?(pos_code_map.key(pos_name)) }.keys end
ruby
{ "resource": "" }
q7602
Rattler::Runtime.PackratParser.apply
train
def apply(match_method_name) start_pos = @scanner.pos if m = memo(match_method_name, start_pos) recall m, match_method_name else m = inject_fail match_method_name, start_pos save m, eval_rule(match_method_name) end end
ruby
{ "resource": "" }
q7603
JBLAS.MatrixClassMixin.from_array
train
def from_array(data) n = data.length if data.reject{|l| Numeric === l}.size == 0 a = self.new(n, 1) (0...data.length).each do |i| a[i, 0] = data[i] end return a else begin lengths = data.collect{|v| v.length} rescue raise "All columns must be arrays" end raise "All columns must have equal length!" if lengths.min < lengths.max a = self.new(n, lengths.max) for i in 0...n for j in 0...lengths.max a[i,j] = data[i][j] end end return a end end
ruby
{ "resource": "" }
q7604
Main.TermASTGenerator.each
train
def each(io) if block_given? filter = BELParser::ASTFilter.new( BELParser::ASTGenerator.new(io), *TYPES) filter.each do |results| yield results end else enum_for(:each, io) end end
ruby
{ "resource": "" }
q7605
Bisques.AwsConnection.request
train
def request(method, path, query = {}, body = nil, headers = {}) AwsRequest.new(aws_http_connection).tap do |aws_request| aws_request.credentials = credentials aws_request.path = path aws_request.region = region aws_request.service = service aws_request.method = method aws_request.query = query aws_request.body = body aws_request.headers = headers aws_request.make_request end end
ruby
{ "resource": "" }
q7606
Bisques.AwsConnection.action
train
def action(action_name, path = "/", options = {}) retries = 0 begin # If options given in place of path assume / options, path = path, "/" if path.is_a?(Hash) && options.empty? request(:post, path, {}, options.merge("Action" => action_name)).response.tap do |response| unless response.success? element = response.doc.xpath("//Error") raise AwsActionError.new(element.xpath("Type").text, element.xpath("Code").text, element.xpath("Message").text, response.http_response.status) end end rescue AwsActionError => e if retries < 2 && (500..599).include?(e.status.to_i) retries += 1 retry else raise e end end end
ruby
{ "resource": "" }
q7607
Authorizable.Controller.is_authorized_for_action?
train
def is_authorized_for_action? action = params[:action].to_sym self.class.authorizable_config ||= DefaultConfig.config if !self.class.authorizable_config[action] action = Authorizable::Controller.alias_action(action) end # retrieve the settings for this particular controller action settings_for_action = self.class.authorizable_config[action] # continue with evaluation result = is_authorized_for_action_with_config?(action, settings_for_action) # if we are configured to raise exception instead of handle the error # ourselves, raise the exception! if Authorizable.configuration.raise_exception_on_denial? and !result raise Authorizable::Error::NotAuthorized.new( action: action, subject: params[:controller] ) end result end
ruby
{ "resource": "" }
q7608
Authorizable.Controller.is_authorized_for_action_with_config?
train
def is_authorized_for_action_with_config?(action, config) request_may_proceed = false return true unless config.present? defaults = { user: current_user, permission: action.to_s, message: I18n.t('authorizable.not_authorized'), flash_type: Authorizable.configuration.flash_error } options = defaults.merge(config) # run permission request_may_proceed = evaluate_action_permission(options) # redirect unless request_may_proceed and request.format == :html authorizable_respond_with( options[:flash_type], options[:message], options[:redirect_path] ) # halt return false end # proceed with request execution true end
ruby
{ "resource": "" }
q7609
Authorizable.Controller.evaluate_action_permission
train
def evaluate_action_permission(options) # the target is the @resource # (@event, @user, @page, whatever) # it must exist in order to perform a permission check # involving the object if options[:target] object = instance_variable_get("@#{options[:target]}") return options[:user].can?(options[:permission], object) else return options[:user].can?(options[:permission]) end end
ruby
{ "resource": "" }
q7610
Takenoko.AttachHelper.get_drive_files_list
train
def get_drive_files_list(folder) ls = Hash.new page_token = nil begin (files, page_token) = folder.files("pageToken" => page_token) files.each do |f| ls[f.original_filename] = f end end while page_token return ls end
ruby
{ "resource": "" }
q7611
HipsterSqlToHbase.ResultTreeToHbaseConverter.insert_sentence
train
def insert_sentence(hash) thrift_method = "mutateRow" thrift_table = hash[:into] thrift_calls = [] hash[:values].each do |value_set| thrift_row = SecureRandom.uuid thrift_mutations = [] i = 0 hash[:columns].each do |col| thrift_mutations << HBase::Mutation.new(column: col, value: value_set[i].to_s) i += 1 end thrift_calls << {:method => thrift_method,:arguments => [thrift_table,thrift_row,thrift_mutations,{}]} end HipsterSqlToHbase::ThriftCallGroup.new(thrift_calls,true) end
ruby
{ "resource": "" }
q7612
HipsterSqlToHbase.ResultTreeToHbaseConverter.select_sentence
train
def select_sentence(hash) thrift_method = "getRowsByScanner" thrift_table = hash[:from] thrift_columns = hash[:select] thrift_filters = recurse_where(hash[:where] || []) thrift_limit = hash[:limit] HipsterSqlToHbase::ThriftCallGroup.new([{:method => thrift_method,:arguments => [thrift_table,thrift_columns,thrift_filters,thrift_limit,{}]}]) end
ruby
{ "resource": "" }
q7613
HipsterSqlToHbase.ResultTreeToHbaseConverter.filters_from_key_value_pair
train
def filters_from_key_value_pair(kvp) kvp[:qualifier] = kvp[:column].split(':') kvp[:column] = kvp[:qualifier].shift if (kvp[:condition].to_s != "LIKE") "(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',#{kvp[:condition]},'binary:#{kvp[:value]}',true,true))" else kvp[:value] = Regexp.escape(kvp[:value]) kvp[:value].sub!(/^%/,"^.*") kvp[:value].sub!(/%$/,".*$") while kvp[:value].match(/([^\\]{1,1})%/) kvp[:value].sub!(/([^\\]{1,1})%/,"#{$1}.*?") end kvp[:value].sub!(/^_/,"^.") kvp[:value].sub!(/_$/,".$") while kvp[:value].match(/([^\\]{1,1})_/) kvp[:value].sub!(/([^\\]{1,1})_/,"#{$1}.") end "(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',=,'regexstring:#{kvp[:value]}',true,true))" end end
ruby
{ "resource": "" }
q7614
Tmsync.FileSearch.find_all_grouped_by_language
train
def find_all_grouped_by_language all_files = Dir.glob(File.join(@base_path, '**/*')) # apply exclude regex found_files = all_files.select { |file_path| file_path !~ @exclude_regex && !File.directory?(file_path) } # exclude empty files found_files = found_files.select { |file_path| content = File.open(file_path, 'r') { |f| f.read } !content.to_s.scrub("<?>").strip.empty? } # apply matching regex found_files = found_files.select { |file_path| file_path =~ @matching_regex }.map { |file_path| [file_path.match(@matching_regex).captures.last, file_path] } result = found_files.group_by(&:first).map { |k,v| [k, v.each(&:shift).flatten] }.to_h # replace nil key with fallback language if !(nil_values = result[nil]).nil? result[Tmsync::Constants::FALLBACK_LANGUAGE] = nil_values result.delete(nil) end result end
ruby
{ "resource": "" }
q7615
DomainTools.Request.build_url
train
def build_url parts = [] uri = "" parts << "/#{@version}" if @version parts << "/#{@domain}" if @domain parts << "/#{@service}" if @service uri = parts.join("") parts << "?" parts << "format=#{@format}" parts << "&#{authentication_params(uri)}" parts << "#{format_parameters}" if @parameters @url = parts.join("") end
ruby
{ "resource": "" }
q7616
DomainTools.Request.execute
train
def execute(refresh=false) return @response if @response && !refresh validate build_url @done = true DomainTools.counter! require 'net/http' begin Net::HTTP.start(@host) do |http| req = Net::HTTP::Get.new(@url) @http = http.request(req) @success = validate_http_status return finalize end rescue DomainTools::ServiceException => e @error = DomainTools::Error.new(self,e) raise e.class.new(e) end end
ruby
{ "resource": "" }
q7617
Zaif.API.trade
train
def trade(currency_code, price, amount, action, limit = nil, counter_currency_code = "jpy") currency_pair = currency_code + "_" + counter_currency_code params = {:currency_pair => currency_pair, :action => action, :price => price, :amount => amount} params.store(:limit, limit) if limit json = post_ssl(@zaif_trade_url, "trade", params) return json end
ruby
{ "resource": "" }
q7618
Zaif.API.bid
train
def bid(currency_code, price, amount, limit = nil, counter_currency_code = "jpy") return trade(currency_code, price, amount, "bid", limit, counter_currency_code) end
ruby
{ "resource": "" }
q7619
Zaif.API.ask
train
def ask(currency_code, price, amount, limit = nil, counter_currency_code = "jpy") return trade(currency_code, price, amount, "ask", limit, counter_currency_code) end
ruby
{ "resource": "" }
q7620
Zaif.API.withdraw
train
def withdraw(currency_code, address, amount, option = {}) option["currency"] = currency_code option["address"] = address option["amount"] = amount json = post_ssl(@zaif_trade_url, "withdraw", option) return json end
ruby
{ "resource": "" }
q7621
Adminable.FieldCollector.associations
train
def associations @associations ||= [].tap do |fields| @model.reflect_on_all_associations.each do |association| fields << resolve(association.macro, association.name) end end end
ruby
{ "resource": "" }
q7622
CConfig.HashUtils.strict_merge_with_env
train
def strict_merge_with_env(default:, local:, prefix:) hsh = {} default.each do |k, v| # The corresponding environment variable. If it's not the final value, # then this just contains the partial prefix of the env. variable. env = "#{prefix}_#{k}" # If the current value is a hash, then go deeper to perform a deep # merge, otherwise we merge the final value by respecting the order as # specified in the documentation. if v.is_a?(Hash) l = local[k] || {} hsh[k] = strict_merge_with_env(default: default[k], local: l, prefix: env) else hsh[k] = first_non_nil(get_env(env), local[k], v) end end hsh end
ruby
{ "resource": "" }
q7623
CConfig.HashUtils.get_env
train
def get_env(key) env = ENV[key.upcase] return nil if env.nil? # Try to convert it into a boolean value. return true if env.casecmp("true").zero? return false if env.casecmp("false").zero? # Try to convert it into an integer. Otherwise just keep the string. begin Integer(env) rescue ArgumentError env end end
ruby
{ "resource": "" }
q7624
Taxonomite.Node.evaluate
train
def evaluate(m) return self.owner.instance_eval(m) if self.owner != nil && self.owner.respond_to?(m) return self.instance_eval(m) if self.respond_to?(m) nil end
ruby
{ "resource": "" }
q7625
Taxonomite.Node.validate_parent
train
def validate_parent(parent) raise InvalidParent.create(parent, self) unless (!parent.nil? && is_valid_parent?(parent)) parent.validate_child(self) end
ruby
{ "resource": "" }
q7626
LateralRecommender.API.match_documents
train
def match_documents(mind_results, database_results, key = 'id') return [] unless database_results mind_results.each_with_object([]) do |result, arr| next unless (doc = database_results.find { |s| s[key].to_s == result['document_id'].to_s }) arr << doc.attributes.merge(result) end end
ruby
{ "resource": "" }
q7627
Auth.Helpers.generate_secret
train
def generate_secret if defined?(SecureRandom) SecureRandom.urlsafe_base64(32) else Base64.encode64( Digest::SHA256.digest("#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}") ).gsub('/','-').gsub('+','_').gsub('=','').strip end end
ruby
{ "resource": "" }
q7628
Auth.Helpers.encrypt_password
train
def encrypt_password(password, salt, hash) case hash.to_s when 'sha256' Digest::SHA256.hexdigest("#{password}-#{salt}") else raise 'Unsupported hash algorithm' end end
ruby
{ "resource": "" }
q7629
Auth.Helpers.decode_scopes
train
def decode_scopes(scopes) if scopes.is_a?(Array) scopes.map {|s| s.to_s.strip } else scopes.to_s.split(' ').map {|s| s.strip } end end
ruby
{ "resource": "" }
q7630
TwitterADS.RestResource.check_method
train
def check_method(tab_ops, prefix, method_sym, do_call, *arguments, &block) method_sym = method_sym.id2name verb = :get [:post, :get, :delete, :put].each do |averb| if method_sym.start_with? averb.id2name verb = averb method_sym[averb.id2name + '_'] = '' break end end if tab_ops[verb].include? method_sym.to_sym if do_call params = arguments.first method = prefix + method_sym method += "/#{params.shift}" if params.first && params.first.class != Hash return do_request verb, method, params.shift else return nil end end nil end
ruby
{ "resource": "" }
q7631
RabbitHutch.Consumer.handle_message
train
def handle_message(metadata, payload) # loop through appenders and fire each as required @consumers.each do |consumer| action = metadata.routing_key.split('.', 2).first if(action == "publish") exchange = metadata.attributes[:headers]["exchange_name"] queue = metadata.routing_key.split('.', 2).last item = {:date => Time.now, :exchange => exchange, :queue => queue, :routing_keys => metadata.attributes[:headers]["routing_keys"].inspect, :attributes => metadata.attributes.inspect, :payload => payload.inspect } consumer.log_event(item) end end end
ruby
{ "resource": "" }
q7632
Gxapi.GoogleAnalytics.get_experiments
train
def get_experiments @experiments ||= begin # fetch our data from the cache data = Gxapi.with_error_handling do # handle caching self.list_experiments_from_cache end # turn into Gxapi::Ostructs (data || []).collect{|data| Ostruct.new(data)} end end
ruby
{ "resource": "" }
q7633
Gxapi.GoogleAnalytics.get_variant
train
def get_variant(identifier) # pull in an experiment experiment = self.get_experiment(identifier) if self.run_experiment?(experiment) # select variant for the experiment variant = self.select_variant(experiment) # return if it it's present return variant if variant.present? end # return blank value if we don't have an experiment or don't get # a valid value return Ostruct.new( name: "default", index: -1, experiment_id: nil ) end
ruby
{ "resource": "" }
q7634
Gxapi.GoogleAnalytics.list_experiments
train
def list_experiments response = self.client.execute({ api_method: self.analytics_experiments.list, parameters: { accountId: self.config.account_id.to_s, profileId: self.config.profile_id.to_s, webPropertyId: self.config.web_property_id } }) response.data.items.collect(&:to_hash) end
ruby
{ "resource": "" }
q7635
Gxapi.GoogleAnalytics.client
train
def client @client ||= begin client = Google::APIClient.new client.authorization = Signet::OAuth2::Client.new( token_credential_uri: 'https://accounts.google.com/o/oauth2/token', audience: 'https://accounts.google.com/o/oauth2/token', scope: 'https://www.googleapis.com/auth/analytics.readonly', issuer: Gxapi.config.google.email, signing_key: self.get_key ) client.authorization.fetch_access_token! client end end
ruby
{ "resource": "" }
q7636
Gxapi.GoogleAnalytics.select_variant
train
def select_variant(experiment) # starts off at 0 accum = 0.0 sample = Kernel.rand # go through our experiments and return the variation that matches # our random value experiment.variations.each_with_index do |variation, i| # we want to record the index in the array for this variation variation.index = i variation.experiment_id = experiment.id # add the variation's weight to accum accum += variation.weight # return the variation if accum is more than our random value if sample <= accum return variation end end # default to nil return nil end
ruby
{ "resource": "" }
q7637
CommandTree.Tree.merge
train
def merge(subtree, prefix, name, options = {}) register(prefix, name, options) subtree.calls.each do |key, command| next unless command calls["#{prefix}#{key}"] = command end end
ruby
{ "resource": "" }
q7638
Pullr.LocalRepository.scm_dir
train
def scm_dir dir, scm = SCM::DIRS.find { |dir,scm| scm == @scm } return dir end
ruby
{ "resource": "" }
q7639
Transprt.Client.locations
train
def locations(parameters) allowed_parameters = %w(query x y type) query = create_query(parameters, allowed_parameters) locations = perform('locations', query) locations['stations'] end
ruby
{ "resource": "" }
q7640
Transprt.Client.connections
train
def connections(parameters) allowed_parameters = %w(from to via date time isArrivalTime transportations limit page direct sleeper couchette bike) query = create_query(parameters, allowed_parameters) locations = perform('connections', query) locations['connections'] end
ruby
{ "resource": "" }
q7641
Transprt.Client.stationboard
train
def stationboard(parameters) allowed_parameters = %w(station id limit transportations datetime) query = create_query(parameters, allowed_parameters) locations = perform('stationboard', query) locations['stationboard'] end
ruby
{ "resource": "" }
q7642
SimpleActivity.Activity.method_missing
train
def method_missing(method_name, *arguments, &block) if method_name.to_s =~ /(actor|target)_(?!type|id).*/ self.cache.try(:[], method_name.to_s) else super end end
ruby
{ "resource": "" }
q7643
ProfitBricks.Loadbalancer.update
train
def update(options = {}) response = ProfitBricks.request( method: :patch, path: "/datacenters/#{datacenterId}/loadbalancers/#{id}", expects: 202, body: options.to_json ) if response self.requestId = response['requestId'] @properties = @properties.merge(response['properties']) end self end
ruby
{ "resource": "" }
q7644
NitroApi.NitroApi.sign
train
def sign(time) unencrypted_signature = @api_key + @secret + time + @user.to_s to_digest = unencrypted_signature + unencrypted_signature.length.to_s return Digest::MD5.hexdigest(to_digest) end
ruby
{ "resource": "" }
q7645
BorrowDirect.GenerateQuery.normalized_author
train
def normalized_author(author) return "" if author.nil? || author.empty? author = author.downcase # Just take everything before the comma/semicolon if we have one -- # or before an "and", for stripping individuals out of 245c # multiples. if author =~ /\A([^,;]*)(,|\sand\s|;)/ author = $1 end author.gsub!(/\A.*by\s*/, '') # We want to remove some punctuation that is better # turned into a space in the query. Along with # any kind of unicode space, why not. author.gsub!(PUNCT_STRIP_REGEX, ' ') # compress any remaining whitespace author.strip! author.gsub!(/\s+/, ' ') return author end
ruby
{ "resource": "" }
q7646
DuckMap.ActionViewHelpers.sitemap_meta_keywords
train
def sitemap_meta_keywords return controller.sitemap_meta_data[:keywords].blank? ? nil : tag(:meta, {name: :keywords, content: controller.sitemap_meta_data[:keywords]}, false, false) end
ruby
{ "resource": "" }
q7647
DuckMap.ActionViewHelpers.sitemap_meta_description
train
def sitemap_meta_description return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false) end
ruby
{ "resource": "" }
q7648
DuckMap.ActionViewHelpers.sitemap_meta_lastmod
train
def sitemap_meta_lastmod return controller.sitemap_meta_data[:lastmod].blank? ? nil : tag(:meta, {name: "Last-Modified", content: controller.sitemap_meta_data[:lastmod]}, false, false) end
ruby
{ "resource": "" }
q7649
DuckMap.ActionViewHelpers.sitemap_meta_canonical
train
def sitemap_meta_canonical return controller.sitemap_meta_data[:canonical].blank? ? nil : tag(:link, {rel: :canonical, href: controller.sitemap_meta_data[:canonical]}, false, false) end
ruby
{ "resource": "" }
q7650
Sjekksum.Primitive97.valid?
train
def valid? number raise_on_type_mismatch number num, check = split_number(number) self.of(num) == check end
ruby
{ "resource": "" }
q7651
Rack::AcceptHeaders.Context.check!
train
def check!(request) @check_headers.each do |header_name| values = @checks[header_name] header = request.send(header_name) raise AcceptError unless values.any? {|v| header.accept?(v) } end end
ruby
{ "resource": "" }
q7652
Sjekksum.Verhoeff.of
train
def of number raise_on_type_mismatch number digits = convert_number_to_digits(number) INVERSE[digits.reverse_each.with_index.reduce(0) { |check, (digit, idx)| d_row = DIHEDRAL_GROUP_D5[check] d_row[ PERMUTATION[idx.next % 8][digit] ] }] end
ruby
{ "resource": "" }
q7653
LXC.Configuration.save_to_file
train
def save_to_file(path) fullpath = File.expand_path(path) lines = [] @content.each_pair do |key,value| k = "lxc.#{key.gsub('_', '.')}" if value.kind_of?(Array) lines << value.map { |v| "#{k} = #{v}" } else lines << "#{k} = #{value}" end end File.open(path, "w") do |f| f.write(lines.flatten.join("\n")) end end
ruby
{ "resource": "" }
q7654
Typhoid.RequestBuilder.symbolize_keys
train
def symbolize_keys(hash) hash = hash.to_hash if hash.respond_to?(:symbolize_keys) hash.symbolize_keys else hash.inject({}) do |new_hash, (key, value)| new_hash[symbolize_key(key)] = value new_hash end end end
ruby
{ "resource": "" }
q7655
Transprt.RateLimiting.get
train
def get(url) begin response = perform_get(url) rescue RestClient::TooManyRequests => e # API uses HTTP 429 to notify us, # @see https://github.com/OpendataCH/Transport/blob/master/lib/Transport/Application.php return nil unless wait_for_quota sleep_until_quota_reset(e.response) response = perform_get(url) end response end
ruby
{ "resource": "" }
q7656
Rack::AcceptHeaders.Language.matches
train
def matches(language) values.select {|v| v = v.match(/^(.+?)-/) ? $1 : v if @first_level_match v == language || v == '*' || (language.match(/^(.+?)-/) && v == $1) }.sort {|a, b| # "*" gets least precedence, any others are compared based on length. a == '*' ? -1 : (b == '*' ? 1 : a.length <=> b.length) }.reverse end
ruby
{ "resource": "" }
q7657
RubyPandoc.Converter.convert
train
def convert(*args) @options += args if args outputfile = @options.map{ |x| x[:output] }.compact tmp_file = Tempfile.new('pandoc-conversion') @options += [{ output: tmp_file.path }] if outputfile.empty? @option_string = prepare_options(@options) begin run_pandoc IO.binread(tmp_file) ensure tmp_file.close tmp_file.unlink end end
ruby
{ "resource": "" }
q7658
RubyPandoc.Converter.run_pandoc
train
def run_pandoc command = unless @input_files.nil? || @input_files.empty? "#{@@pandoc_path} #{@input_files} #{@option_string}" else "#{@@pandoc_path} #{@option_string}" end output = error = exit_status = nil options = {} options[:stdin_data] = @input_string if @input_string output, error, exit_status = Open3.capture3(command, **options) raise error unless exit_status && exit_status.success? output end
ruby
{ "resource": "" }
q7659
RubyPandoc.Converter.prepare_options
train
def prepare_options(opts = []) opts.inject('') do |string, (option, value)| string += case when value create_option(option, value) when option.respond_to?(:each_pair) prepare_options(option) else create_option(option) end end end
ruby
{ "resource": "" }
q7660
RubyPandoc.Converter.create_option
train
def create_option(flag, argument = nil) return '' unless flag flag = flag.to_s return " #{argument}" if flag == 'extra' set_pandoc_ruby_options(flag, argument) if !argument.nil? "#{format_flag(flag)} #{argument}" else format_flag(flag) end end
ruby
{ "resource": "" }
q7661
RubyPandoc.Converter.set_pandoc_ruby_options
train
def set_pandoc_ruby_options(flag, argument = nil) case flag when 't', 'to' @writer = argument.to_s @binary_output = true if BINARY_WRITERS.keys.include?(@writer) end end
ruby
{ "resource": "" }
q7662
Rattler::Parsers.AttributedSequence.parse
train
def parse(scanner, rules, scope = ParserScope.empty) result = false backtracking(scanner) do if scope = parse_children(scanner, rules, scope.nest) {|r| result = r } yield scope if block_given? result end end end
ruby
{ "resource": "" }
q7663
RubyHoldem.Deck.burn
train
def burn(burn_cards) return false if burn_cards.is_a?(Integer) if burn_cards.is_a?(Card) || burn_cards.is_a?(String) burn_cards = [burn_cards] end burn_cards.map! do |c| c = Card.new(c) unless c.class == Card @cards.delete(c) end true end
ruby
{ "resource": "" }
q7664
Routing.ItsfBackendResourceConcern.backend_resources
train
def backend_resources(*args, &block) resources(*args, &block) # additional_member_actions = (Itsf::Backend::Configuration.default_resource_pages - [:show]) # if additional_member_actions.any? # resources_name = args.first # resources resources_name, only: [] do # member do # additional_member_actions.each do |action| # get action # end # end # end # end additional_resource_route_blocks = Itsf::Backend::Configuration.additional_resource_route_blocks if additional_resource_route_blocks.any? resources_name = args.first additional_resource_route_blocks.each do |route_block| resources resources_name, only: [] do route_block.call(self) end end end end
ruby
{ "resource": "" }
q7665
Apidocs.ApiDocs.generate_html
train
def generate_html FileUtils.rm_rf(Rails.root.join('tmp/apidocs')) options = [Rails.root.join("app/controllers").to_s, "--op=#{Rails.root.join('tmp/apidocs')}"] self.store = RDoc::Store.new @options = load_options @options.parse options @exclude = @options.exclude @last_modified = setup_output_dir @options.op_dir, @options.force_update @store.encoding = @options.encoding if @options.respond_to? :encoding @store.dry_run = @options.dry_run @store.main = @options.main_page @store.title = @options.title @store.path = @options.op_dir @start_time = Time.now @store.load_cache @options.default_title = "RDoc Documentation" parse_files @options.files @store.complete @options.visibility formatter = RDoc::Markup::ToHtml.new(RDoc::Options.new) routes = routes_by_regex.map do |r| {verb: r[:verb], path: r[:path].sub('(.:format)', ''), class_name: gen_class_name(r), action_name: gen_action_name(r) } end.each do |r| doc = document_route(r) r[:html_comment] = doc ? doc.accept(formatter) : "" end.select { |r| r[:class_name] != "ApidocsController" } puts routes.inspect routes end
ruby
{ "resource": "" }
q7666
Cxxproject.HasSources.collect_sources_and_toolchains
train
def collect_sources_and_toolchains sources_to_build = {} exclude_files = Set.new exclude_sources.each do |p| if p.include?("..") Printer.printError "Error: Exclude source file pattern '#{p}' must not include '..'" return nil end Dir.glob(p).each {|f| exclude_files << f} end files = Set.new # do not build the same file twice add_to_sources_to_build(sources_to_build, exclude_files, sources) source_patterns.each do |p| if p.include?("..") Printer.printError "Error: Source file pattern '#{p}' must not include '..'" return nil end globRes = Dir.glob(p) if (globRes.length == 0) Printer.printWarning "Warning: Source file pattern '#{p}' did not match to any file" end add_to_sources_to_build(sources_to_build, exclude_files, globRes, tcs4source(p)) end return sources_to_build end
ruby
{ "resource": "" }
q7667
Cxxproject.HasSources.calc_dirs_with_files
train
def calc_dirs_with_files(sources) filemap = {} sources.keys.sort.reverse.each do |o| d = File.dirname(o) if filemap.include?(d) filemap[d] << o else filemap[d] = [o] end end return filemap end
ruby
{ "resource": "" }
q7668
RProgram.Argument.arguments
train
def arguments(value) value = case value when Hash value.map do |key,sub_value| if sub_value == true then key.to_s elsif sub_value then "#{key}=#{sub_value}" end end when false, nil [] else Array(value) end return value.compact end
ruby
{ "resource": "" }
q7669
Halibut::Core.RelationMap.add
train
def add(relation, item) unless item.respond_to?(:to_hash) raise ArgumentError.new('only items that can be converted to hashes with #to_hash are permitted') end @relations[relation] = @relations.fetch(relation, []) << item end
ruby
{ "resource": "" }
q7670
Halibut::Core.RelationMap.to_hash
train
def to_hash @relations.each_with_object({}) do |(rel,val), obj| rel = rel.to_s hashed_val = val.map(&:to_hash) if val.length == 1 && !single_item_arrays? hashed_val = val.first.to_hash end obj[rel] = hashed_val end end
ruby
{ "resource": "" }
q7671
Dirigible.Request.request
train
def request(method, path, options, headers) headers.merge!({ 'User-Agent' => user_agent, 'Accept' => 'application/vnd.urbanairship+json; version=3;', }) response = connection.send(method) do |request| request.url("#{endpoint}#{path}/") if [:post, :put].member?(method) request.body = options.to_json else request.params.merge!(options) end request.headers.merge!(headers) end Utils.handle_api_error(response) unless (200..399).include?(response.status) Utils.parse_message(response) end
ruby
{ "resource": "" }
q7672
Mongoid.Follower.follow
train
def follow(model) if self.id != model.id && !self.follows?(model) model.before_followed_by(self) if model.respond_to?('before_followed_by') model.followers.create!(:ff_type => self.class.name, :ff_id => self.id) model.inc(:fferc, 1) model.after_followed_by(self) if model.respond_to?('after_followed_by') self.before_follow(model) if self.respond_to?('before_follow') self.followees.create!(:ff_type => model.class.name, :ff_id => model.id) self.inc(:ffeec, 1) self.after_follow(model) if self.respond_to?('after_follow') else return false end end
ruby
{ "resource": "" }
q7673
Mongoid.Follower.unfollow
train
def unfollow(model) if self.id != model.id && self.follows?(model) model.before_unfollowed_by(self) if model.respond_to?('before_unfollowed_by') model.followers.where(:ff_type => self.class.name, :ff_id => self.id).destroy model.inc(:fferc, -1) model.after_unfollowed_by(self) if model.respond_to?('after_unfollowed_by') self.before_unfollow(model) if self.respond_to?('before_unfollow') self.followees.where(:ff_type => model.class.name, :ff_id => model.id).destroy self.inc(:ffeec, -1) self.after_unfollow(model) if self.respond_to?('after_unfollow') else return false end end
ruby
{ "resource": "" }
q7674
TemplateParams.Assertion.assert_type
train
def assert_type(value) unless @type.nil? || value.is_a?(@type) || allow_nil && value.nil? raise TypeError, format("Expected %s, got %s", @type, value.class) end end
ruby
{ "resource": "" }
q7675
Logan.TodoList.todo_with_substring
train
def todo_with_substring(substring) issue_todo = @remaining_todos.detect{ |t| !t.content.index(substring).nil? } issue_todo ||= @completed_todos.detect { |t| !t.content.index(substring).nil? } end
ruby
{ "resource": "" }
q7676
Logan.TodoList.create_todo
train
def create_todo(todo) post_params = { :body => todo.post_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/projects/#{@project_id}/todolists/#{@id}/todos.json", post_params Logan::Todo.new response end
ruby
{ "resource": "" }
q7677
Logan.TodoList.update_todo
train
def update_todo(todo) put_params = { :body => todo.put_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.put "/projects/#{@project_id}/todos/#{todo.id}.json", put_params Logan::Todo.new response end
ruby
{ "resource": "" }
q7678
SafetyCone.Filter.safety_cone_filter
train
def safety_cone_filter if cone = fetch_cone if cone.type == 'notice' flash.now["safetycone_#{notice_type(cone.type)}"] = cone.message else flash["safetycone_#{notice_type(cone.type)}"] = cone.message end redirect_to safety_redirect if cone.type == 'block' end end
ruby
{ "resource": "" }
q7679
SafetyCone.Filter.fetch_cone
train
def fetch_cone paths = SafetyCone.paths if path = paths[request_action] key = request_action elsif cone = paths[request_method] key = request_method else return false end path = Path.new(key, path) path.fetch %w[notice block].include?(path.type) ? path : false end
ruby
{ "resource": "" }
q7680
Stars.Client.star_loop
train
def star_loop selection = '' while true puts "Type the number of the post that you want to learn about" print " (or hit return to view all again, you ego-maniac) >> " selection = $stdin.gets.chomp break if ['','q','quit','exit','fuckthis'].include?(selection.downcase) show(selection) end display if selection == '' end
ruby
{ "resource": "" }
q7681
Stars.Client.show
train
def show(id) post = @posts[id.to_i-1] return puts("\nMake a valid selection. Pretty please?\n") unless post puts post.more display end
ruby
{ "resource": "" }
q7682
Stars.Client.print_posts
train
def print_posts(posts) table do |t| t.headings = headings posts.each_with_index do |post,i| t << [ { :value => i+1, :alignment => :right }, post.service.capitalize, { :value => post.stars_count, :alignment => :center }, post.short_name ] end end end
ruby
{ "resource": "" }
q7683
Gatherer.CardParser.loyalty
train
def loyalty(parsed_text = extract_power_toughness) if parsed_text && !parsed_text.include?('/') parsed_text.to_i if parsed_text.to_i > 0 end end
ruby
{ "resource": "" }
q7684
Aptly.Repository.add_file
train
def add_file(path, **kwords) # Don't mangle query, the file API is inconsistently using camelCase # rather than CamelCase. response = connection.send(:post, "/repos/#{self.Name}/file/#{path}", query: kwords, query_mangle: false) hash = JSON.parse(response.body) error = Errors::RepositoryFileError.from_hash(hash) raise error if error hash['Report']['Added'] end
ruby
{ "resource": "" }
q7685
Aptly.Repository.packages
train
def packages(**kwords) response = connection.send(:get, "/repos/#{self.Name}/packages", query: kwords, query_mangle: false) JSON.parse(response.body) end
ruby
{ "resource": "" }
q7686
Aptly.Repository.edit!
train
def edit!(**kwords) response = connection.send(:put, "/repos/#{self.Name}", body: JSON.generate(kwords)) hash = JSON.parse(response.body, symbolize_names: true) return nil if hash == marshal_dump marshal_load(hash) self end
ruby
{ "resource": "" }
q7687
Mei.Loc.parse_authority_response
train
def parse_authority_response threaded_responses = [] #end_response = Array.new(20) end_response = [] position_counter = 0 @raw_response.select {|response| response[0] == "atom:entry"}.map do |response| threaded_responses << Thread.new(position_counter) { |local_pos| end_response[local_pos] = loc_response_to_qa(response_to_struct(response), position_counter) } position_counter+=1 #sleep(0.05) #loc_response_to_qa(response_to_struct(response)) end threaded_responses.each { |thr| thr.join } end_response end
ruby
{ "resource": "" }
q7688
Mei.Loc.loc_response_to_qa
train
def loc_response_to_qa(data, counter) json_link = data.links.select { |link| link.first == 'application/json' } if json_link.present? json_link = json_link[0][1] broader, narrower, variants = get_skos_concepts(json_link.gsub('.json','')) end #count = ActiveFedora::Base.find_with_conditions("subject_tesim:#{data.id.gsub('info:lc', 'http://id.loc.gov').gsub(':','\:')}", rows: '100', fl: 'id' ).length #FIXME count = ActiveFedora::Base.search_with_conditions("#{@solr_field}:#{solr_clean(data.id.gsub('info:lc', 'http://id.loc.gov'))}", rows: '100', fl: 'id' ).length #count = 0 if count >= 99 count = "99+" else count = count.to_s end { "uri_link" => data.id.gsub('info:lc', 'http://id.loc.gov') || data.title, "label" => data.title, "broader" => broader, "narrower" => narrower, "variants" => variants, "count" => count } end
ruby
{ "resource": "" }
q7689
Pullr.RemoteRepository.name
train
def name dirs = File.expand_path(@uri.path).split(File::SEPARATOR) unless dirs.empty? if @scm == :sub_version if dirs[-1] == 'trunk' dirs.pop elsif (dirs[-2] == 'branches' || dirs[-2] == 'tags') dirs.pop dirs.pop end elsif @scm == :git dirs.last.chomp!('.git') end end return (dirs.last || @uri.host) end
ruby
{ "resource": "" }
q7690
HipsterSqlToHbase.Executor.execute
train
def execute(thrift_call_group,host_s=nil,port_n=nil,incr=false) @@host = host_s if !host_s.nil? @@port = port_n if !port_n.nil? socket = Thrift::Socket.new(@@host, @@port) transport = Thrift::BufferedTransport.new(socket) transport.open protocol = Thrift::BinaryProtocol.new(transport) client = HBase::Client.new(protocol) results = [] if incr not_incr = true c_row = 0 end thrift_call_group.each do |thrift_call| if incr if not_incr c_row = increment_table_row_index(thrift_call[:arguments][0],thrift_call_group.length,client) not_incr = false end c_row += 1 thrift_call[:arguments][1] = c_row.to_s end results << client.send(thrift_call[:method],*thrift_call[:arguments]) end results.flatten end
ruby
{ "resource": "" }
q7691
Logan.Project.todolists
train
def todolists active_response = Logan::Client.get "/projects/#{@id}/todolists.json" lists_array = active_response.parsed_response.map do |h| Logan::TodoList.new h.merge({ :project_id => @id }) end end
ruby
{ "resource": "" }
q7692
Logan.Project.publish
train
def publish post_params = { :body => {}.to_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/projects/#{@id}/publish.json", post_params end
ruby
{ "resource": "" }
q7693
Logan.Project.completed_todolists
train
def completed_todolists completed_response = Logan::Client.get "/projects/#{@id}/todolists/completed.json" lists_array = completed_response.parsed_response.map do |h| Logan::TodoList.new h.merge({ :project_id => @id }) end end
ruby
{ "resource": "" }
q7694
Logan.Project.todolist
train
def todolist(list_id) response = Logan::Client.get "/projects/#{@id}/todolists/#{list_id}.json" Logan::TodoList.new response.parsed_response.merge({ :project_id => @id }) end
ruby
{ "resource": "" }
q7695
Logan.Project.create_todolist
train
def create_todolist(todo_list) post_params = { :body => todo_list.post_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/projects/#{@id}/todolists.json", post_params Logan::TodoList.new response.merge({ :project_id => @id }) end
ruby
{ "resource": "" }
q7696
Logan.Project.create_message
train
def create_message(subject, content, subscribers, private) post_params = { :body => {subject: subject, content: content, subscribers: subscribers, private: private}.to_json, :headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'}) } response = Logan::Client.post "/projects/#{@id}/messages.json", post_params Logan::Project.new response end
ruby
{ "resource": "" }
q7697
Rattler::Parsers.Rule.parse
train
def parse(scanner, rules, scope = ParserScope.empty) catch(:rule_failed) do return expr.parse(scanner, rules, scope) end false end
ruby
{ "resource": "" }
q7698
CrashLog.Configuration.development_mode=
train
def development_mode=(flag) self[:development_mode] = flag self.level = Logger::DEBUG if new_logger new_logger.level = self.level if self.logger.respond_to?(:level=) end end
ruby
{ "resource": "" }
q7699
Mellon.Keychain.[]=
train
def []=(key, data) info, _ = read(key) info ||= {} if data write(key, data, info) else delete(key, info) end end
ruby
{ "resource": "" }