_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q8900
Kanpachi.ResourceList.named
train
def named(name) resource = all.detect { |resource| resource.name == name } if resource.nil? raise UnknownResource, "Resource named #{name} doesn't exist" else resource end end
ruby
{ "resource": "" }
q8901
EM::Xmpp.CertStore.trusted?
train
def trusted?(pem) if cert = OpenSSL::X509::Certificate.new(pem) rescue nil @store.verify(cert).tap do |trusted| @store.add_cert(cert) if trusted rescue nil end end end
ruby
{ "resource": "" }
q8902
EM::Xmpp.CertStore.certs
train
def certs unless @@certs pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m dir = @cert_directory certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) } certs = certs.map {|c| c.scan(pattern) }.flatten certs.map! {|c| OpenSSL::X509::Certificate.new(c) } @@certs = certs.reject {|c| c.not_after < Time.now } end @@certs end
ruby
{ "resource": "" }
q8903
StorageRoom.Image.url
train
def url(name = nil) if name if version_identifiers.include?(name.to_s) self[:@versions][name.to_s][:@url] else raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})" end else self[:@url] end end
ruby
{ "resource": "" }
q8904
Iord.Fields.field_attribute
train
def field_attribute(attr) return 'id' if attr == :_id # default, simply return name return attr unless attr.is_a? Hash # else, Hash return attr[:object] if attr.has_key? :object return attr[:array] if attr.has_key? :array return attr[:value] if attr.has_key? :value return attr[:link] if attr.has_key? :link attr.keys[0] end
ruby
{ "resource": "" }
q8905
Faker.Taxonomy.lookup
train
def lookup(code) TAXONOMY.select {|t| t.code.eql?(code) }.first end
ruby
{ "resource": "" }
q8906
Kanpachi.ErrorList.add
train
def add(error) if @list.key? error.name raise DuplicateError, "An error named #{error.name} already exists" end @list[error.name] = error end
ruby
{ "resource": "" }
q8907
Lotto.Draw.draw
train
def draw drawns = [] @options[:include].each { |n| drawns << n } unless @options[:include].nil? count = @options[:include] ? @options[:pick] - @options[:include].count : @options[:pick] count.times { drawns << pick(drawns) } drawns end
ruby
{ "resource": "" }
q8908
Lotto.Draw.basket
train
def basket numbers = (1..@options[:of]) numbers = numbers.reject { |n| @options[:include].include? n } unless @options[:include].nil? numbers = numbers.reject { |n| @options[:exclude].include? n } unless @options[:exclude].nil? numbers end
ruby
{ "resource": "" }
q8909
Checkdin.Activities.activities
train
def activities(options={}) response = connection.get do |req| req.url "activities", options end return_error_or_body(response) end
ruby
{ "resource": "" }
q8910
Digistore24.Notification.signature
train
def signature # Remove 'sha_sign' key from request params and concatenate all # key value pairs params = payload.to_h .reject { |key, value| key == :sha_sign } .reject { |key, value| value == '' || value == false }.sort .map { | key, value| "#{key}=#{value}#{passphrase}" }.join # Calculate SHA512 and upcase all letters, since Digistore will # also return upcased letters in the signature. Digest::SHA512.hexdigest(params).upcase end
ruby
{ "resource": "" }
q8911
Edoors.Board.process_p
train
def process_p p @viewer.receive_p p if @viewer if p.action!=Edoors::ACT_ERROR and p.action!=Edoors::ACT_PASS_THROUGH p2 = @postponed[p.link_value] ||= p return if p2==p @postponed.delete p.link_value p,p2 = p2,p if p.action==Edoors::ACT_FOLLOW p.merge! p2 end @saved = p receive_p p _garbage if not @saved.nil? end
ruby
{ "resource": "" }
q8912
TCOMethod.BlockExtractor.determine_offsets
train
def determine_offsets(block, source) tokens = Ripper.lex(source) start_offset, start_token = determine_start_offset(block, tokens) expected_match = start_token == :on_kw ? :on_kw : :on_rbrace end_offset = determine_end_offset(block, tokens, source, expected_match) [start_offset, end_offset] end
ruby
{ "resource": "" }
q8913
ExtendModelAt.Extention.method_missing
train
def method_missing(m, *args, &block) column_name = m.to_s.gsub(/\=$/, '') raise ExtendModelAt::InvalidColumn, "#{column_name} not exist" if @static == true and not (@columns.try(:keys).try(:include?, column_name.to_sym) ) # If the method don't finish with "=" is fore read if m !~ /\=$/ self[m.to_s] # but if finish with "=" is for wirte else self[column_name.to_s] = args.first end end
ruby
{ "resource": "" }
q8914
ExtendModelAt.Extention.get_adapter
train
def get_adapter(column, value) if @columns[column.to_sym][:type] == String return :to_s elsif @columns[column.to_sym][:type] == Fixnum return :to_i if value.respond_to? :to_i elsif @columns[column.to_sym][:type] == Float return :to_f if value.respond_to? :to_f elsif @columns[column.to_sym][:type] == Time return :to_time if value.respond_to? :to_time elsif @columns[column.to_sym][:type] == Date return :to_date if value.respond_to? :to_date end nil end
ruby
{ "resource": "" }
q8915
ExtendModelAt.Extention.get_defaults_values
train
def get_defaults_values(options = {}) defaults_ = {} options[:columns].each do |column, config| defaults_[column.to_s] = @columns[column.to_sym][:default] || nil end defaults_ end
ruby
{ "resource": "" }
q8916
Checkdin.PointAccountEntries.point_account_entries
train
def point_account_entries(options={}) response = connection.get do |req| req.url "point_account_entries", options end return_error_or_body(response) end
ruby
{ "resource": "" }
q8917
Fetch.Request.process!
train
def process!(body, url, effective_url) before_process! body = parse!(body) @process_callback.call(body, url, effective_url) if @process_callback after_process! rescue => e error!(e) end
ruby
{ "resource": "" }
q8918
GroupDocsSignatureCloud.SignatureApi.get_qr_codes_with_http_info
train
def get_qr_codes_with_http_info() @api_client.config.logger.debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client.config.debugging # resource path local_var_path = '/signature/qrcodes' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = nil data, status_code, headers = @api_client.call_api(:GET, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'QRCodeCollection') if @api_client.config.debugging @api_client.config.logger.debug "API called: SignatureApi#get_qr_codes\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
ruby
{ "resource": "" }
q8919
GroupDocsSignatureCloud.SignatureApi.post_verification_collection_with_http_info
train
def post_verification_collection_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest @api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging # verify the required parameter 'name' is set raise ArgumentError, 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client.config.client_side_validation && request.name.nil? # resource path local_var_path = '/signature/{name}/collection/verification' local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', request.name.to_s) # query parameters query_params = {} if local_var_path.include? ('{' + downcase_first_letter('Password') + '}') local_var_path = local_var_path.sub('{' + downcase_first_letter('Password') + '}', request.password.to_s) else query_params[downcase_first_letter('Password')] = request.password unless request.password.nil? end if local_var_path.include? ('{' + downcase_first_letter('Folder') + '}') local_var_path = local_var_path.sub('{' + downcase_first_letter('Folder') + '}', request.folder.to_s) else query_params[downcase_first_letter('Folder')] = request.folder unless request.folder.nil? end if local_var_path.include? ('{' + downcase_first_letter('Storage') + '}') local_var_path = local_var_path.sub('{' + downcase_first_letter('Storage') + '}', request.storage.to_s) else query_params[downcase_first_letter('Storage')] = request.storage unless request.storage.nil? end # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.verify_options_collection_data) data, status_code, headers = @api_client.call_api(:POST, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'VerifiedDocumentResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
ruby
{ "resource": "" }
q8920
Nokogiri::Decorators::XBEL.Entry.desc=
train
def desc=(value) node = at './desc' node ||= add_child Nokogiri::XML::Node.new('desc', document) node.content = value end
ruby
{ "resource": "" }
q8921
Nokogiri::Decorators::XBEL.Entry.added=
train
def added=(value) set_attribute 'added', case value when Time; value.strftime '%Y-%m-%d' when String; value else raise ArgumentError end end
ruby
{ "resource": "" }
q8922
Empyrean.TweetParser.parse
train
def parse(tweets) retdict = { mentions: {}, hashtags: {}, clients: {}, smileys: {}, times_of_day: [0] * 24, tweet_count: 0, retweet_count: 0, selftweet_count: 0, } tweets.each do |tweet| parsed_tweet = self.parse_one tweet if parsed_tweet[:retweet] # the tweet was a retweet # increase retweeted tweets count retdict[:retweet_count] += 1 else parsed_tweet[:mentions].each do |user, data| # add mentions to the mentions dict retdict[:mentions][user] ||= { count: 0 } retdict[:mentions][user][:count] += data[:count] retdict[:mentions][user][:name] ||= data[:name] retdict[:mentions][user][:examples] ||= [] retdict[:mentions][user][:examples] << data[:example] end parsed_tweet[:hashtags].each do |hashtag, data| # add hashtags to the hashtags dict retdict[:hashtags][hashtag] ||= { count: 0 } retdict[:hashtags][hashtag][:count] += data[:count] retdict[:hashtags][hashtag][:hashtag] ||= data[:hashtag] retdict[:hashtags][hashtag][:examples] ||= [] retdict[:hashtags][hashtag][:examples] << data[:example] end parsed_tweet[:smileys].each do |smile, data| retdict[:smileys][smile] ||= { count: 0 } retdict[:smileys][smile][:frown] ||= data[:frown] retdict[:smileys][smile][:count] += data[:count] retdict[:smileys][smile][:smiley] ||= data[:smiley] retdict[:smileys][smile][:examples] ||= [] retdict[:smileys][smile][:examples] << data[:example] end # increase self tweeted tweets count retdict[:selftweet_count] += 1 end # add client to the clients dict client_dict = parsed_tweet[:client][:name] retdict[:clients][client_dict] ||= { count: 0 } retdict[:clients][client_dict][:count] += 1 retdict[:clients][client_dict][:name] = parsed_tweet[:client][:name] retdict[:clients][client_dict][:url] = parsed_tweet[:client][:url] retdict[:times_of_day][parsed_tweet[:time_of_day]] += 1 # increase tweet count retdict[:tweet_count] += 1 end retdict end
ruby
{ "resource": "" }
q8923
Fb.HTTPRequest.run
train
def run if response.is_a? @expected_response self.class.on_response.call(self, response) response.tap do parse_response! end else raise HTTPError.new(error_message, response: response) end end
ruby
{ "resource": "" }
q8924
BitMagic.Bits.read
train
def read(name, field = nil) field ||= self.field if name.is_a?(Integer) field.read_field(name) elsif bits = @field_list[name] field.read_field(bits) end end
ruby
{ "resource": "" }
q8925
BitMagic.Bits.write
train
def write(name, target_value) if name.is_a?(Symbol) self.write(@field_list[name], target_value) elsif name.is_a?(Integer) self.update self.field.write_bits(name => @options[:bool_caster].call(target_value)) elsif name.respond_to?(:[]) and target_value.respond_to?(:[]) bits = {} name.each_with_index do |bit, i| bits[bit] = @options[:bool_caster].call(target_value[i]) end self.update self.field.write_bits bits end end
ruby
{ "resource": "" }
q8926
MassShootings.Shooting.as_json
train
def as_json(_=nil) json = {'id' => id} json['allegedShooters'] = alleged_shooters unless alleged_shooters.nil? json.merge( 'casualties' => casualties.stringify_keys, 'date' => date.iso8601, 'location' => location, 'references' => references.map(&:to_s)) end
ruby
{ "resource": "" }
q8927
SimilarityTree.SimilarityTree.prune
train
def prune(nodes) nodes.each do |node| node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold) end end
ruby
{ "resource": "" }
q8928
Redhead.String.headers!
train
def headers!(hash) changing = headers.select { |header| hash.has_key?(header.key) } # modifies its elements! changing.each do |header| new_values = hash[header.key] header.raw = new_values[:raw] if new_values[:raw] header.key = new_values[:key] if new_values[:key] end Redhead::HeaderSet.new(changing) end
ruby
{ "resource": "" }
q8929
Easymongo.Document.method_missing
train
def method_missing(name, *args, &block) return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '=' end
ruby
{ "resource": "" }
q8930
AndFeathers.Sugar.dir
train
def dir(name, mode = 16877, &block) name_parts = name.split(::File::SEPARATOR) innermost_child_name = name_parts.pop if name_parts.empty? Directory.new(name, mode).tap do |directory| add_directory(directory) block.call(directory) if block end else innermost_parent = name_parts.reduce(self) do |parent, child_name| parent.dir(child_name) end innermost_parent.dir(innermost_child_name, &block) end end
ruby
{ "resource": "" }
q8931
AndFeathers.Sugar.file
train
def file(name, mode = 33188, &content) content ||= NO_CONTENT name_parts = name.split(::File::SEPARATOR) file_name = name_parts.pop if name_parts.empty? File.new(name, mode, content).tap do |file| add_file(file) end else dir(name_parts.join(::File::SEPARATOR)) do |parent| parent.file(file_name, mode, &content) end end end
ruby
{ "resource": "" }
q8932
Tropo.Message.request_xml
train
def request_xml request_params = @params.dup token = request_params.delete("token") xml = "" request_params.each do |key, value| xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>" end "<sessions><token>#{token}</token>#{xml}</sessions>" end
ruby
{ "resource": "" }
q8933
Shamu.Attributes.to_attributes
train
def to_attributes( only: nil, except: nil ) self.class.attributes.each_with_object({}) do |(name, options), attrs| next if ( only && !match_attribute?( only, name ) ) || ( except && match_attribute?( except, name ) ) next unless serialize_attribute?( name, options ) attrs[name] = send( name ) end end
ruby
{ "resource": "" }
q8934
Rsxml.Namespace.compact_attr_qnames
train
def compact_attr_qnames(ns_stack, attrs) Hash[attrs.map do |name,value| [compact_qname(ns_stack, name), value] end] end
ruby
{ "resource": "" }
q8935
Rsxml.Namespace.find_namespace_uri
train
def find_namespace_uri(ns_stack, prefix, uri_check=nil) tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)} uri = tns[prefix] if tns raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check uri end
ruby
{ "resource": "" }
q8936
Rsxml.Namespace.undeclared_namespace_bindings
train
def undeclared_namespace_bindings(ns_stack, ns_explicit) Hash[ns_explicit.map do |prefix,uri| [prefix, uri] if !find_namespace_uri(ns_stack, prefix, uri) end.compact] end
ruby
{ "resource": "" }
q8937
Rsxml.Namespace.exploded_namespace_declarations
train
def exploded_namespace_declarations(ns) Hash[ns.map do |prefix, uri| if prefix=="" ["xmlns", uri] else [[prefix, "xmlns"], uri] end end] end
ruby
{ "resource": "" }
q8938
Rsxml.Namespace.namespace_attributes
train
def namespace_attributes(ns) Hash[ns.map do |prefix, uri| if prefix=="" ["xmlns", uri] else [["xmlns", prefix].join(":"), uri] end end] end
ruby
{ "resource": "" }
q8939
Rsxml.Namespace.merge_namespace_bindings
train
def merge_namespace_bindings(ns1, ns2) m = ns1.clone ns2.each do |k,v| raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m.has_key?(k) && m[k]!=v m[k]=v end m end
ruby
{ "resource": "" }
q8940
Caliph.Shell.spawn_process
train
def spawn_process(command_line) host_stdout, cmd_stdout = IO.pipe host_stderr, cmd_stderr = IO.pipe pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr) cmd_stdout.close cmd_stderr.close return pid, host_stdout, host_stderr end
ruby
{ "resource": "" }
q8941
Caliph.Shell.execute
train
def execute(command_line) result = collect_result(command_line, *spawn_process(command_line)) result.wait result end
ruby
{ "resource": "" }
q8942
Caliph.Shell.run_as_replacement
train
def run_as_replacement(*args, &block) command_line = normalize_command_line(*args, &block) report "Ceding execution to: " report command_line.string_format Process.exec(command_line.command_environment, command_line.command) end
ruby
{ "resource": "" }
q8943
Caliph.Shell.run_detached
train
def run_detached(*args, &block) command_line = normalize_command_line(*args, &block) pid, out, err = spawn_process(command_line) Process.detach(pid) return collect_result(command_line, pid, out, err) end
ruby
{ "resource": "" }
q8944
Scram.Holder.can?
train
def can? action, target target = target.to_s if target.is_a? Symbol action = action.to_s # Checks policies in priority order for explicit allow or deny. policies.sort_by(&:priority).reverse.each do |policy| opinion = policy.can?(self, action, target) return opinion.to_bool if %i[allow deny].include? opinion end return false end
ruby
{ "resource": "" }
q8945
SectionsRails.Section.referenced_sections
train
def referenced_sections recursive = true result = PartialParser.find_sections partial_content # Find all sections within the already known sections. if recursive i = -1 while (i += 1) < result.size Section.new(result[i]).referenced_sections(false).each do |referenced_section| result << referenced_section unless result.include? referenced_section end end end result.sort! end
ruby
{ "resource": "" }
q8946
SectionsRails.Section.render
train
def render &block raise "Section #{folder_filepath} doesn't exist." unless Dir.exists? folder_filepath result = [] render_assets result if Rails.application.config.assets.compile render_partial result, &block result.join("\n").html_safe end
ruby
{ "resource": "" }
q8947
ChainOptions.Option.new_value
train
def new_value(*args, &block) value = value_from_args(args, &block) value = if incremental incremental_value(value) else filter_value(transformed_value(value)) end if value_valid?(value) self.custom_value = value elsif invalid.to_s == 'default' && !incremental default_value else fail ArgumentError, "The value #{value.inspect} is not valid." end end
ruby
{ "resource": "" }
q8948
ChainOptions.Option.to_h
train
def to_h PARAMETERS.each_with_object({}) do |param, hash| next if send(param).nil? hash[param] = send(param) end end
ruby
{ "resource": "" }
q8949
ChainOptions.Option.value_from_args
train
def value_from_args(args, &block) return block if ChainOptions::Util.blank?(args) && block && allow_block flat_value(args) end
ruby
{ "resource": "" }
q8950
ChainOptions.Option.flat_value
train
def flat_value(args) return args.first if args.is_a?(Enumerable) && args.count == 1 args end
ruby
{ "resource": "" }
q8951
ChainOptions.Option.transformed_value
train
def transformed_value(value) return value unless transform transformed = Array(value).map(&transform) value.is_a?(Enumerable) ? transformed : transformed.first end
ruby
{ "resource": "" }
q8952
MissingText.Writer.get_entry_for
train
def get_entry_for(entry, language) if entry.length > 1 entry_string = get_entry_for_rec(entry[1..-1], language, hashes[language][entry[0]]) else entry_string = hashes[language][entry[0]] end if entry_string.kind_of?(Array) entry_string = entry_string.map(&:inspect).join(', ') end entry_string end
ruby
{ "resource": "" }
q8953
Redlander.Parsing.from
train
def from(content, options = {}) format = options[:format].to_s mime_type = options[:mime_type] && options[:mime_type].to_s type_uri = options[:type_uri] && options[:type_uri].to_s base_uri = options[:base_uri] && options[:base_uri].to_s content = Uri.new(content) if content.is_a?(URI) # FIXME: to be fixed in librdf: # ntriples parser absolutely needs "\n" at the end of the input if format == "ntriples" && !content.is_a?(Uri) && !content.end_with?("\n") content << "\n" end rdf_parser = Redland.librdf_new_parser(Redlander.rdf_world, format, mime_type, type_uri) raise RedlandError, "Failed to create a new '#{format}' parser" if rdf_parser.null? begin if block_given? rdf_stream = if content.is_a?(Uri) Redland.librdf_parser_parse_as_stream(rdf_parser, content.rdf_uri, base_uri) else Redland.librdf_parser_parse_string_as_stream(rdf_parser, content, base_uri) end raise RedlandError, "Failed to create a new stream" if rdf_stream.null? begin while Redland.librdf_stream_end(rdf_stream).zero? statement = Statement.new(Redland.librdf_stream_get_object(rdf_stream)) statements.add(statement) if yield statement Redland.librdf_stream_next(rdf_stream) end ensure Redland.librdf_free_stream(rdf_stream) end else if content.is_a?(Uri) Redland.librdf_parser_parse_into_model(rdf_parser, content.rdf_uri, base_uri, @rdf_model).zero? else Redland.librdf_parser_parse_string_into_model(rdf_parser, content, base_uri, @rdf_model).zero? end end ensure Redland.librdf_free_parser(rdf_parser) end self end
ruby
{ "resource": "" }
q8954
Cathode.IndexRequest.model
train
def model if @resource_tree.size > 1 parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"] model = @resource_tree.first.model.find(parent_model_id) @resource_tree.drop(1).each do |resource| model = model.send resource.name end model else super.all end end
ruby
{ "resource": "" }
q8955
Cathode.IndexRequest.default_action_block
train
def default_action_block proc do all_records = model if allowed?(:paging) && params[:page] page = params[:page] per_page = params[:per_page] || 10 lower_bound = (per_page - 1) * page upper_bound = lower_bound + per_page - 1 body all_records[lower_bound..upper_bound] else body all_records end end end
ruby
{ "resource": "" }
q8956
Simulator.Equation.evaluate_in
train
def evaluate_in(context, periods = []) sandbox = Sandbox.new context, periods sandbox.instance_eval &@equation_block end
ruby
{ "resource": "" }
q8957
Rufus::Jig.Couch.all
train
def all(opts={}) opts = opts.dup # don't touch the original path = adjust('_all_docs') opts[:include_docs] = true if opts[:include_docs].nil? adjust_params(opts) keys = opts.delete(:keys) return [] if keys && keys.empty? res = if keys opts[:cache] = :with_body if opts[:cache].nil? @http.post(path, { 'keys' => keys }, opts) else @http.get(path, opts) end rows = res['rows'] docs = if opts[:params][:include_docs] rows.map { |row| row['doc'] } else rows.map { |row| { '_id' => row['id'], '_rev' => row['value']['rev'] } } end if opts[:include_design_docs] == false docs = docs.reject { |doc| DESIGN_PATH_REGEX.match(doc['_id']) } end docs end
ruby
{ "resource": "" }
q8958
Rufus::Jig.Couch.attach
train
def attach(doc_id, doc_rev, attachment_name, data, opts=nil) if opts.nil? opts = data data = attachment_name attachment_name = doc_rev doc_rev = doc_id['_rev'] doc_id = doc_id['_id'] end attachment_name = attachment_name.gsub(/\//, '%2F') ct = opts[:content_type] raise(ArgumentError.new( ":content_type option must be specified" )) unless ct opts[:cache] = false path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}") if @http.variant == :patron # patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting # attachements # this is a fallback to net/http require 'net/http' http = Net::HTTP.new(@http.host, @http.port) req = Net::HTTP::Put.new(path) req['User-Agent'] = "rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)" req['Content-Type'] = opts[:content_type] req['Accept'] = 'application/json' req.body = data res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) }) return @http.send(:respond, :put, path, nil, opts, nil, res) end @http.put(path, data, opts) end
ruby
{ "resource": "" }
q8959
Rufus::Jig.Couch.detach
train
def detach(doc_id, doc_rev, attachment_name=nil) if attachment_name.nil? attachment_name = doc_rev doc_rev = doc_id['_rev'] doc_id = doc_id['_id'] end attachment_name = attachment_name.gsub(/\//, '%2F') path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}") @http.delete(path) end
ruby
{ "resource": "" }
q8960
Rufus::Jig.Couch.on_change
train
def on_change(opts={}, &block) query = { 'feed' => 'continuous', 'heartbeat' => opts[:heartbeat] || 20_000 } #'since' => 0 } # that's already the default query['include_docs'] = true if block.arity > 2 query = query.map { |k, v| "#{k}=#{v}" }.join('&') socket = TCPSocket.open(@http.host, @http.port) auth = @http.options[:basic_auth] if auth auth = Base64.encode64(auth.join(':')).strip auth = "Authorization: Basic #{auth}\r\n" else auth = '' end socket.print("GET /#{path}/_changes?#{query} HTTP/1.1\r\n") socket.print("User-Agent: rufus-jig #{Rufus::Jig::VERSION}\r\n") #socket.print("Accept: application/json;charset=UTF-8\r\n") socket.print(auth) socket.print("\r\n") # consider reply answer = socket.gets.strip status = answer.match(/^HTTP\/.+ (\d{3}) /)[1].to_i raise Rufus::Jig::HttpError.new(status, answer) if status != 200 # discard headers loop do data = socket.gets break if data.nil? || data == "\r\n" end # the on_change loop loop do data = socket.gets break if data.nil? data = (Rufus::Json.decode(data) rescue nil) next unless data.is_a?(Hash) args = [ data['id'], (data['deleted'] == true) ] args << data['doc'] if block.arity > 2 block.call(*args) end on_change(opts, &block) if opts[:reconnect] end
ruby
{ "resource": "" }
q8961
Rufus::Jig.Couch.nuke_design_documents
train
def nuke_design_documents docs = get('_all_docs')['rows'] views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) } views.each { |v| delete(v['id'], v['value']['rev']) } end
ruby
{ "resource": "" }
q8962
Rufus::Jig.Couch.query
train
def query(path, opts={}) opts = opts.dup # don't touch the original raw = opts.delete(:raw) path = if DESIGN_PATH_REGEX.match(path) path else doc_id, view = path.split(':') path = "_design/#{doc_id}/_view/#{view}" end path = adjust(path) adjust_params(opts) keys = opts.delete(:keys) res = if keys opts[:cache] = :with_body if opts[:cache].nil? @http.post(path, { 'keys' => keys }, opts) else @http.get(path, opts) end return nil if res == true # POST and the view doesn't exist return res if raw res.nil? ? res : res['rows'] end
ruby
{ "resource": "" }
q8963
Rufus::Jig.Couch.query_for_docs
train
def query_for_docs(path, opts={}) res = query(path, opts.merge(:include_docs => true)) if res.nil? nil elsif opts[:raw] res else res.collect { |row| row['doc'] }.uniq end end
ruby
{ "resource": "" }
q8964
Motivosity.Client.send_appreciation!
train
def send_appreciation!(user_id, opts = {}) params = { "toUserID" => user_id } params["companyValueID"] = opts[:company_value_id] if opts[:company_value_id] params["amount"] = opts[:amount] if opts[:amount] params["note"] = opts[:note] if opts[:note] params["privateAppreciation"] = opts[:private] || false put "/api/v1/user/#{user_id}/appreciation", {}, params end
ruby
{ "resource": "" }
q8965
NsOptions.NamespaceData.define
train
def define(&block) if block && block.arity > 0 block.call @ns elsif block @ns.instance_eval(&block) end @ns end
ruby
{ "resource": "" }
q8966
Tay.Packager.extension_id
train
def extension_id raise Tay::PrivateKeyNotFound.new unless private_key_exists? public_key = OpenSSL::PKey::RSA.new(File.read(full_key_path)).public_key.to_der hash = Digest::SHA256.hexdigest(public_key)[0...32] hash.unpack('C*').map{ |c| c < 97 ? c + 49 : c + 10 }.pack('C*') end
ruby
{ "resource": "" }
q8967
Tay.Packager.write_new_key
train
def write_new_key File.open(full_key_path, 'w') do |f| f.write OpenSSL::PKey::RSA.generate(1024).export() end end
ruby
{ "resource": "" }
q8968
Rsxml.Xml.traverse
train
def traverse(element, visitor, context = Visitor::Context.new) ns_bindings = namespace_bindings_from_defs(element.namespace_definitions) context.ns_stack.push(ns_bindings) eelement, eattrs = explode_element(element) begin visitor.element(context, eelement, eattrs, ns_bindings) do element.children.each do |child| if child.element? traverse(child, visitor, context) elsif child.text? visitor.text(context, child.content) else Rsxml.log{|logger| logger.warn("unknown Nokogiri Node type: #{child.inspect}")} end end end ensure context.ns_stack.pop end visitor end
ruby
{ "resource": "" }
q8969
FentonShell.ConfigFile.config_file_create
train
def config_file_create(global_options, options) config_directory_create(global_options) file = "#{global_options[:directory]}/config" options.store(:fenton_server_url, global_options[:fenton_server_url]) content = config_generation(options) File.write(file, content) [true, 'ConfigFile': ['created!']] end
ruby
{ "resource": "" }
q8970
FentonShell.ConfigFile.config_generation
train
def config_generation(options) config_contents = {} config_options = options.keys.map(&:to_sym).sort.uniq config_options.delete(:password) config_options.each do |config_option| config_contents.store(config_option.to_sym, options[config_option]) end config_contents.store(:default_organization, options[:username]) config_contents.to_yaml end
ruby
{ "resource": "" }
q8971
Conify.Helpers.format_with_bang
train
def format_with_bang(message) return message if !message.is_a?(String) return '' if message.to_s.strip == '' " ! " + message.encode('utf-8', 'binary', invalid: :replace, undef: :replace).split("\n").join("\n ! ") end
ruby
{ "resource": "" }
q8972
Conify.Helpers.to_table
train
def to_table(data, headers) column_lengths = [] gutter = 2 table = '' # Figure out column widths based on longest string in each column (including the header string) headers.each { |header| width = data.map { |_| _[header] }.max_by(&:length).length width = header.length if width < header.length column_lengths << width } # format the length of a table cell string to make it as wide as the column (by adding extra spaces) format_row_entry = lambda { |entry, i| entry + (' ' * (column_lengths[i] - entry.length + gutter)) } # Add headers headers.each_with_index { |header, i| table += format_row_entry.call(header, i) } table += "\n" # Add line breaks under headers column_lengths.each { |length| table += (('-' * length) + (' ' * gutter)) } table += "\n" # Add rows data.each { |row| headers.each_with_index { |header, i| table += format_row_entry.call(row[header], i) } table += "\n" } table end
ruby
{ "resource": "" }
q8973
Warden.Proxy.clear_strategies_cache!
train
def clear_strategies_cache!(*args) scope, opts = _retrieve_scope_and_opts(args) @winning_strategies.delete(scope) @strategies[scope].each do |k, v| v.clear! if args.empty? || args.include?(k) end end
ruby
{ "resource": "" }
q8974
Warden.Proxy.set_user
train
def set_user(user, opts = {}) scope = (opts[:scope] ||= @config.default_scope) # Get the default options from the master configuration for the given scope opts = (@config[:scope_defaults][scope] || {}).merge(opts) opts[:event] ||= :set_user @users[scope] = user if opts[:store] != false && opts[:event] != :fetch options = env[ENV_SESSION_OPTIONS] options[:renew] = true if options session_serializer.store(user, scope) end run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks @users[scope] end
ruby
{ "resource": "" }
q8975
Lono.Core.env_from_profile
train
def env_from_profile(aws_profile) data = YAML.load_file("#{Lono.root}/config/settings.yml") env = data.find do |_env, setting| setting ||= {} profiles = setting['aws_profiles'] profiles && profiles.include?(aws_profile) end env.first if env end
ruby
{ "resource": "" }
q8976
HashControl.Validator.require
train
def require(*keys) permitted_keys.merge keys required_keys = keys.to_set unless (missing_keys = required_keys - hash_keys).empty? error "required #{terms} #{missing_keys.to_a} missing" + postscript end self end
ruby
{ "resource": "" }
q8977
Redlander.Node.datatype
train
def datatype if instance_variable_defined?(:@datatype) @datatype else @datatype = if literal? rdf_uri = Redland.librdf_node_get_literal_value_datatype_uri(rdf_node) rdf_uri.null? ? XmlSchema.datatype_of("") : URI.parse(Redland.librdf_uri_to_string(rdf_uri)) else nil end end end
ruby
{ "resource": "" }
q8978
Redlander.Node.value
train
def value if resource? uri elsif blank? Redland.librdf_node_get_blank_identifier(rdf_node).force_encoding("UTF-8") else v = Redland.librdf_node_get_literal_value(rdf_node).force_encoding("UTF-8") v << "@#{lang}" if lang XmlSchema.instantiate(v, datatype) end end
ruby
{ "resource": "" }
q8979
Repository.Base.delete
train
def delete(identifier) RecordDeleter.new(identifier: identifier, dao: dao, factory: factory) .delete end
ruby
{ "resource": "" }
q8980
WillPaginateRenderers.Gmail.window
train
def window base = @collection.offset high = base + @collection.per_page high = @collection.total_entries if high > @collection.total_entries # TODO: What's the best way to allow customization of this text, particularly "of"? tag(:span, " #{base + 1} - #{high} of #{@collection.total_entries} ", :class => WillPaginateRenderers.pagination_options[:gmail_window_class]) end
ruby
{ "resource": "" }
q8981
Echonest.Artist.news
train
def news(options = { results: 1 }) response = get_response(results: options[:results], name: @name) response[:news].collect do |b| Blog.new(name: b[:name], site: b[:site], url: b[:url]) end end
ruby
{ "resource": "" }
q8982
SycLink.Website.list_links
train
def list_links(args = {}) if args.empty? links else links.select { |link| link.match? args } end end
ruby
{ "resource": "" }
q8983
SycLink.Website.merge_links_on
train
def merge_links_on(attribute, concat_string = ',') links_group_by(attribute) .select { |key, link_list| links.size > 1 } .map do |key, link_list| merge_attributes = Link::ATTRS - [attribute] link_list.first .update(Hash[extract_columns(link_list, merge_attributes) .map { |c| c.uniq.join(concat_string) } .collect { |v| [merge_attributes.shift, v] }]) link_list.shift link_list.each { |link| links.delete(link) } end end
ruby
{ "resource": "" }
q8984
SycLink.Website.links_group_by
train
def links_group_by(attribute, linkz = links) linkz.map { |link| { key: link.send(attribute), link: link } } .group_by { |entry| entry[:key] } .each { |key, link| link.map! { |l| l[:link] }} end
ruby
{ "resource": "" }
q8985
SycLink.Website.links_duplicate_on
train
def links_duplicate_on(attribute, separator) links.map do |link| link.send(attribute).split(separator).collect do |value| link.dup.update(Hash[attribute, value]) end end.flatten end
ruby
{ "resource": "" }
q8986
SycLink.Website.link_attribute_list
train
def link_attribute_list(attribute, separator = nil) links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort end
ruby
{ "resource": "" }
q8987
DCPU16.CPU.run
train
def run @started_at = Time.now max_cycles = 1 while true do if @cycle < max_cycles step else diff = Time.now - @started_at max_cycles = (diff * @clock_cycle) end end end
ruby
{ "resource": "" }
q8988
Imwukong.Base.wk_api_info
train
def wk_api_info(api_method='') api_method ||= '' fail 'Invalid wukong api' unless api_method == '' || api_method =~ WK_API_FORMAT if api_method.size > 0 m = api_method.to_s.match(/^wk_([a-zA-Z0-9]+)_(.+)/) method_group = m[1].singularize method_name = m[2] end apis = api_method.size > 0 ? API_LIST.select { |a| a[:method_group]==method_group && method_name==a[:method_name] } : API_LIST fail 'api not found' unless apis.present? apis.map do |api| method_group = api[:method_pluralize] ? api[:method_group].pluralize : api[:method_group] method_name = "wk_#{method_group}_#{api[:method_name]}" "#{method_name}, #{api_url(api)}, #{api[:args].inspect} " end end
ruby
{ "resource": "" }
q8989
Cornerstone.Post.update_counter_cache
train
def update_counter_cache self.discussion.reply_count = Post.where(:discussion_id => self.discussion.id) .count - 1 self.discussion.save end
ruby
{ "resource": "" }
q8990
Cornerstone.Post.anonymous_or_user_attr
train
def anonymous_or_user_attr(attr) unless self.user_id.nil? mthd = "user_#{attr.to_s}" # TODO: rails caching is messing this relationship up. # will .user work even if model name is something else. e.g. AdminUser ?? self.user.send(attr) else case attr when :cornerstone_name self.send(:name) when :cornerstone_email self.send(:email) end end end
ruby
{ "resource": "" }
q8991
Taxonifi::Export.OboNomenclature.export
train
def export() super f = new_output_file('obo_nomenclature.obo') # header f.puts 'format-version: 1.2' f.puts "date: #{@time}" f.puts 'saved-by: someone' f.puts 'auto-generated-by: Taxonifi' f.puts 'synonymtypedef: COMMONNAME "common name"' f.puts 'synonymtypedef: MISSPELLING "misspelling" EXACT' f.puts 'synonymtypedef: TAXONNAMEUSAGE "name with (author year)" NARROW' f.puts "default-namespace: #{@namespace}" f.puts "ontology: FIX-ME-taxonifi-ontology\n\n" # terms @name_collection.collection.each do |n| f.puts '[Term]' f.puts "id: #{id_string(n)}" f.puts "name: #{n.name}" f.puts "is_a: #{id_string(n.parent)} ! #{n.parent.name}" if n.parent f.puts "property_value: has_rank #{rank_string(n)}" f.puts end # typedefs f.puts "[Typedef]" f.puts "id: has_rank" f.puts "name: has taxonomic rank" f.puts "is_metadata_tag: true" true end
ruby
{ "resource": "" }
q8992
Templatr.Field.has_unique_name
train
def has_unique_name invalid = false if template invalid ||= template.common_fields.any? {|field| field.name.downcase == self.name.downcase && field != self } invalid ||= template.default_fields.any? {|field| field.name.downcase == self.name.downcase && field != self } else scope = self.class.common.where("LOWER(name) = LOWER(?)", self.name) scope = scope.where("id != ?", self.id) if persisted? invalid ||= scope.exists? end errors.add(:name, "has already been taken") if invalid end
ruby
{ "resource": "" }
q8993
Templatr.Field.disambiguate_fields
train
def disambiguate_fields if name_changed? # New, Updated fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name) fields.update_all(:disambiguate => fields.many?) end if name_was # Updated, Destroyed fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name_was) fields.update_all(:disambiguate => fields.many?) end end
ruby
{ "resource": "" }
q8994
FlexibleAccessibility.RouteProvider.app_routes_as_hash
train
def app_routes_as_hash Rails.application.routes.routes.each do |route| controller = route.defaults[:controller] next if controller.nil? key = controller.split('/').map(&:camelize).join('::') routes[key] ||= [] routes[key] << route.defaults[:action] end end
ruby
{ "resource": "" }
q8995
BcaStatement.Client.get_statement
train
def get_statement(start_date = '2016-08-29', end_date = '2016-09-01') return nil unless @access_token @timestamp = Time.now.iso8601(3) @start_date = start_date.to_s @end_date = end_date.to_s @path = "/banking/v3/corporates/" @relative_url = "#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}" begin response = RestClient.get("#{@base_url}#{@relative_url}", "Content-Type": 'application/json', "Authorization": "Bearer #{@access_token}", "Origin": @domain, "X-BCA-Key": @api_key, "X-BCA-Timestamp": @timestamp, "X-BCA-Signature": signature) elements = JSON.parse response.body statements = [] elements['Data'].each do |element| year = Date.parse(@start_date).strftime('%m').to_i.eql?(12) ? Date.parse(@start_date).strftime('%Y') : Date.parse(@end_date).strftime('%Y') date = element['TransactionDate'].eql?("PEND") ? element['TransactionDate'] : "#{element['TransactionDate']}/#{year}" attribute = { date: date, brance_code: element['BranchCode'], type: element['TransactionType'], amount: element['TransactionAmount'].to_f, name: element['TransactionName'], trailer: element['Trailer'] } statements << BcaStatement::Entities::Statement.new(attribute) end statements rescue RestClient::ExceptionWithResponse => err return nil end end
ruby
{ "resource": "" }
q8996
BcaStatement.Client.balance
train
def balance return nil unless @access_token begin @timestamp = Time.now.iso8601(3) @relative_url = "/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}" response = RestClient.get("#{@base_url}#{@relative_url}", "Content-Type": 'application/json', "Authorization": "Bearer #{@access_token}", "Origin": @domain, "X-BCA-Key": @api_key, "X-BCA-Timestamp": @timestamp, "X-BCA-Signature": signature) data = JSON.parse response.body if account_detail_success = data['AccountDetailDataSuccess'] detail = account_detail_success.first attribute = { account_number: detail['AccountNumber'], currency: detail['Currency'], balance: detail['Balance'].to_f, available_balance: detail['AvailableBalance'].to_f, float_amount: detail['FloatAmount'].to_f, hold_amount: detail['HoldAmount'].to_f, plafon: detail['Plafon'].to_f } BcaStatement::Entities::Balance.new(attribute) else return nil end rescue RestClient::ExceptionWithResponse => err return nil end end
ruby
{ "resource": "" }
q8997
SimpleGeocoder.Geocoder.geocode!
train
def geocode!(address, options = {}) response = call_geocoder_service(address, options) if response.is_a?(Net::HTTPOK) return JSON.parse response.body else raise ResponseError.new response end end
ruby
{ "resource": "" }
q8998
SimpleGeocoder.Geocoder.find_location
train
def find_location(address) result = geocode(address) if result['status'] == 'OK' return result['results'][0]['geometry']['location'] else latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/ if address =~ latlon_regexp location = $&.split(',').map {|e| e.to_f} return { "lat" => location[0], "lng" => location[1] } else return nil end end end
ruby
{ "resource": "" }
q8999
PSQL.Database.object
train
def object( object_name ) object = objects.find do |obj| obj[ 'name' ] == object_name end if !object raise "Database #{name} does not have an object named '#{object_name}'." end klass = PSQL.const_get object[ 'type' ].capitalize klass.new object[ 'name' ], name end
ruby
{ "resource": "" }