repository_name
stringlengths
7
56
func_path_in_repository
stringlengths
10
101
func_name
stringlengths
12
78
language
stringclasses
1 value
func_code_string
stringlengths
74
11.9k
func_documentation_string
stringlengths
3
8.03k
split_name
stringclasses
1 value
func_code_url
stringlengths
98
213
enclosing_scope
stringlengths
42
98.2k
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.roles
ruby
def roles return [] if get_roles.nil? x = [get_roles].flatten.map do |role| role.respond_to?(:to_sym) ? role.to_sym : role end x.first.kind_of?(Set) ? x.first.to_a : x end
query assigned roles
train
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L112-L118
module Implementation include Roles::Generic::RoleUtil def role_attribute strategy_class.roles_attribute_name end # set a single role def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) ...
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.find
ruby
def find(name, providers, version) providers = Array(providers) # Build up the requirements we have requirements = version.to_s.split(",").map do |v| Gem::Requirement.new(v.strip) end with_collection_lock do box_directory = @directory.join(dir_name(name)) if !box_...
Find a box in the collection with the given name and provider. @param [String] name Name of the box (logical name). @param [Array] providers Providers that the box implements. @param [String] version Version constraints to adhere to. Example: "~> 1.0" or "= 1.0, ~> 1.1" @return [Box] The box found, or `nil` if ...
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L272-L335
class BoxCollection TEMP_PREFIX = "vagrant-box-add-temp-".freeze VAGRANT_SLASH = "-VAGRANTSLASH-".freeze VAGRANT_COLON = "-VAGRANTCOLON-".freeze # The directory where the boxes in this collection are stored. # # A box collection matches a very specific folder structure that Vagrant # expe...
genaromadrid/email_checker
lib/email_checker/domain.rb
EmailChecker.Domain.mx_servers
ruby
def mx_servers return @mx_servers if @mx_servers @mx_servers = [] mx_records.each do |mx| @mx_servers.push(preference: mx.preference, address: mx.exchange.to_s) end @mx_servers end
The servers that this domian MX records point at. @return [Array<Hash>] Array of type { preference: 1, address: '127.0.0.1' }
train
https://github.com/genaromadrid/email_checker/blob/34cae07ddf5bb86efff030d062e420d5aa15486a/lib/email_checker/domain.rb#L67-L74
class Domain # @return [String] the provided domain name. attr_reader :domain # Returns a new instance of Domain # # @param domain [String] The domain name. # # @example EmailChecker::Domain.new('google.com') def initialize(domain) @domain = domain end # Checks if the ...
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.ensure_valid_checkid_request
ruby
def ensure_valid_checkid_request self.openid_request = checkid_request if !openid_request.is_a?(OpenID::Server::CheckIDRequest) redirect_to root_path, :alert => t(:identity_verification_request_invalid) elsif !allow_verification? flash[:notice] = logged_in? && !pape_requirements_met?(a...
Use this as before_filter for every CheckID request based action. Loads the current openid request and cancels if none can be found. The user has to log in, if he has not verified his ownership of the identifier, yet.
train
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L157-L168
class ServerController < BaseController # CSRF-protection must be skipped, because incoming # OpenID requests lack an authenticity token skip_before_filter :verify_authenticity_token # Error handling rescue_from OpenID::Server::ProtocolError, :with => :render_openid_error # Actions other than ...
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.InstanceMethods.get_bits_for
ruby
def get_bits_for(column_name, field) return nil if self[column_name].nil? only = self.class.only_mask_for column_name, field inc = self.class.increment_mask_for column_name, field (self[column_name] & only)/inc end
:nodoc:
train
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L236-L241
module InstanceMethods # Sets one or more bitfields to 0 within a column # # +reset_bitfield :column, :fields # # @example # user.reset_bitfield :column, :daily, :monthly # # @param [ Symbol ] column name of the column these fields are in # @param [ Symbol ] field(s) name o...
spikegrobstein/capnotify
lib/capnotify/component.rb
Capnotify.Component.render_content
ruby
def render_content(format) begin ERB.new( File.open( template_path_for(format) ).read, nil, '%<>' ).result(self.get_binding) rescue TemplateUndefined '' end end
FIXME: this should probably leverage Procs for rendering of different types, maybe? that would give a lot of power to a developer who wants a custom format for a plugin (eg XML or JSON) Render the content in the given format using the right built-in template. Returns the content as a string. In the event that...
train
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/component.rb#L52-L58
class Component class TemplateUndefined < StandardError; end attr_accessor :header, :name # the class(s) for this component (as a string) attr_accessor :css_class, :custom_css # a block that will configure this instance lazily attr_reader :builder attr_accessor :template_path, :render...
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.subscript_codeseparator
ruby
def subscript_codeseparator(separator_index) buf = [] process_separator_index = 0 chunks.each{|chunk| buf << chunk if process_separator_index == separator_index if chunk.ord == OP_CODESEPARATOR && process_separator_index < separator_index process_separator_index += 1 ...
Returns a script that deleted the script before the index specified by separator_index.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L462-L472
class Script include Bitcoin::Opcodes attr_accessor :chunks def initialize @chunks = [] end # generate P2PKH script def self.to_p2pkh(pubkey_hash) new << OP_DUP << OP_HASH160 << pubkey_hash << OP_EQUALVERIFY << OP_CHECKSIG end # generate P2WPKH script def self.to_p2...
sds/haml-lint
lib/haml_lint/configuration.rb
HamlLint.Configuration.ensure_linter_include_exclude_arrays_exist
ruby
def ensure_linter_include_exclude_arrays_exist @hash['linters'].each_key do |linter_name| %w[include exclude].each do |option| linter_config = @hash['linters'][linter_name] linter_config[option] = Array(linter_config[option]) end end end
Ensure `include` and `exclude` options for linters are arrays (since users can specify a single string glob pattern for convenience)
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/configuration.rb#L116-L123
class Configuration # Internal hash storing the configuration. attr_reader :hash # Creates a configuration from the given options hash. # # @param options [Hash] def initialize(options, file = nil) @hash = options @config_dir = file ? File.dirname(file) : nil resolve_require...
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/command.rb
VagrantVbguest.Command.execute
ruby
def execute options = { :_method => :run, :_rebootable => true, :auto_reboot => false } opts = OptionParser.new do |opts| opts.banner = "Usage: vagrant vbguest [vm-name] "\ "[--do start|rebuild|install] "\ "[--status] "\ ...
Runs the vbguest installer on the VMs that are represented by this environment.
train
https://github.com/dotless-de/vagrant-vbguest/blob/934fd22864c811c951c020cfcfc5c2ef9d79d5ef/lib/vagrant-vbguest/command.rb#L12-L74
class Command < Vagrant.plugin("2", :command) include VagrantPlugins::CommandUp::StartMixins include VagrantVbguest::Helpers::Rebootable # Runs the vbguest installer on the VMs that are represented # by this environment. # Show description when `vagrant list-commands` is triggered def self....
documentcloud/cloud-crowd
lib/cloud_crowd/action.rb
CloudCrowd.Action.`
ruby
def `(command) result = super(command) exit_code = $?.to_i raise Error::CommandFailed.new(result, exit_code) unless exit_code == 0 result end
Actions have a backticks command that raises a CommandFailed exception on failure, so that processing doesn't just blithely continue.
train
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/action.rb#L74-L79
class Action FILE_URL = /\Afile:\/\// attr_reader :input, :input_path, :file_name, :options, :work_directory # Initializing an Action sets up all of the read-only variables that # form the bulk of the API for action subclasses. (Paths to read from and # write to). It creates the +work_directory...
sandipransing/rails_tiny_mce
plugins/paperclip/shoulda_macros/paperclip.rb
Paperclip.Shoulda.stub_paperclip_s3
ruby
def stub_paperclip_s3(model, attachment, extension) definition = model.gsub(" ", "_").classify.constantize. attachment_definitions[attachment.to_sym] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path.gsub!(/:([^\/\.]+)/) do |match| "([^\/\.]+)" end ...
Stubs the HTTP PUT for an attachment using S3 storage. @example stub_paperclip_s3('user', 'avatar', 'png')
train
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L68-L82
module Shoulda include Matchers # This will test whether you have defined your attachment correctly by # checking for all the required fields exist after the definition of the # attachment. def should_have_attached_file name klass = self.name.gsub(/Test$/, '').constantize matcher = h...
barkerest/incline
lib/incline/user_manager.rb
Incline.UserManager.authenticate
ruby
def authenticate(email, password, client_ip) return nil unless Incline::EmailValidator.valid?(email) email = email.downcase # If an engine is registered for the email domain, then use it. engine = get_auth_engine(email) if engine return engine.authenticate(email, password, client_...
Creates a new user manager. The user manager itself takes no options, however options will be passed to any registered authentication engines when they are instantiated. The options can be used to pre-register engines and provide configuration for them. The engines will have specific configurations, but the UserM...
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/user_manager.rb#L81-L109
class UserManager < AuthEngineBase ## # Creates a new user manager. # # The user manager itself takes no options, however options will be passed to # any registered authentication engines when they are instantiated. # # The options can be used to pre-register engines and provide configura...
hashicorp/vagrant
lib/vagrant/environment.rb
Vagrant.Environment.host
ruby
def host return @host if defined?(@host) # Determine the host class to use. ":detect" is an old Vagrant config # that shouldn't be valid anymore, but we respect it here by assuming # its old behavior. No need to deprecate this because I thin it is # fairly harmless. host_klass = vag...
Returns the host object associated with this environment. @return [Class]
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L533-L564
class Environment # This is the current version that this version of Vagrant is # compatible with in the home directory. # # @return [String] CURRENT_SETUP_VERSION = "1.5" DEFAULT_LOCAL_DATA = ".vagrant" # The `cwd` that this environment represents attr_reader :cwd # The persist...
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.ClassMethods.increment_mask_for
ruby
def increment_mask_for column_name, *fields fields = bitfields if fields.empty? column = @@bitfields[column_name] raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil? fields.sum do |field_name| raise ArugmentError, "Unknown field: #{field_name} for column #{c...
Returns an "increment mask" for a list of fields +increment_mask_for :fields @example user.increment_mask_for :field @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) for the mask
train
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L103-L111
module ClassMethods # alias :reset_bitfields :reset_bitfield # Assign bitfields to a column # # +has_bit_field :column, :fields # # @example # class User < ActiveRecord::Base # has_bit_field :counter, :daily => 0..4, :weekly => 5..9, :monthly => 10..14 # end # ...
af83/desi
lib/desi/index_manager.rb
Desi.IndexManager.list
ruby
def list(pattern = '.*') pattern = Regexp.new(pattern || '.*') @outputter.puts "Indices from host #{@host} matching the pattern #{pattern.inspect}\n\n" if @verbose list = indices(pattern).sort list.each {|i| @outputter.puts i.inspect } if @verbose list end
Initializes a Desi::IndexManager instance @param [#to_hash] opts Hash of extra opts @option opts [#to_s] :host ('http://localhost:9200') Host to manage indices for @option opts [Boolean] :verbose (nil) Whether to output the actions' result ...
train
https://github.com/af83/desi/blob/30c51ce3b484765bd8911baf2fb83a85809cc81c/lib/desi/index_manager.rb#L100-L108
class IndexManager class Index attr_reader :name, :number_of_documents, :aliases, :state, :number_of_documents def initialize(name, state_data, status_data) @name = name @number_of_documents = status_data["docs"]["num_docs"] if status_data && status_data["docs"] @aliases = []...
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.load_line_stats
ruby
def load_line_stats(ids) if ids.is_a? Range if ids.first == '' range = ids.last else range = '%s..%s' % [ids.first, ids.last] end options = { :numstat => true, :timeout => false } output = @grit_repo.git.native :log, options, range commit_stats ...
Loads the line stats for the commits given by a set of commit IDs @param [Array<String>] ids The IDs of the commits to load line stats for @return [Hash<String, Array<Fixnum>] An array of two number (line additions and deletions) for each of the given commit IDs
train
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L65-L88
class Repository < Metior::Repository # Creates a new Git repository based on the given path # # This creates a new `Grit::Repo` instance to interface with the # repository. # # @param [String] path The file system path of the repository def initialize(path) super path @grit_...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.move_cursor
ruby
def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 en...
Move the cursor to specified row. The main window and the headers will be updated reflecting the displayed files and directories. The row number can be out of range of the current page.
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L151-L170
class Controller include Rfd::Commands attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip # :nodoc: def initialize @main = MainWindow.new @header_l = HeaderLeftWindow.new @header_r = HeaderRightW...
bdurand/json_record
lib/json_record/field_definition.rb
JsonRecord.FieldDefinition.default
ruby
def default if @default.nil? nil elsif @default.is_a?(Numeric) || @default.is_a?(Symbol) || @default.is_a?(TrueClass) || @default.is_a?(FalseClass) @default else @default.dup rescue @default end end
Define a field. Options should include :type with the class of the field. Other options available are :multivalued and :default. Get the default value.
train
https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/field_definition.rb#L24-L32
class FieldDefinition BOOLEAN_MAPPING = { true => true, 'true' => true, 'TRUE' => true, 'True' => true, 't' => true, 'T' => true, '1' => true, 1 => true, 1.0 => true, false => false, 'false' => false, 'FALSE' => false, 'False' => false, 'f' => false, 'F' => false, '0' => false, 0 => false, 0.0 => fals...
igrigorik/http-2
lib/http/2/connection.rb
HTTP2.Connection.connection_settings
ruby
def connection_settings(frame) connection_error unless frame[:type] == :settings && (frame[:stream]).zero? # Apply settings. # side = # local: previously sent and pended our settings should be effective # remote: just received peer settings should immediately be effective setti...
Update connection settings based on parameters set by the peer. @param frame [Hash]
train
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L528-L609
class Connection include FlowBuffer include Emitter include Error # Connection state (:new, :closed). attr_reader :state # Size of current connection flow control window (by default, set to # infinity, but is automatically updated on receipt of peer settings). attr_reader :local_wind...
SpontaneousCMS/cutaneous
lib/cutaneous/syntax.rb
Cutaneous.Syntax.token_map
ruby
def token_map @token_map ||= Hash[tags.map { |type, tags| [tags[0], [type, tags[0].count(?{), tags[1].length]] }] end
map the set of tags into a hash used by the parse routine that converts an opening tag into a list of: tag type, the number of opening braces in the tag and the length of the closing tag
train
https://github.com/SpontaneousCMS/cutaneous/blob/b0dffbd18b360a8d089d9822821f15c04cdc1b33/lib/cutaneous/syntax.rb#L35-L37
class Syntax attr_reader :tags def initialize(tag_definitions) @tags = tag_definitions end def is_dynamic?(text) !text.index(tag_start_pattern).nil? end def tag_start_pattern @tag_start_pattern ||= compile_start_pattern end def escaped_tag_pattern @escaped_t...
sumoheavy/jira-ruby
lib/jira/client.rb
JIRA.Client.post
ruby
def post(path, body = '', headers = {}) headers = { 'Content-Type' => 'application/json' }.merge(headers) request(:post, path, body, merge_default_headers(headers)) end
HTTP methods with a body
train
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/client.rb#L228-L231
class Client extend Forwardable # The OAuth::Consumer instance returned by the OauthClient # # The authenticated client instance returned by the respective client type # (Oauth, Basic) attr_accessor :consumer, :request_client, :http_debug, :cache # The configuration options for this clie...
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.create
ruby
def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_ses...
Force the collection to be created in the database. @example Force the collection to be created. collection.create @param [ Hash ] opts The options for the create operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L184-L199
class Collection extend Forwardable include Retryable # The capped option. # # @since 2.1.0 CAPPED = 'capped'.freeze # The ns field constant. # # @since 2.1.0 NS = 'ns'.freeze # @return [ Mongo::Database ] The database the collection resides in. attr_reader :database...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.color_floodfill
ruby
def color_floodfill(x, y, fill) target = pixel_color(x, y) color_flood_fill(target, fill, x, y, Magick::FloodfillMethod) end
Set all pixels that have the same color as the pixel at x,y and are neighbors to the fill color
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L771-L774
class Image include Comparable alias affinity remap # Provide an alternate version of Draw#annotate, for folks who # want to find it in this class. def annotate(draw, width, height, x, y, text, &block) check_destroyed draw.annotate(self, width, height, x, y, text, &block) self ...
trishume/pro
lib/pro/commands.rb
Pro.Commands.status
ruby
def status() max_name = @index.map {|repo| repo.name.length}.max + 1 @index.each do |r| next unless Dir.exists?(r.path) status = repo_status(r.path) next if status.empty? name = format("%-#{max_name}s",r.name).bold puts "#{name} > #{status}" end end
prints a status list showing repos with unpushed commits or uncommitted changes
train
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L88-L97
class Commands EMPTY_MESSAGE = 'empty'.green UNCOMMITTED_MESSAGE = 'uncommitted'.red UNTRACKED_MESSAGE = 'untracked'.magenta UNPUSHED_MESSAGE = 'unpushed'.blue JOIN_STRING = ' + ' def initialize(index) @index = index end # Fuzzy search for a git repository by name # Returns...
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.undir_name
ruby
def undir_name(name) name = name.dup name.gsub!(VAGRANT_COLON, ":") name.gsub!(VAGRANT_SLASH, "/") name end
Returns the directory name for the box cleaned up
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L394-L399
class BoxCollection TEMP_PREFIX = "vagrant-box-add-temp-".freeze VAGRANT_SLASH = "-VAGRANTSLASH-".freeze VAGRANT_COLON = "-VAGRANTCOLON-".freeze # The directory where the boxes in this collection are stored. # # A box collection matches a very specific folder structure that Vagrant # expe...
PierreRambaud/gemirro
lib/gemirro/source.rb
Gemirro.Source.fetch_versions
ruby
def fetch_versions Utils.logger.info( "Fetching #{Configuration.versions_file} on #{@name} (#{@host})" ) Http.get(host + '/' + Configuration.versions_file).body end
@param [String] name @param [String] host @param [Array] gems Fetches a list of all the available Gems and their versions. @return [String]
train
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/source.rb#L32-L38
class Source attr_reader :name, :host, :gems ## # @param [String] name # @param [String] host # @param [Array] gems # def initialize(name, host, gems = []) @name = name.downcase.gsub(/\s+/, '_') @host = host.chomp('/') @gems = gems end ## # Fetches a list of...
shadowbq/snort-thresholds
lib/threshold/thresholds.rb
Threshold.Thresholds.reject
ruby
def reject(&blk) if block_given? Thresholds.new(@thresholds.reject(&blk)) else Thresholds.new(@thresholds.reject) end end
Returns a new Threshold Object
train
https://github.com/shadowbq/snort-thresholds/blob/e3e9d1b10c2460846e1779fda67e8bec0422f53e/lib/threshold/thresholds.rb#L119-L125
class Thresholds extend Forwardable attr_accessor :file, :readonly def_delegators :@thresholds, :<<, :length, :push, :pop, :first, :last, :<=>, :==, :clear, :[], :[]=, :shift, :unshift, :each, :sort!, :shuffle!, :collect!, :map!, :reject!, :delete_if, :select!, :keep_if, :index, :include? def init...
mailgun/mailgun-ruby
lib/railgun/mailer.rb
Railgun.Mailer.deliver!
ruby
def deliver!(mail) mg_message = Railgun.transform_for_mailgun(mail) response = @mg_client.send_message(@domain, mg_message) if response.code == 200 then mg_id = response.to_h['id'] mail.message_id = mg_id end response end
Initialize the Railgun mailer. @param [Hash] config Hash of config values, typically from `app_config.action_mailer.mailgun_config`
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/railgun/mailer.rb#L42-L51
class Mailer # List of the headers that will be ignored when copying headers from `mail.header_fields` IGNORED_HEADERS = %w[ to from subject ] # [Hash] config -> # Requires *at least* `api_key` and `domain` keys. attr_accessor :config, :domain, :settings # Initialize the Railgun mailer. ...
senchalabs/jsduck
lib/jsduck/tag/overrides.rb
JsDuck::Tag.Overrides.format
ruby
def format(m, formatter) m[:overrides].each do |o| label = o[:owner] + "." + o[:name] o[:link] = formatter.link(o[:owner], o[:name], label, m[:tagname], m[:static]) end end
Generate HTML links from :overrides data.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag/overrides.rb#L17-L22
class Overrides < Tag def initialize @tagname = :overrides @html_position = POS_OVERRIDES end # Generate HTML links from :overrides data. def to_html(m) "<p>Overrides: " + m[:overrides].map {|o| o[:link] }.join(", ") + "</p>" end end
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.matte_replace
ruby
def matte_replace(x, y) f = copy f.opacity = OpaqueOpacity unless f.alpha? target = f.pixel_color(x, y) f.transparent(target) end
Make transparent all pixels that are the same color as the pixel at (x, y).
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L917-L922
class Image include Comparable alias affinity remap # Provide an alternate version of Draw#annotate, for folks who # want to find it in this class. def annotate(draw, width, height, x, y, text, &block) check_destroyed draw.annotate(self, width, height, x, y, text, &block) self ...
mojombo/chronic
lib/chronic/repeaters/repeater_day.rb
Chronic.RepeaterDay.next
ruby
def next(pointer) super unless @current_day_start @current_day_start = Chronic.time_class.local(@now.year, @now.month, @now.day) end direction = pointer == :future ? 1 : -1 @current_day_start += direction * DAY_SECONDS Span.new(@current_day_start, @current_day_start + DAY_...
(24 * 60 * 60)
train
https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/repeaters/repeater_day.rb#L10-L21
class RepeaterDay < Repeater #:nodoc: DAY_SECONDS = 86_400 # (24 * 60 * 60) def initialize(type, width = nil, options = {}) super @current_day_start = nil end def this(pointer = :future) super case pointer when :future day_begin = Chronic.construct(@now.year, ...
projectcypress/health-data-standards
lib/hqmf-parser/2.0/population_criteria.rb
HQMF2.PopulationCriteria.handle_type
ruby
def handle_type(id_generator) if @type != 'AGGREGATE' # Generate the precondition for this population if @preconditions.length > 1 || (@preconditions.length == 1 && @preconditions[0].conjunction != conjunction_code) @preconditions = [Precondition.new(id_generator.next_id, conj...
Create a new population criteria from the supplied HQMF entry @param [Nokogiri::XML::Element] the HQMF entry Handles how the code should deal with the type definition (aggregate vs non-aggregate)
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/population_criteria.rb#L27-L39
class PopulationCriteria include HQMF2::Utilities attr_reader :preconditions, :id, :hqmf_id, :title, :aggregator, :comments # need to do this to allow for setting the type to OBSERV for attr_accessor :type # Create a new population criteria from the supplied HQMF entry # @param [Nokogiri::XML...
kontena/k8s-client
lib/k8s/client.rb
K8s.Client.get_resources
ruby
def get_resources(resources) # prefetch api resources, skip missing APIs resource_apis = apis(resources.map(&:apiVersion), prefetch_resources: true, skip_missing: true) # map each resource to excon request options, or nil if resource is not (yet) defined requests = resources.zip(resource_apis)....
Returns nils for any resources that do not exist. This includes custom resources that were not yet defined. @param resources [Array<K8s::Resource>] @return [Array<K8s::Resource, nil>] matching resources array 1:1
train
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/client.rb#L232-L253
class Client # @param config [Phraos::Kube::Config] # @param namespace [String] @see #initialize # @param options [Hash] @see Transport.config # @return [K8s::Client] def self.config(config, namespace: nil, **options) new( Transport.config(config, **options), namespace: names...
rlisowski/open_flash_chart_2_plugin
lib/ofc2.rb
OFC2.OWJSON.method_missing
ruby
def method_missing(method_id, *arguments) a = arguments[0] if arguments and arguments.size > 0 method = method_id.to_s if method =~ /^(.*)(=)$/ self.instance_variable_set("@#{$1.gsub('_','__')}", a) elsif method =~ /^(set_)(.*)$/ self.instance_variable_set("@#{$2.gsub('_','__')}"...
if You use rails older that 2.3 probably you have to uncomment that method and add "config.gem 'json'" in config/enviroment.rb file otherwise to_json method will not work propertly # You can pass options to to_json method, but remember that they have no effects!!! # argument 'options' is for rails compabilit...
train
https://github.com/rlisowski/open_flash_chart_2_plugin/blob/2ee7f7d3b81ee9c6773705d3b919df8688972361/lib/ofc2.rb#L27-L39
module OWJSON # return a hash of instance values def to_hash self.instance_values end alias :to_h :to_hash # if You use rails older that 2.3 probably you have to uncomment that method and add "config.gem 'json'" in config/enviroment.rb file # otherwise to_json method will not work pro...
hashicorp/vault-ruby
lib/vault/persistent.rb
Vault.PersistentHTTP.start
ruby
def start http http.set_debug_output @debug_output if @debug_output http.open_timeout = @open_timeout if @open_timeout http.start socket = http.instance_variable_get :@socket if socket then # for fakeweb @socket_options.each do |option| socket.io.setsockopt(*option) end en...
Starts the Net::HTTP +connection+
train
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/persistent.rb#L694-L707
class PersistentHTTP ## # The beginning of Time EPOCH = Time.at 0 # :nodoc: ## # Is OpenSSL available? This test works with autoload HAVE_OPENSSL = defined? OpenSSL::SSL # :nodoc: ## # The default connection pool size is 1/4 the allowed open files. DEFAULT_POOL_SIZE = 16 ## # The version o...
alexreisner/geocoder
lib/geocoder/calculations.rb
Geocoder.Calculations.coordinates_present?
ruby
def coordinates_present?(*args) args.each do |a| # note that Float::NAN != Float::NAN # still, this could probably be improved: return false if (!a.is_a?(Numeric) or a.to_s == "NaN") end true end
Returns true if all given arguments are valid latitude/longitude values.
train
https://github.com/alexreisner/geocoder/blob/e087dc2759264ee6f307b926bb2de4ec2406859e/lib/geocoder/calculations.rb#L44-L51
module Calculations extend self ## # Compass point names, listed clockwise starting at North. # # If you want bearings named using more, fewer, or different points # override Geocoder::Calculations.COMPASS_POINTS with your own array. # COMPASS_POINTS = %w[N NE E SE S SW W NW] ## ...
hashicorp/vagrant
lib/vagrant/machine.rb
Vagrant.Machine.reload
ruby
def reload old_id = @id @id = nil if @data_dir # Read the id file from the data directory if it exists as the # ID for the pre-existing physical representation of this machine. id_file = @data_dir.join("id") id_content = id_file.read.strip if id_file.file? if !...
This reloads the ID of the underlying machine.
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L394-L414
class Machine # The box that is backing this machine. # # @return [Box] attr_accessor :box # Configuration for the machine. # # @return [Object] attr_accessor :config # Directory where machine-specific data can be stored. # # @return [Pathname] attr_reader :data_dir ...
tetradice/neuroncheck
lib/neuroncheck/declaration.rb
NeuronCheckSystem.DeclarationMethods.__neuroncheck_ndecl_main_with_block
ruby
def __neuroncheck_ndecl_main_with_block(block, declared_caller_locations) # 宣言ブロック実行用のコンテキストを作成 context = NeuronCheckSystem::DeclarationContext.new # 宣言ブロックの内容を実行 context.instance_eval(&block) # 呼び出し場所を記憶 context.declaration.declared_caller_locations = declared_caller_locat...
ndeclの通常記法
train
https://github.com/tetradice/neuroncheck/blob/0505dedd8f7a8018a3891f7519f7861e1c787014/lib/neuroncheck/declaration.rb#L49-L61
module DeclarationMethods # 宣言を実行 def ndecl(*expecteds, &block) # 未初期化の場合、NeuronCheck用の初期化を自動実行 unless @__neuron_check_initialized then NeuronCheckSystem.initialize_module_for_neuron_check(self) end # メイン処理実行 __neuroncheck_ndecl_main(expecteds, block, caller(1, 1)) e...
thumblemonks/riot
lib/riot/assertion_macros/kind_of.rb
Riot.KindOfMacro.evaluate
ruby
def evaluate(actual, expected) if actual.kind_of?(expected) pass new_message.is_a_kind_of(expected) else fail expected_message.kind_of(expected).not(actual.class) end end
(see Riot::AssertionMacro#evaluate) @param [Class] expected the expected class of actual
train
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/assertion_macros/kind_of.rb#L15-L21
class KindOfMacro < AssertionMacro register :kind_of # (see Riot::AssertionMacro#evaluate) # @param [Class] expected the expected class of actual # (see Riot::AssertionMacro#devaluate) # @param [Class] expected the unexpected class of actual def devaluate(actual, expected) if actu...
NCSU-Libraries/quick_search
app/controllers/quick_search/appstats_controller.rb
QuickSearch.AppstatsController.data_sessions_overview
ruby
def data_sessions_overview onCampus = params[:onCampus] ? params[:onCampus].to_i : 0 offCampus = params[:offCampus] ? params[:offCampus].to_i : 0 isMobile = params[:isMobile] ? params[:isMobile].to_i : 0 notMobile = params[:notMobile] ? params[:notMobile].to_i : 0 filterCase = (2**3)*onCam...
In order to obtain all filter cases, an integer corresponding to the following truth table is formed: rowNumber onCampus offCampus isMobile notMobile | filters 0 0 0 0 0 | Neither filter applied (default) 1 0 0 0 1 ...
train
https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/appstats_controller.rb#L133-L164
class AppstatsController < ApplicationController include Auth before_action :auth, :get_dates, :days_in_sample def data_general_statistics @result = [] clicks = Event.where(@range).where(:action => 'click').group(:created_at_string).order("created_at_string ASC").count(:created_at_string) ...
mongodb/mongoid
lib/mongoid/factory.rb
Mongoid.Factory.from_db
ruby
def from_db(klass, attributes = nil, criteria = nil, selected_fields = nil) if criteria selected_fields ||= criteria.options[:fields] end type = (attributes || {})[TYPE] if type.blank? obj = klass.instantiate(attributes, selected_fields) if criteria && criteria.associatio...
Builds a new +Document+ from the supplied attributes loaded from the database. If a criteria object is given, it is used in two ways: 1. If the criteria has a list of fields specified via #only, only those fields are populated in the returned document. 2. If the criteria has a referencing association (i.e., th...
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/factory.rb#L52-L80
module Factory extend self TYPE = "_type".freeze # Builds a new +Document+ from the supplied attributes. # # @example Build the document. # Mongoid::Factory.build(Person, { "name" => "Durran" }) # # @param [ Class ] klass The class to instantiate from if _type is not present. #...
Falkor/falkorlib
lib/falkorlib/git/flow.rb
FalkorLib.GitFlow.start
ruby
def start(type, name, path = Dir.pwd, optional_args = '') command(name, type, 'start', path, optional_args) end
git flow {feature, hotfix, release, support} start <name>
train
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/flow.rb#L169-L171
module GitFlow module_function ## OLD version ## Check if git-flow is initialized # def init?(path = Dir.pwd) # res = FalkorLib::Git.init?(path) # Dir.chdir(path) do # gf_check = `git config --get-regexp 'gitflow*'` # res &= ! gf_check.empty? # end ...
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.parse_options
ruby
def parse_options(parser_configuration = {}) raise_on_invalid_option = parser_configuration.has_key?(:raise_on_invalid_option) ? parser_configuration[:raise_on_invalid_option] : true parse_base_options = parser_configuration.has_key?(:parse_base_options) ? parser_configuration[:parse_base_options] : true ...
Parse generic action options for all decendant actions @return [OptionParser] for use by decendant actions
train
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L47-L136
class BaseAction # main configuration hash attr_reader :configuration # options hash, read from configuration hash attr_reader :options # args as passed on command line attr_reader :args # filename to template for rendering attr_accessor :template # filename to write output ...
david942j/seccomp-tools
lib/seccomp-tools/disasm/disasm.rb
SeccompTools.Disasm.disasm
ruby
def disasm(raw, arch: nil) codes = to_bpf(raw, arch) contexts = Array.new(codes.size) { Set.new } contexts[0].add(Context.new) # all we care is if A is exactly one of data[*] dis = codes.zip(contexts).map do |code, ctxs| ctxs.each do |ctx| code.branch(ctx) do |pc, c| ...
Disassemble bpf codes. @param [String] raw The raw bpf bytes. @param [Symbol] arch Architecture.
train
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/disasm/disasm.rb#L17-L35
module Disasm module_function # Disassemble bpf codes. # @param [String] raw # The raw bpf bytes. # @param [Symbol] arch # Architecture. # Convert raw bpf string to array of {BPF}. # @param [String] raw # @param [Symbol] arch # @return [Array<BPF>] def to_bpf(raw, ar...
murb/workbook
lib/workbook/column.rb
Workbook.Column.column_type
ruby
def column_type return @column_type if defined?(@column_type) ind = self.index table[1..500].each do |row| if row[ind] and row[ind].cell_type cel_column_type = row[ind].cell_type if !defined?(@column_type) or @column_type.nil? @column_type = cel_column_type ...
character limit Returns column type, either :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :date, :binary, :boolean
train
https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/column.rb#L17-L33
class Column attr_accessor :limit, :width #character limit def initialize(table=nil, options={}) self.table = table options.each{ |k,v| self.public_send("#{k}=",v) } end # Returns column type, either :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :date, :binary, :bo...
motion-kit/motion-kit
lib/motion-kit-osx/helpers/nsmenu_helpers.rb
MotionKit.MenuLayout.add
ruby
def add(title_or_item, element_id=nil, options={}, &block) if element_id.is_a?(NSDictionary) options = element_id element_id = nil end if title_or_item.is_a?(NSMenuItem) item = title_or_item menu = nil retval = item elsif title_or_item.is_a?(NSMenu) ...
override 'add'; menus are just a horse of a different color.
train
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit-osx/helpers/nsmenu_helpers.rb#L36-L78
class MenuLayout < TreeLayout # A more sensible name for the menu that is created. def menu self.view end # platform specific default root view def default_root # child WindowLayout classes can return *their* NSView subclass from self.nsview_class menu_class = self.class.target...
bradleymarques/carbon_date
lib/carbon_date/date.rb
CarbonDate.Date.set_date
ruby
def set_date(year, month, day) raise invalid_date if (year.nil? || year == 0 || !((1..12).include? month)) begin ::Date.new(year, month, day) rescue ArgumentError raise invalid_date end @year = year.to_i @month = month @day = day end
An atomic function to set the date component (year, month and day) Raises +ArgumentError+ if invalid date
train
https://github.com/bradleymarques/carbon_date/blob/778b2a58e0d0ae554d36fb92c356a6d9fc6415b4/lib/carbon_date/date.rb#L88-L98
class Date # The class-wide Formatter to use to turn CarbonDate::Dates into human-readable strings @formatter = CarbonDate::StandardFormatter.new class << self # Used to get and set the CarbonDate::Date.formatter attr_accessor :formatter end ## # The precisions available PRE...
wvanbergen/request-log-analyzer
lib/request_log_analyzer/file_format.rb
RequestLogAnalyzer::FileFormat.Base.parse_line
ruby
def parse_line(line, &warning_handler) line_definitions.each do |_lt, definition| match = definition.matches(line, &warning_handler) return match if match end nil end
Parses a line by trying to parse it using every line definition in this file format
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/file_format.rb#L297-L304
class Base extend RequestLogAnalyzer::ClassLevelInheritableAttributes inheritable_attributes :line_definer, :report_definer attr_reader :line_definitions, :report_trackers #################################################################################### # CLASS METHODS for format definition ...
jaymcgavren/zyps
lib/zyps.rb
Zyps.Behavior.copy
ruby
def copy copy = self.clone #Currently, we overwrite everything anyway, but we may add some clonable attributes later. #Make a deep copy of all actions. copy.instance_eval {@actions = []} self.actions.each {|action| copy.add_action(action.copy)} #Make a deep copy of all conditions. copy.instance_...
Make a deep copy.
train
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps.rb#L552-L561
class Behavior #An array of Condition subclasses. #Condition#select(actor, targets) will be called on each. attr_accessor :conditions #An array of Action subclasses. #Action#start(actor, targets) and action.do(actor, targets) will be called on each when all conditions are true. #Action#stop(actor, targets)...
state-machines/state_machines
lib/state_machines/state.rb
StateMachines.State.context_methods
ruby
def context_methods @context.instance_methods.inject({}) do |methods, name| methods.merge(name.to_sym => @context.instance_method(name)) end end
The list of methods that have been defined in this state's context
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state.rb#L208-L212
class State # The state machine for which this state is defined attr_reader :machine # The unique identifier for the state used in event and callback definitions attr_reader :name # The fully-qualified identifier for the state, scoped by the machine's # namespace attr_reader :qualified_...
ideonetwork/lato-blog
app/models/lato_blog/category/serializer_helpers.rb
LatoBlog.Category::SerializerHelpers.serialize_base
ruby
def serialize_base serialized = {} # set basic info serialized[:id] = id serialized[:title] = title serialized[:meta_language] = meta_language serialized[:meta_permalink] = meta_permalink # return serialized category serialized end
This function serializes a basic version of the category.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/serializer_helpers.rb#L28-L39
module Category::SerializerHelpers # This function serializes a complete version of the category. def serialize serialized = {} # set basic info serialized[:id] = id serialized[:title] = title serialized[:meta_language] = meta_language serialized[:meta_permalink] = meta_p...
senchalabs/jsduck
lib/jsduck/tag/member_tag.rb
JsDuck::Tag.MemberTag.member_params
ruby
def member_params(params) ps = Array(params).map do |p| p[:optional] ? "[#{p[:name]}]" : p[:name] end.join(", ") "( <span class='pre'>#{ps}</span> )" end
Creates HTML listing of parameters. When called with nil, creates empty params list. A helper method for use in #to_html.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag/member_tag.rb#L121-L127
class MemberTag < Tag # Defines a class member type and specifies various settings. For # example: # # { # :title => "Events", # :position => MEMBER_POS_EVENT, # # The following are optional # :toolbar_title => "Events", # :icon => File.dirname(__...
nafu/aws_sns_manager
lib/aws_sns_manager/client.rb
AwsSnsManager.Client.normal_notification
ruby
def normal_notification(text, options = {}) base = { aps: { alert: { title: nil, subtitle: nil, body: text }, sound: options.delete(:sound), badge: 1, 'mutable-content': 1, 'content-available': 1 } ...
rubocop:disable Metrics/MethodLength
train
https://github.com/nafu/aws_sns_manager/blob/9ec6ce1799d1195108e95a1efa2dd21437220a3e/lib/aws_sns_manager/client.rb#L50-L65
class Client attr_accessor :client attr_accessor :arn def initialize(options = {}) super() @client = Aws::SNS::Client.new(options) end def send(text = nil, options = {}, env = :prod, type = :normal) message = message(text, options, env, type).to_json response = publish_r...
lostisland/faraday
lib/faraday/utils.rb
Faraday.Utils.URI
ruby
def URI(url) # rubocop:disable Naming/MethodName if url.respond_to?(:host) url elsif url.respond_to?(:to_str) default_uri_parser.call(url) else raise ArgumentError, 'bad argument (expected URI object or URI string)' end end
Normalize URI() behavior across Ruby versions url - A String or URI. Returns a parsed URI.
train
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/utils.rb#L55-L63
module Utils module_function def build_query(params) FlatParamsEncoder.encode(params) end def build_nested_query(params) NestedParamsEncoder.encode(params) end ESCAPE_RE = /[^a-zA-Z0-9 .~_-]/.freeze def escape(str) str.to_s.gsub(ESCAPE_RE) do |match| '%' + mat...
murb/workbook
lib/workbook/row.rb
Workbook.Row.push
ruby
def push(cell) cell = Workbook::Cell.new(cell, {row:self}) unless cell.class == Workbook::Cell super(cell) end
Add cell @param [Workbook::Cell, Numeric,String,Time,Date,TrueClass,FalseClass,NilClass] cell or value to add
train
https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/row.rb#L67-L70
class Row < Array include Workbook::Modules::Cache alias_method :compare_without_header, :<=> attr_accessor :placeholder # The placeholder attribute is used in compares (corresponds to newly created or removed lines (depending which side you're on) attr_accessor :format # Initialize a new ro...
oleganza/btcruby
lib/btcruby/open_assets/asset_processor.rb
BTC.AssetProcessor.verify_asset_transaction
ruby
def verify_asset_transaction(asset_transaction) raise ArgumentError, "Asset Transaction is missing" if !asset_transaction # Perform a depth-first scanning. # When completed, we'll only have transactions that have all previous txs fully verified. atx_stack = [ asset_transaction ] i = 0 ...
Scans backwards and validates every AssetTransaction on the way. Does not verify Bitcoin transactions (assumes amounts and scripts are already validated). Updates verified flags on the asset transaction. Returns `true` if asset transaction is verified succesfully. Returns `false` otherwise.
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_processor.rb#L27-L91
class AssetProcessor # AssetProcessorSource instance that provides transactions. attr_accessor :source # Network to use for encoding AssetIDs. Default is `Network.default`. attr_accessor :network def initialize(source: nil, network: nil) raise ArgumentError, "Source is missing." if !sourc...
oleganza/btcruby
lib/btcruby/data.rb
BTC.Data.ensure_ascii_compatible_encoding
ruby
def ensure_ascii_compatible_encoding(string, options = nil) if string.encoding.ascii_compatible? string else string.encode(Encoding::UTF_8, options || {:invalid => :replace, :undef => :replace}) end end
Returns string as-is if it is ASCII-compatible (that is, if you are interested in 7-bit characters exposed as #bytes). If it is not, attempts to transcode to UTF8 replacing invalid characters if there are any. If options are not specified, uses safe default that replaces unknown characters with standard character. ...
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/data.rb#L91-L97
module Data extend self HEX_PACK_CODE = "H*".freeze BYTE_PACK_CODE = "C*".freeze # Generates a secure random number of a given length def random_data(length = 32) SecureRandom.random_bytes(length) end # Converts hexadecimal string to a binary data string. def data_from_hex...
rjurado01/rapidoc
lib/rapidoc/resource_doc.rb
Rapidoc.ResourceDoc.generate_info
ruby
def generate_info( routes_info ) if routes_info extractor = get_controller_extractor @description = extractor.get_resource_info['description'] if extractor @actions_doc = get_actions_doc( routes_info, extractor ) # template need that description will be an array @descript...
Create description and actions_doc
train
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/resource_doc.rb#L36-L45
class ResourceDoc attr_reader :name, :description, :controller_file, :actions_doc ## # @param resource_name [String] resource name # @param routes_doc [RoutesDoc] routes documentation # def initialize( resource_name, routes_actions_info ) @name = resource_name.to_s.split('/').last ...
stripe/stripe-ruby
lib/stripe/stripe_object.rb
Stripe.StripeObject.empty_values
ruby
def empty_values(obj) values = case obj when Hash then obj when StripeObject then obj.instance_variable_get(:@values) else raise ArgumentError, "#empty_values got unexpected object type: #{obj.class.name}" end values.each_...
Returns a hash of empty values for all the values that are in the given StripeObject.
train
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_object.rb#L556-L567
class StripeObject include Enumerable @@permanent_attributes = Set.new([:id]) # The default :id method is deprecated and isn't useful to us undef :id if method_defined?(:id) # Sets the given parameter name to one which is known to be an additive # object. # # Additive objects are su...
CocoaPods/Xcodeproj
lib/xcodeproj/workspace.rb
Xcodeproj.Workspace.xcworkspace_element_start_xml
ruby
def xcworkspace_element_start_xml(depth, elem) attributes = case elem.name when 'Group' %w(location name) when 'FileRef' %w(location) end contents = "<#{elem.name}" indent = ' ' * depth attribute...
@param [Integer] depth The depth of the element in the tree @param [REXML::Document::Element] elem The XML element to format. @return [String] The Xcode-specific XML formatting of an element start
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L251-L262
class Workspace # @return [REXML::Document] the parsed XML model for the workspace contents attr_reader :document # @return [Hash<String => String>] a mapping from scheme name to project full path # containing the scheme attr_reader :schemes # @return [Array<FileReference>] the paths...
zed-0xff/zpng
lib/zpng/color.rb
ZPNG.Color.to_depth
ruby
def to_depth new_depth return self if depth == new_depth color = Color.new :depth => new_depth if new_depth > self.depth %w'r g b a'.each do |part| color.send("#{part}=", (2**new_depth-1)/(2**depth-1)*self.send(part)) end else # new_depth < self.depth %...
change bit depth, return new Color
train
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L159-L174
class Color attr_accessor :r, :g, :b attr_reader :a attr_accessor :depth include DeepCopyable def initialize *a h = a.last.is_a?(Hash) ? a.pop : {} @r,@g,@b,@a = *a # default sample depth for r,g,b and alpha = 8 bits @depth = h[:depth] || 8 # default...
moneta-rb/moneta
lib/moneta/expires.rb
Moneta.Expires.delete
ruby
def delete(key, options = {}) return super if options.include?(:raw) value, expires = super value if !expires || Time.now <= Time.at(expires) end
(see Proxy#delete)
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/expires.rb#L44-L48
class Expires < Proxy include ExpiresSupport # @param [Moneta store] adapter The underlying store # @param [Hash] options # @option options [String] :expires Default expiration time def initialize(adapter, options = {}) raise 'Store already supports feature :expires' if adapter.supports?(:e...
bmuller/ankusa
lib/ankusa/cassandra_storage.rb
Ankusa.CassandraStorage.incr_doc_count
ruby
def incr_doc_count(klass, count) klass = klass.to_s doc_count = @cassandra.get(:totals, klass, "doc_count").values.last.to_i doc_count += count @cassandra.insert(:totals, klass, {"doc_count" => doc_count.to_s}) @klass_doc_counts[klass.to_sym] = doc_count end
Increment total document count for a given class by 'count'
train
https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L159-L165
class CassandraStorage attr_reader :cassandra # # Necessary to set max classes since current implementation of ruby # cassandra client doesn't support table scans. Using crufty get_range # method at the moment. # def initialize(host='127.0.0.1', port=9160, keyspace = 'ankusa', max_classes...
paxtonhare/marklogic-ruby-driver
lib/marklogic/collection.rb
MarkLogic.Collection.from_criteria
ruby
def from_criteria(criteria) queries = [] criteria.each do |k, v| name, operator, index_type, value = nil query_options = {} if (v.is_a?(Hash)) name = k.to_s query_options.merge!(v.delete(:options) || {}) sub_queries = [] v.each do |kk, vv| ...
Builds a MarkLogic Query from Mongo Style Criteria @param [Hash] criteria The Criteria to use when searching @example Build a query from criteria # Query on age == 3 collection.from_criteria({ 'age' => { '$eq' => 3 } }) # Query on age < 3 collection.from_criteria({ 'age' => { '$lt' => 3 } }) ...
train
https://github.com/paxtonhare/marklogic-ruby-driver/blob/76c3f2c2da7b8266cdbe786b7f3e910e0983eb9b/lib/marklogic/collection.rb#L174-L218
class Collection attr_accessor :collection attr_reader :database alias_method :name, :collection def initialize(name, database) @collection = name @database = database @operators = %w{GT LT GE LE EQ NE ASC DESC} end def count MarkLogic::Cursor.new(self).count end...
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.store_config
ruby
def store_config(filepath, hash, options = {}) content = "# " + File.basename(filepath) + "\n" content += "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated\n" if options[:header] options[:header].split("\n").each { |line| content += "# #{line}" } end content += ha...
Store the Hash object as a Yaml file Supported options: :header [string]: additional info to place in the header of the (stored) file :no_interaction [boolean]: do not interact
train
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L289-L307
module Common module_function ################################## ### Default printing functions ### ################################## # Print a text in bold def bold(str) (COLOR == true) ? Term::ANSIColor.bold(str) : str end # Print a text in green def green(str) (C...
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.relation_names
ruby
def relation_names(inclusions) inclusions.is_a?(Hash) ? inclusions.keys : Array.wrap(inclusions) end
Since the inclusions can be a hash, symbol, or array of symbols, this is provided as a convenience to parse out the names. @example Get the association names. document.relation_names(:include => [ :addresses ]) @param [ Hash, Symbol, Array<Symbol> ] inclusions The inclusions. @return [ Array<Symbol> ] The nam...
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L147-L149
module Serializable extend ActiveSupport::Concern # We need to redefine where the JSON configuration is getting defined, # similar to +ActiveRecord+. included do undef_method :include_root_in_json delegate :include_root_in_json, to: ::Mongoid end # Gets the document as a serializ...
litaio/lita
lib/lita/default_configuration.rb
Lita.DefaultConfiguration.handlers_config
ruby
def handlers_config handlers = registry.handlers root.config :handlers do handlers.each do |handler| if handler.configuration_builder.children? combine(handler.namespace, handler.configuration_builder) end end end end
Builds config.handlers
train
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/default_configuration.rb#L54-L64
class DefaultConfiguration # Valid levels for Lita's logger. LOG_LEVELS = %w[debug info warn error fatal].freeze # A {Registry} to extract configuration for plugins from. # @return [Registry] The registry. attr_reader :registry # The top-level {ConfigurationBuilder} attribute. # @return ...
hashicorp/vagrant
lib/vagrant/environment.rb
Vagrant.Environment.batch
ruby
def batch(parallel=true) parallel = false if ENV["VAGRANT_NO_PARALLEL"] @batch_lock.synchronize do BatchAction.new(parallel).tap do |b| # Yield it so that the caller can setup actions yield b # And run it! b.run end end end
This creates a new batch action, yielding it, and then running it once the block is called. This handles the case where batch actions are disabled by the VAGRANT_NO_PARALLEL environmental variable.
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L272-L284
class Environment # This is the current version that this version of Vagrant is # compatible with in the home directory. # # @return [String] CURRENT_SETUP_VERSION = "1.5" DEFAULT_LOCAL_DATA = ".vagrant" # The `cwd` that this environment represents attr_reader :cwd # The persist...
GeorgeKaraszi/ActiveRecordExtended
lib/active_record_extended/utilities.rb
ActiveRecordExtended.Utilities.to_arel_sql
ruby
def to_arel_sql(value) case value when Arel::Node, Arel::Nodes::SqlLiteral, nil value when ActiveRecord::Relation Arel.sql(value.spawn.to_sql) else Arel.sql(value.respond_to?(:to_sql) ? value.to_sql : value.to_s) end end
Converts a potential subquery into a compatible Arel SQL node. Note: We convert relations to SQL to maintain compatibility with Rails 5.[0/1]. Only Rails 5.2+ maintains bound attributes in Arel, so its better to be safe then sorry. When we drop support for Rails 5.[0/1], we then can then drop the '.to_sql' convers...
train
https://github.com/GeorgeKaraszi/ActiveRecordExtended/blob/aca74eebb64b9957a2c8765bef6e43c7d5736fd8/lib/active_record_extended/utilities.rb#L140-L149
module Utilities A_TO_Z_KEYS = ("a".."z").to_a.freeze # We need to ensure we can flatten nested ActiveRecord::Relations # that might have been nested due to the (splat)*args parameters # # Note: calling `Array.flatten[!]/1` will actually remove all AR relations from the array. # def flatt...
nestor-custodio/automodel-sqlserver
lib/automodel/schema_inspector.rb
Automodel.SchemaInspector.foreign_keys
ruby
def foreign_keys(table_name) table_name = table_name.to_s @foreign_keys ||= {} @foreign_keys[table_name] ||= begin if @registration[:foreign_keys].present? @registration[:foreign_keys].call(@connection, table_name) else begin @connection.foreign_keys(ta...
Returns a list of foreign keys for the given table. If a matching Automodel::SchemaInspector registration is found for the connection's adapter, and that registration specified a `:foreign_keys` Proc, the Proc is called. Otherwise, the standard connection `#foreign_keys` is attempted. If that call to ``#foreign_key...
train
https://github.com/nestor-custodio/automodel-sqlserver/blob/7269224752274f59113ccf8267fc49316062ae22/lib/automodel/schema_inspector.rb#L151-L188
class SchemaInspector ## rubocop:disable all ## Class-Instance variable: `known_adapters` is a Hash of adapters registered via ## {Automodel::SchemaInspector.register_adapter}. ## @known_adapters = {} def self.known_adapters; @known_adapters; end def known_adapters; self.class.known_adapt...
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.create_volume_set
ruby
def create_volume_set(name, domain = nil, comment = nil, setmembers = nil) begin @volume_set.create_volume_set(name, domain, comment, setmembers) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
Creates a new volume set ==== Attributes * name - the volume set to create type name: String * domain: the domain where the set lives type domain: String * comment: the comment for the vv set type comment: String * setmembers: the vv(s) to add to the set, the existence of the vv(s) will not be ...
train
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1850-L1857
class Client def initialize(api_url,debug:false, secure: false, timeout: nil, suppress_ssl_warnings: false, app_type: 'ruby_SDK_3par', log_file_path: nil) unless api_url.is_a?(String) raise Hpe3parSdk::HPE3PARException.new(nil, "'api_url' parameter i...
kmuto/review
lib/epubmaker/producer.rb
EPUBMaker.Producer.complement
ruby
def complement @config['htmlext'] ||= 'html' defaults = ReVIEW::Configure.new.merge( 'language' => 'ja', 'date' => Time.now.strftime('%Y-%m-%d'), 'modified' => Time.now.utc.strftime('%Y-%02m-%02dT%02H:%02M:%02SZ'), 'isbn' => nil, 'toclevel' => 2, 'stylesheet' ...
Complement parameters.
train
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L234-L338
class Producer # Array of content objects. attr_accessor :contents # Parameter hash. attr_accessor :config # Message resource object. attr_reader :res # Take YAML +file+ and return parameter hash. def self.load(file) if file.nil? || !File.exist?(file) raise "Can't open #...
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_cpg
ruby
def delete_cpg(name) begin @cpg.delete_cpg(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
Deletes a CPG. ==== Attributes * name - The name of the CPG type name: String ==== Raises * Hpe3parSdk::HPE3PARException Error with code: 15 message: CPG does not exist * Hpe3parSdk::HTTPForbidden - IN_USE - The CPG Cannot be removed because it's in use. * Hpe3parSdk::HTTPForbidden ...
train
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L2435-L2442
class Client def initialize(api_url,debug:false, secure: false, timeout: nil, suppress_ssl_warnings: false, app_type: 'ruby_SDK_3par', log_file_path: nil) unless api_url.is_a?(String) raise Hpe3parSdk::HPE3PARException.new(nil, "'api_url' parameter i...
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.drop
ruby
def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: sessio...
Drop the collection. Will also drop all indexes associated with the collection. @note An error returned if the collection doesn't exist is suppressed. @example Drop the collection. collection.drop @param [ Hash ] opts The options for the drop operation. @option options [ Session ] :session The session to us...
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L216-L228
class Collection extend Forwardable include Retryable # The capped option. # # @since 2.1.0 CAPPED = 'capped'.freeze # The ns field constant. # # @since 2.1.0 NS = 'ns'.freeze # @return [ Mongo::Database ] The database the collection resides in. attr_reader :database...
appdrones/page_record
lib/page_record/attributes.rb
PageRecord.Attributes.read_attribute
ruby
def read_attribute(attribute) if block_given? element = yield else element = send("#{attribute}?") end tag = element.tag_name input_field?(tag) ? element.value : element.text end
Searches the record for the specified attribute and returns the text content. This method is called when you access an attribute of a record @return [String] the text content of the specified attribute @raise [AttributeNotFound] when the attribute is not found in the record
train
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/attributes.rb#L27-L35
module Attributes ## # Searches the record for the specified attribute and returns # the {http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Result Capybara Result}. # This method is called when you access an attribute with a `?` of a record # # @return [Capybara::Result] the text co...
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.<<
ruby
def <<(commit) return self if key? commit.id if @additions.nil? && empty? && commit.line_stats? @additions = commit.additions @deletions = commit.deletions elsif !@additions.nil? @additions += commit.additions @deletions += commit.deletions end super e...
Creates a new collection with the given commits @param [Array<Commit>] commits The commits that should be initially inserted into the collection Adds a commit to this collection @param [Commit] commit The commit to add to this collection @return [CommitCollection] The collection itself
train
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L47-L59
class CommitCollection < Collection # Creates a new collection with the given commits # # @param [Array<Commit>] commits The commits that should be initially # inserted into the collection def initialize(commits = [], range = nil) @additions = nil @deletions = nil @range ...
lostisland/faraday
lib/faraday/request.rb
Faraday.Request.url
ruby
def url(path, params = nil) if path.respond_to? :query if (query = path.query) path = path.dup path.query = nil end else anchor_index = path.index('#') path = path.slice(0, anchor_index) unless anchor_index.nil? path, query = path.split('?', 2) ...
Update path and params. @param path [URI, String] @param params [Hash, nil] @return [void]
train
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/request.rb#L86-L100
class Request < Struct.new(:method, :path, :params, :headers, :body, :options) # rubocop:enable Style/StructInheritance extend MiddlewareRegistry register_middleware File.expand_path('request', __dir__), url_encoded: [:UrlEncoded, 'url_encoded'], multipart...
sds/haml-lint
lib/haml_lint/tree/node.rb
HamlLint::Tree.Node.line_numbers
ruby
def line_numbers return (line..line) unless @value && text end_line = line + lines.count end_line = nontrivial_end_line if line == end_line (line..end_line) end
The line numbers that are contained within the node. @api public @return [Range]
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/node.rb#L104-L111
class Node include Enumerable attr_accessor :children, :parent attr_reader :line, :type # Creates a node wrapping the given {Haml::Parser::ParseNode} struct. # # @param document [HamlLint::Document] Haml document that created this node # @param parse_node [Haml::Parser::ParseNode] parse ...
hashicorp/vault-ruby
lib/vault/api/sys/mount.rb
Vault.Sys.remount
ruby
def remount(from, to) client.post("/v1/sys/remount", JSON.fast_generate( from: from, to: to, )) return true end
Change the name of the mount @example Vault.sys.remount("pg", "postgres") #=> true @param [String] from the origin mount path @param [String] to the new mount path @return [true]
train
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/mount.rb#L95-L101
class Sys < Request # List all mounts in the vault. # # @example # Vault.sys.mounts #=> { :secret => #<struct Vault::Mount type="generic", description="generic secret storage"> } # # @return [Hash<Symbol, Mount>] def mounts json = client.get("/v1/sys/mounts") json = json[:dat...
PierreRambaud/gemirro
lib/gemirro/server.rb
Gemirro.Server.update_indexes
ruby
def update_indexes indexer = Gemirro::Indexer.new(Utils.configuration.destination) indexer.only_origin = true indexer.ui = ::Gem::SilentUI.new Utils.logger.info('Generating indexes') indexer.update_index indexer.updated_gems.each do |gem| Utils.cache.flush_key(File.basename(...
Update indexes files @return [Indexer]
train
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L164-L176
class Server < Sinatra::Base # rubocop:disable Metrics/LineLength URI_REGEXP = /^(.*)-(\d+(?:\.\d+){1,4}.*?)(?:-(x86-(?:(?:mswin|mingw)(?:32|64)).*?|java))?\.(gem(?:spec\.rz)?)$/ GEMSPEC_TYPE = 'gemspec.rz'.freeze GEM_TYPE = 'gem'.freeze access_logger = Logger.new(Utils.configuration.server.acces...
litaio/lita
lib/lita/template.rb
Lita.Template.context_binding
ruby
def context_binding(variables) context = TemplateEvaluationContext.new helpers.each { |helper| context.extend(helper) } variables.each do |k, v| context.instance_variable_set("@#{k}", v) end context.__get_binding end
Create an empty object to use as the ERB context and set any provided variables in it.
train
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/template.rb#L56-L66
class Template # A clean room object to use as the binding for ERB rendering. # @api private class TemplateEvaluationContext # Returns the evaluation context's binding. # @return [Binding] The binding. def __get_binding binding end end class << self # Initial...
dagrz/nba_stats
lib/nba_stats/stats/box_score_usage.rb
NbaStats.BoxScoreUsage.box_score_usage
ruby
def box_score_usage( game_id, range_type=0, start_period=0, end_period=0, start_range=0, end_range=0 ) NbaStats::Resources::BoxScoreUsage.new( get(BOX_SCORE_USAGE_PATH, { :GameID => game_id, :RangeType => range_type, ...
Calls the boxscoreusage API and returns a BoxScoreUsage resource. @param game_id [String] @param range_type [Integer] @param start_period [Integer] @param end_period [Integer] @param start_range [Integer] @param end_range [Integer] @return [NbaStats::Resources::BoxScoreUsage]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/box_score_usage.rb#L19-L37
module BoxScoreUsage # The path of the boxscoreusage API BOX_SCORE_USAGE_PATH = '/stats/boxscoreusage' # Calls the boxscoreusage API and returns a BoxScoreUsage resource. # # @param game_id [String] # @param range_type [Integer] # @param start_period [Integer] # @param end_period [...
moneta-rb/moneta
lib/moneta/stack.rb
Moneta.Stack.store
ruby
def store(key, value, options = {}) @stack.each {|s| s.store(key, value, options) } value end
(see Proxy#store)
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/stack.rb#L58-L61
class Stack include Defaults # @api private class DSL def initialize(stack, &block) @stack = stack instance_eval(&block) end # @api public def add(store = nil, &block) raise ArgumentError, 'Only argument or block allowed' if store && block @stack <...
kristianmandrup/geo_units
lib/geo_units/converter.rb
GeoUnits.Converter.to_lat
ruby
def to_lat deg, format = :dms, dp = 0 deg = deg.normalize_lat _lat = Dms.to_dms deg, format, dp _lat == '' ? '' : _lat[1..-1] + (deg<0 ? 'S' : 'N') # knock off initial '0' for lat! end
Convert numeric degrees to deg/min/sec latitude (suffixed with N/S) @param {Number} deg: Degrees @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d @returns {String} Deg/min/seconds
train
https://github.com/kristianmandrup/geo_units/blob/ddee241b826af36bc96dad3dd01258f56a730cd9/lib/geo_units/converter.rb#L14-L18
module Converter autoload_modules :Normalizer, :Dms, :Units include Normalizer # Convert numeric degrees to deg/min/sec latitude (suffixed with N/S) # # @param {Number} deg: Degrees # @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' # @param {Number} [dp=0|2|4]: No o...
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_doserate
ruby
def add_doserate(value, item) if !@current_doserate || value != @current_doserate @current_doserate = value DICOM::Element.new('300A,0115', value, :parent => item) end end
Adds a Dose Rate Set element to a Control Point Item. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [String, NilClass] value the doserate attribute @param [DICOM::Item] item the DICOM control point item in which to...
train
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L414-L419
class Plan < Record attr_accessor :current_gantry attr_accessor :current_collimator attr_accessor :current_couch_angle attr_accessor :current_couch_pedestal attr_accessor :current_couch_lateral attr_accessor :current_couch_longitudinal attr_accessor :current_couch_vertical # Converts...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_objects
ruby
def get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) requests = objectIDs.map do |objectID| req = { :indexName => name, :objectID => objectID.to_s } req[:attributesToRet...
Get a list of objects from this index @param objectIDs the array of unique identifier of the objects to retrieve @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by "," @param request_options contains extra parameters to send w...
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L257-L265
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "d...
chicks/sugarcrm
lib/sugarcrm/base.rb
SugarCRM.Base.save
ruby
def save(opts={}) options = { :validate => true }.merge(opts) return false if !(new_record? || changed?) if options[:validate] return false if !valid? end begin save!(options) rescue return false end true end
Saves the current object, checks that required fields are present. returns true or false
train
https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/base.rb#L190-L202
module SugarCRM; class Base # Unset all of the instance methods we don't need. instance_methods.each { |m| undef_method m unless m =~ /(^__|^send$|^object_id$|^define_method$|^class$|^nil.$|^methods$|^instance_of.$|^respond_to)/ } # Tracks if we have extended our class with attribute methods yet. class_attri...
ideonetwork/lato-blog
lib/lato_blog/interfaces/categories.rb
LatoBlog.Interface::Categories.blog__clean_category_parents
ruby
def blog__clean_category_parents category_parents = LatoBlog::CategoryParent.all category_parents.map { |cp| cp.destroy if cp.categories.empty? } end
This function cleans all old category parents without any child.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L28-L31
module Interface::Categories # This function create the default category if it not exists. def blog__create_default_category category_parent = LatoBlog::CategoryParent.find_by(meta_default: true) return if category_parent category_parent = LatoBlog::CategoryParent.new(meta_default: true) ...
mongodb/mongoid
lib/mongoid/serializable.rb
Mongoid.Serializable.serialize_attribute
ruby
def serialize_attribute(attrs, name, names, options) if relations.key?(name) value = send(name) attrs[name] = value ? value.serializable_hash(options) : nil elsif names.include?(name) && !fields.key?(name) attrs[name] = read_raw_attribute(name) elsif !attribute_missing?(name) ...
Serialize a single attribute. Handles associations, fields, and dynamic attributes. @api private @example Serialize the attribute. document.serialize_attribute({}, "id" , [ "id" ]) @param [ Hash ] attrs The attributes. @param [ String ] name The attribute name. @param [ Array<String> ] names The names of al...
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L100-L109
module Serializable extend ActiveSupport::Concern # We need to redefine where the JSON configuration is getting defined, # similar to +ActiveRecord+. included do undef_method :include_root_in_json delegate :include_root_in_json, to: ::Mongoid end # Gets the document as a serializ...
stevedowney/rails_view_helpers
app/helpers/rails_view_helpers/html_helper.rb
RailsViewHelpers.HtmlHelper.td_bln
ruby
def td_bln(*args) options = canonicalize_options(args.extract_options!) options = ensure_class(options, 'c') content_tag(:td, bln(*args), options) end
Same as +bln+ but wrapped in a TD and centered (w/rail_view_helper.css) @example td_bln(true) #=> <td class="c">&#10004;</td> @return [String]
train
https://github.com/stevedowney/rails_view_helpers/blob/715c7daca9434c763b777be25b1069ecc50df287/app/helpers/rails_view_helpers/html_helper.rb#L48-L53
module HtmlHelper # Includes controller and action name as data attributes. # # @example # body_tag() #=> <body data-action='index' data-controller='home'> # # body_tag(id: 'my-id', class: 'my-class') #=> <body class="my-class" data-action="index" data-controller="home" id="my-id"> # ...
colstrom/ezmq
lib/ezmq/subscribe.rb
EZMQ.Subscriber.receive
ruby
def receive(**options) message = '' @socket.recv_string message message = message.match(/^(?<topic>[^\ ]*)\ (?<body>.*)/m) decoded = (options[:decode] || @decode).call message['body'] if block_given? yield decoded, message['topic'] else [decoded, message['topic']] ...
Creates a new Subscriber socket. @note The default behaviour is to output and messages received to STDOUT. @param [:bind, :connect] mode (:connect) a mode for the socket. @param [Hash] options optional parameters. @option options [String] topic a topic to subscribe to. @see EZMQ::Socket EZMQ::Socket for optional...
train
https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/subscribe.rb#L36-L48
class Subscriber < EZMQ::Socket # Creates a new Subscriber socket. # # @note The default behaviour is to output and messages received to STDOUT. # # @param [:bind, :connect] mode (:connect) a mode for the socket. # @param [Hash] options optional parameters. # @option options [String] topic...
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/decoder.rb
Pocketsphinx.Decoder.decode_raw
ruby
def decode_raw(audio_file, max_samples = 2048) start_utterance FFI::MemoryPointer.new(:int16, max_samples) do |buffer| while data = audio_file.read(max_samples * 2) buffer.write_string(data) process_raw(buffer, data.length / 2) end end end_utterance end
Decode a raw audio stream as a single utterance. No headers are recognized in this files. The configuration parameters samprate and input_endian are used to determine the sampling rate and endianness of the stream, respectively. Audio is always assumed to be 16-bit signed PCM. @param [IO] audio_file The raw aud...
train
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L71-L82
class Decoder require 'delegate' include API::CallHelpers class Hypothesis < SimpleDelegator attr_accessor :path_score attr_accessor :posterior_prob def initialize(string, path_score, posterior_prob = nil) @path_score = path_score @posterior_prob = posterior_prob ...
etewiah/property_web_builder
app/controllers/pwb/import/translations_controller.rb
Pwb.Import::TranslationsController.multiple
ruby
def multiple I18n::Backend::ActiveRecord::Translation.import(params[:file]) return render json: { "success": true }, status: :ok, head: :no_content # redirect_to root_url, notice: "I18n::Backend::ActiveRecord::Translations imported." end
http://localhost:3000/import/translations/multiple
train
https://github.com/etewiah/property_web_builder/blob/fba4e6d4ffa7bc1f4d3b50dfa5a6a9fbfee23f21/app/controllers/pwb/import/translations_controller.rb#L5-L11
class Import::TranslationsController < ApplicationApiController # http://localhost:3000/import/translations/multiple end
nylas/nylas-ruby
lib/nylas/api.rb
Nylas.API.revoke
ruby
def revoke(access_token) response = client.as(access_token).post(path: "/oauth/revoke") response.code == 200 && response.empty? end
Revokes access to the Nylas API for the given access token @return [Boolean]
train
https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/api.rb#L97-L100
class API attr_accessor :client extend Forwardable def_delegators :client, :execute, :get, :post, :put, :delete, :app_id include Logging # @param client [HttpClient] Http Client to use for retrieving data # @param app_id [String] Your application id from the Nylas Dashboard # @param app_...
dagrz/nba_stats
lib/nba_stats/stats/scoreboard.rb
NbaStats.Scoreboard.scoreboard
ruby
def scoreboard( game_date=Date.today, day_offset=0, league_id=NbaStats::Constants::LEAGUE_ID_NBA ) NbaStats::Resources::Scoreboard.new( get(SCOREBOARD_PATH, { :LeagueID => league_id, :GameDate => game_date.strftime('%m-%d-%Y'), :DayOf...
Calls the scoreboard API and returns a Scoreboard resource. @param game_date [Date] @param day_offset [Integer] @param league_id [String] @return [NbaStats::Resources::Scoreboard]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/scoreboard.rb#L17-L29
module Scoreboard # The path of the scoreboard API SCOREBOARD_PATH = '/stats/scoreboard' # Calls the scoreboard API and returns a Scoreboard resource. # # @param game_date [Date] # @param day_offset [Integer] # @param league_id [String] # @return [NbaStats::Resources::Scoreboard] ...
mrakobeze/vrtk
src/vrtk/applets/version_applet.rb
VRTK::Applets.VersionApplet.run_parse
ruby
def run_parse obj = { 'name' => VRTK::NAME, 'version' => VRTK::VERSION, 'codename' => VRTK::CODENAME, 'ffmpeg' => ffmpeg_version, 'magick' => magick_version, 'license' => VRTK::LICENSE } puts JSON.pretty_unparse obj end
noinspection RubyStringKeysInHashInspection,RubyResolve
train
https://github.com/mrakobeze/vrtk/blob/444052951949e3faab01f6292345dcd0a789f005/src/vrtk/applets/version_applet.rb#L34-L45
class VersionApplet < BaseApplet include VRTK::Utils def init_options @pa = false OptionParser.new do |opts| opts.on('-p', '--parsable', 'Generate parsable version output') do |v| @pa = v end end end def run if @pa run_parse else run_human end end # noinspection R...
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.url_prefix=
ruby
def url_prefix=(url, encoder = nil) uri = @url_prefix = Utils.URI(url) self.path_prefix = uri.path params.merge_query(uri.query, encoder) uri.query = nil with_uri_credentials(uri) do |user, password| basic_auth user, password uri.user = uri.password = nil end en...
Parses the given URL with URI and stores the individual components in this connection. These components serve as defaults for requests made by this connection. @param url [String, URI] @param encoder [Object] @example conn = Faraday::Connection.new { ... } conn.url_prefix = "https://sushi.com/api" conn...
train
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L420-L431
class Connection # A Set of allowed HTTP verbs. METHODS = Set.new %i[get post put delete head patch options trace connect] # @return [Hash] URI query unencoded key/value pairs. attr_reader :params # @return [Hash] unencoded HTTP header key/value pairs. attr_reader :headers # @return [St...
SecureBrain/ruby_apk
lib/android/manifest.rb
Android.Manifest.label
ruby
def label(lang=nil) label = @doc.elements['/manifest/application'].attributes['label'] if label.nil? # application element has no label attributes. # so looking for activites that has label attribute. activities = @doc.elements['/manifest/application'].find{|e| e.name == 'activity' &...
application label @param [String] lang language code like 'ja', 'cn', ... @return [String] application label string(if resouce is provided), or label resource id @return [nil] when label is not found @since 0.5.1
train
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/manifest.rb#L221-L237
class Manifest APPLICATION_TAG = '/manifest/application' # <activity>, <service>, <receiver> or <provider> element in <application> element of the manifest file. class Component # component types TYPES = ['service', 'activity', 'receiver', 'provider'] # the element is valid Component e...
agios/simple_form-dojo
lib/simple_form-dojo/dojo_props_methods.rb
SimpleFormDojo.DojoPropsMethods.get_and_merge_dojo_props!
ruby
def get_and_merge_dojo_props! add_dojo_options_to_dojo_props if object.id.present? add_dojo_compliant_id else input_html_options["id"] = nil #let dojo generate internal id end input_html_options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(@dojo_p...
Retrieves and merges all dojo_props
train
https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/dojo_props_methods.rb#L5-L13
module DojoPropsMethods ## # Retrieves and merges all dojo_props private ## # Retrieves dojo props from :dojo_html => {} options def add_dojo_options_to_dojo_props @dojo_props ||= {} @dojo_props.merge!(html_options_for(:dojo, [])) end def tag_id index = nil id =...
zhimin/rwebspec
lib/rwebspec-webdriver/web_browser.rb
RWebSpec.WebBrowser.submit
ruby
def submit(buttonName = nil) if (buttonName.nil?) then buttons.each { |button| next if button.type != 'submit' button.click return } else click_button_with_name(buttonName) end end
submit first submit button
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-webdriver/web_browser.rb#L590-L600
class WebBrowser include ElementLocator attr_accessor :context def initialize(base_url = nil, existing_browser = nil, options = {}) default_options = {:speed => "zippy", :visible => true, :highlight_colour => 'yellow', :close_others => true } ...