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
dropofwill/rtasklib
lib/rtasklib/taskrc.rb
Rtasklib.Taskrc.mappable_to_model
ruby
def mappable_to_model rc_file rc_file.map! { |l| line_to_tuple(l) }.compact! taskrc = Hash[rc_file] hash_to_model(taskrc) end
Converts a .taskrc file path into a Hash that can be converted into a TaskrcModel object @param rc_file [String,Pathname] a valid pathname to a .taskrc file @return [Models::TaskrcModel] the instance variable config @api private
train
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/taskrc.rb#L69-L73
class Taskrc attr_accessor :config # Generate a dynamic Virtus model, with the attributes defined by the input # # @param rc [Hash, Pathname] either a hash of attribute value pairs # or a Pathname to the raw taskrc file. # @raise [TypeError] if rc is not of type Hash, String, or Pathname ...
bradleymarques/carbon_date
lib/carbon_date/standard_formatter.rb
CarbonDate.StandardFormatter.millennium
ruby
def millennium(date) m = ((date.year.abs.to_i / 1000) + 1).ordinalize + ' millennium' return [m, BCE_SUFFIX].join(' ') if (date.year <= -1) m end
Formats a CarbonDate::Date with millennium precision Returns: A human-readable string representing the Date
train
https://github.com/bradleymarques/carbon_date/blob/778b2a58e0d0ae554d36fb92c356a6d9fc6415b4/lib/carbon_date/standard_formatter.rb#L84-L88
class StandardFormatter < Formatter # Suffix to use for Before Common Era dates (quite often BCE or BC) BCE_SUFFIX = 'BCE' # Collection of strings denoting month names for this Formatter MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'Nove...
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.write_uleb128
ruby
def write_uleb128(value, data: nil, stream: nil) raise ArgumentError, "Integer must be present" if !value buf = encode_uleb128(value) data << buf if data stream.write(buf) if stream buf end
Writes an unsigned integer encoded in LEB128 to a data buffer or a stream. Returns LEB128-encoded binary string.
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L280-L286
module WireFormat extend self # Reads varint from data or stream. # Either data or stream must be present (and only one of them). # Optional offset is useful when reading from data. # Returns [value, length] where value is a decoded integer value and length is number of bytes read (including offs...
dicom/rtp-connect
lib/rtp-connect/control_point.rb
RTP.ControlPoint.dcm_collimator
ruby
def dcm_collimator(axis, coeff, nr) mode = self.send("field_#{axis}_mode") if mode && !mode.empty? target = self else target = @parent end target.send("collimator_#{axis}#{nr}").to_f * 10 * coeff end
Converts the collimator attribute to proper DICOM format. @param [Symbol] axis a representation for the axis of interest (x or y) @param [Integer] coeff a coeffecient (of -1 or 1) which the attribute is multiplied with @param [Integer] nr collimator side/index (1 or 2) @return [Float] the DICOM-formatted collimato...
train
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/control_point.rb#L585-L593
class ControlPoint < Record # The number of attributes not having their own variable for this record (200 - 2). NR_SURPLUS_ATTRIBUTES = 198 # The Record which this instance belongs to. attr_accessor :parent # The MLC shape record (if any) that belongs to this ControlPoint. attr_reader :mlc_s...
kontena/kontena
cli/lib/kontena/client.rb
Kontena.Client.delete
ruby
def delete(path, body = nil, params = {}, headers = {}, auth = true) request(http_method: :delete, path: path, body: body, query: params, headers: headers, auth: auth) end
Delete request @param [String] path @param [Hash,String] body @param [Hash] params @param [Hash] headers @return [Hash]
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L243-L245
class Client CLIENT_ID = ENV['KONTENA_CLIENT_ID'] || '15faec8a7a9b4f1e8b7daebb1307f1d8'.freeze CLIENT_SECRET = ENV['KONTENA_CLIENT_SECRET'] || 'fb8942ae00da4c7b8d5a1898effc742f'.freeze CONTENT_URLENCODED = 'application/x-www-form-urlencoded'.freeze CONTENT_JSON = 'application/json'.fre...
igrigorik/http-2
lib/http/2/connection.rb
HTTP2.Connection.encode_headers
ruby
def encode_headers(frame) payload = frame[:payload] payload = @compressor.encode(payload) unless payload.is_a? Buffer frames = [] while payload.bytesize > 0 cont = frame.dup cont[:type] = :continuation cont[:flags] = [] cont[:payload] = payload.slice!(0, @remote...
Encode headers payload and update connection compressor state. @param frame [Hash] @return [Array of Frame]
train
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L636-L662
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...
cdarne/triton
lib/triton/messenger.rb
Triton.Messenger.remove_listener
ruby
def remove_listener(listener) type = listener.type if listeners.has_key? type listeners[type].delete(listener) listeners.delete(type) if listeners[type].empty? end end
Unregister the given block. It won't be call then went an event is emitted.
train
https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L36-L42
module Messenger extend self # This make Messenger behave like a singleton def listeners # this makes @listeners to be auto-initialized and accessed read-only @listeners ||= Hash.new end # Register the given block to be called when the events of type +type+ will be emitted. # if +once+, th...
zed-0xff/zpng
lib/zpng/image.rb
ZPNG.Image.crop!
ruby
def crop! params decode_all_scanlines x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width] raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 } # adjust crop sizes if they greater than image sizes h = self.height-y if (y+h) > self.heigh...
modifies this image
train
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L430-L455
class Image attr_accessor :chunks, :scanlines, :imagedata, :extradata, :format, :verbose # now only for (limited) BMP support attr_accessor :color_class include DeepCopyable alias :clone :deep_copy alias :dup :deep_copy include BMP::Reader PNG_HDR = "\x89PNG\x0d\x0a\x1a\x0a".forc...
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.in_use?
ruby
def in_use?(index) results = [] index.each do |entry| box_data = entry.extra_data["box"] next if !box_data # If all the data matches, record it if box_data["name"] == self.name && box_data["provider"] == self.provider.to_s && box_data["version"] == self.v...
Checks if this box is in use according to the given machine index and returns the entries that appear to be using the box. The entries returned, if any, are not tested for validity with {MachineIndex::Entry#valid?}, so the caller should do that if the caller cares. @param [MachineIndex] index @return [Array<Mac...
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L100-L116
class Box include Comparable # Number of seconds to wait between checks for box updates BOX_UPDATE_CHECK_INTERVAL = 3600 # The box name. This is the logical name used when adding the box. # # @return [String] attr_reader :name # This is the provider that this box is built for. #...
david942j/seccomp-tools
lib/seccomp-tools/util.rb
SeccompTools.Util.supported_archs
ruby
def supported_archs @supported_archs ||= Dir.glob(File.join(__dir__, 'consts', '*.rb')) .map { |f| File.basename(f, '.rb').to_sym } .sort end
Get currently supported architectures. @return [Array<Symbol>] Architectures.
train
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/util.rb#L9-L13
module Util module_function # Get currently supported architectures. # @return [Array<Symbol>] # Architectures. # Detect system architecture. # @return [Symbol] def system_arch case RbConfig::CONFIG['host_cpu'] when /x86_64/ then :amd64 when /i386/ then :i386 e...
ideonetwork/lato-blog
app/models/lato_blog/post.rb
LatoBlog.Post.check_lato_blog_post_parent
ruby
def check_lato_blog_post_parent post_parent = LatoBlog::PostParent.find_by(id: lato_blog_post_parent_id) if !post_parent errors.add('Post parent', 'not exist for the post') throw :abort return end same_language_post = post_parent.posts.find_by(meta_language: meta_languag...
This function check that the post parent exist and has not others post for the same language.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post.rb#L89-L103
class Post < ApplicationRecord include Post::EntityHelpers include Post::SerializerHelpers # Validations: validates :title, presence: true, length: { maximum: 250 } validates :meta_permalink, presence: true, uniqueness: true, length: { maximum: 250 } validates :meta_status, presence: true,...
chef/mixlib-shellout
lib/mixlib/shellout.rb
Mixlib.ShellOut.gid
ruby
def gid return group.kind_of?(Integer) ? group : Etc.getgrnam(group.to_s).gid if group return Etc.getpwuid(uid).gid if using_login? nil end
The gid that the subprocess will switch to. If the group attribute is given as a group name, it is converted to a gid by Etc.getgrnam TODO migrate to shellout/unix.rb
train
https://github.com/chef/mixlib-shellout/blob/35f1d3636974838cd623c65f18b861fa2d16b777/lib/mixlib/shellout.rb#L219-L223
class ShellOut READ_WAIT_TIME = 0.01 READ_SIZE = 4096 DEFAULT_READ_TIMEOUT = 600 if RUBY_PLATFORM =~ /mswin|mingw32|windows/ require "mixlib/shellout/windows" include ShellOut::Windows else require "mixlib/shellout/unix" include ShellOut::Unix end # User the comma...
tbuehlmann/ponder
lib/ponder/channel_list.rb
Ponder.ChannelList.remove_user
ruby
def remove_user(nick) @mutex.synchronize do channels = Set.new @channels.each do |channel| if channel.remove_user(nick) channels << channel end end channels end end
Removes a User from all Channels from the ChannelList. Returning a Set of Channels in which the User was.
train
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L30-L42
class ChannelList attr_reader :channels def initialize @channels = Set.new @mutex = Mutex.new end # Add a Channel to the ChannelList. def add(channel) @mutex.synchronize do @channels << channel end end # Removes a Channel from the ChannelList. def rem...
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/request.rb
BitBucket.Request._extract_mime_type
ruby
def _extract_mime_type(params, options) # :nodoc: options['resource'] = params['resource'] ? params.delete('resource') : '' options['mime_type'] = params['resource'] ? params.delete('mime_type') : '' end
def extract_data_from_params(params) # :nodoc: if params.has_key?('data') and !params['data'].nil? params['data'] else params end end
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/request.rb#L70-L73
module Request METHODS = [:get, :post, :put, :delete, :patch] METHODS_WITH_BODIES = [ :post, :put, :patch ] def get_request(path, params={}, options={}) request(:get, path, params, options) end def patch_request(path, params={}, options={}) request(:patch, path, params, options) ...
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.method_missing
ruby
def method_missing(name, *args) # Queries if @collections.include?(name.to_s) @query = build_collection_query_object(name,@additional_params, *args) return @query # Adds elsif name.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) @save_operations << Operation...
Creates a new instance of the Service class @param [String] service_uri the root URI of the OData service @param [Hash] options the options to pass to the service @option options [String] :username for http basic auth @option options [String] :password for http basic auth @option options [Object] :verify_ssl fals...
train
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L24-L42
class Service attr_reader :classes, :class_metadata, :options, :collections, :edmx, :function_imports, :response # Creates a new instance of the Service class # # @param [String] service_uri the root URI of the OData service # @param [Hash] options the options to pass to the service # @option options [Strin...
iyuuya/jkf
lib/jkf/parser/kif.rb
Jkf::Parser.Kif.parse_fugou
ruby
def parse_fugou s0 = @current_pos s1 = parse_place if s1 != :failed s2 = parse_piece if s2 != :failed s3 = match_str("成") s3 = nil if s3 == :failed @reported_pos = s0 s0 = { "to" => s1, "piece" => s2, "promote" => !!s3 } else @c...
fugou : place piece "成"?
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kif.rb#L276-L295
class Kif < Base include Kifuable protected # kifu : skipline* header* initialboard? header* split? moves fork* nl? def parse_root @input += "\n" unless @input.end_with?("\n") s0 = @current_pos s1 = [] s2 = parse_skipline while s2 != :failed s1 << s2 s2...
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.abort_transaction
ruby
def abort_transaction check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_COMMITTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :commitTransaction, :abortTransaction)) ...
Abort the currently active transaction without making any changes to the database. @example Abort the transaction. session.abort_transaction @raise [ Error::InvalidTransactionOperation ] If there is no active transaction. @since 2.6.0
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L688-L724
class Session extend Forwardable include Retryable include Loggable # Get the options for this session. # # @since 2.5.0 attr_reader :options # Get the client through which this session was created. # # @since 2.5.1 attr_reader :client # The cluster time for this ses...
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_dose_reference
ruby
def create_dose_reference(dcm, description) dr_seq = DICOM::Sequence.new('300A,0010', :parent => dcm) dr_item = DICOM::Item.new(:parent => dr_seq) # Dose Reference Number: DICOM::Element.new('300A,0012', '1', :parent => dr_item) # Dose Reference Structure Type: DICOM::Element.new('30...
Creates a dose reference sequence in the given DICOM object. @param [DICOM::DObject] dcm the DICOM object in which to insert the sequence @param [String] description the value to use for Dose Reference Description @return [DICOM::Sequence] the constructed dose reference sequence
train
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L619-L631
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...
mhs/rvideo
lib/rvideo/inspector.rb
RVideo.Inspector.duration
ruby
def duration return nil unless valid? units = raw_duration.split(":") (units[0].to_i * 60 * 60 * 1000) + (units[1].to_i * 60 * 1000) + (units[2].to_f * 1000).to_i end
The duration of the movie in milliseconds, as an integer. Example: 24400 # 24.4 seconds Note that the precision of the duration is in tenths of a second, not thousandths, but milliseconds are a more standard unit of time than deciseconds.
train
https://github.com/mhs/rvideo/blob/5d12bafc5b63888f01c42de272fddcef0ac528b1/lib/rvideo/inspector.rb#L304-L309
class Inspector attr_reader :filename, :path, :full_filename, :raw_response, :raw_metadata attr_accessor :ffmpeg_binary # # To inspect a video or audio file, initialize an Inspector object. # # file = RVideo::Inspector.new(options_hash) # # Inspector accepts three opti...
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.IncrementSupport.increment
ruby
def increment(key, amount = 1, options = {}) value = Utils.to_int(load(key, options)) + amount store(key, value.to_s, options) value end
(see Defaults#increment)
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L409-L413
module IncrementSupport # (see Defaults#increment) def self.included(base) base.supports(:increment) if base.respond_to?(:supports) end end
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.open
ruby
def open context = LIBUSB::Context.new device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil? @handle = device.open @handle.claim_interface(0) ...
Opens the connection This is triggered automatically by intantiating the object. @return [nil]
train
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L107-L113
class UsbConnection # The USB idVendor code LEGO_VENDOR_ID = 0x0694 # The USB idProduct code NXT_PRODUCT_ID = 0x0002 # The USB endpoint (communication channel) to send data out to the NXT brick USB_ENDPOINT_OUT = 0x01 # The USB endpoint (communication channel) to receive data from the NX...
litaio/lita
lib/lita/configuration_builder.rb
Lita.ConfigurationBuilder.validate
ruby
def validate(&block) validator = block unless value.nil? error = validator.call(value) raise ValidationError, error if error end @validator = block end
Declares a block to be used to validate the value of an attribute whenever it's set. Validation blocks should return any object to indicate an error, or +nil+/+false+ if validation passed. @yield The code that performs validation. @return [void]
train
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L155-L164
class ConfigurationBuilder # An array of any nested configuration builders. # @return [Array<ConfigurationBuilder>] The array of child configuration builders. # @api private attr_reader :children # An array of valid types for the attribute. # @return [Array<Object>] The array of valid types. ...
hashicorp/vagrant
lib/vagrant/registry.rb
Vagrant.Registry.get
ruby
def get(key) return nil if !@items.key?(key) return @results_cache[key] if @results_cache.key?(key) @results_cache[key] = @items[key].call end
Get a value by the given key. This will evaluate the block given to `register` and return the resulting value.
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/registry.rb#L24-L28
class Registry def initialize @items = {} @results_cache = {} end # Register a key with a lazy-loaded value. # # If a key with the given name already exists, it is overwritten. def register(key, &block) raise ArgumentError, "block required" if !block_given? @items[key]...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.get_settings
ruby
def get_settings(options = {}, request_options = {}) options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion'] client.get(Protocol.settings_uri(name, options).to_s, :read, request_options) end
Get settings of this index
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L617-L620
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/connection/api/set_note_attachment.rb
SugarCRM.Connection.set_note_attachment
ruby
def set_note_attachment(id, filename, file, opts={}) options = { :module_id => '', :module_name => '' }.merge! opts login! unless logged_in? json = <<-EOF { "session": "#{@sugar_session_id}", "note": { "id": "#{id}", "filename": "#...
Creates or updates an attachment on a note
train
https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/api/set_note_attachment.rb#L3-L24
module SugarCRM; class Connection # Creates or updates an attachment on a note end; end
Thermatix/ruta
lib/ruta/route.rb
Ruta.Route.paramaterize
ruby
def paramaterize params segments = @url.split('/') segments.map { |item| item[0] == ':' ? params.shift : item }.join('/') end
@param [String] pattern of url to match against @param [Symbol] context_ref to context route is mounted to @param [{Symbol => String,Number,Boolean}] flags attached to route take in params and return a paramaterized route @param [Array<String,Number,Boolean>] params a list of params to replace named params in a rou...
train
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/route.rb#L63-L66
class Route DOM = ::Kernel.method(:DOM) NAMED = /:(\w+)/ SPLAT = /\\\*(\w+)/ OPTIONAL = /\\\((.*?)\\\)/ # @!attribute [r] regexp # @return [Symbol] the regexp used to match against a route # @!attribute [r] named # @return [Symbol] list of all named paramters # @!attribute [r] t...
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/repos/default_reviewers.rb
BitBucket.Repos::DefaultReviewers.get
ruby
def get(user_name, repo_name, reviewer_username, params={}) update_and_validate_user_repo_params(user_name, repo_name) normalize! params get_request("/2.0/repositories/#{user_name}/#{repo_name}/default-reviewers/#{reviewer_username}", params) end
Get a default reviewer's info = Examples bitbucket = BitBucket.new bitbucket.repos.default_reviewers.get 'user-name', 'repo-name', 'reviewer-username'
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/repos/default_reviewers.rb#L27-L32
class Repos::DefaultReviewers < API # List default reviewers # # = Examples # bitbucket = BitBucket.new # bitbucket.repos.default_reviewers.list 'user-name', 'repo-name' # bitbucket.repos.default_reviewers.list 'user-name', 'repo-name' { |reviewer| ... } # def list(user_name, repo_...
minhnghivn/idata
lib/idata/detector.rb
Idata.Detector.find_valid
ruby
def find_valid selected = @candidates.select { |delim, count| begin CSV.parse(@sample, col_sep: delim) true rescue Exception => ex false end }.keys return selected.first if selected.count == 1 return DEFAULT_DELIMITER if selected.include?(DE...
just work
train
https://github.com/minhnghivn/idata/blob/266bff364e8c98dd12eb4256dc7a3ee10a142fb3/lib/idata/detector.rb#L38-L50
class Detector DEFAULT_DELIMITER = "," COMMON_DELIMITERS = [DEFAULT_DELIMITER, "|", "\t", ";"] SAMPLE_SIZE = 100 def initialize(file) @file = file @sample = `head -n #{SAMPLE_SIZE} #{@file}`.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') @sample_lines = @...
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.write_from_erb_template
ruby
def write_from_erb_template(erbfile, outfile, config = {}, options = { :no_interaction => false }) erbfiles = (erbfile.is_a?(Array)) ? erbfile : [ erbfile ] content = "" erbfiles.each do |f| erb =...
ERB generation of the file `outfile` using the source template file `erbfile` Supported options: :no_interaction [boolean]: do not interact :srcdir [string]: source dir for all considered ERB files
train
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L364-L384
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...
barkerest/incline
app/controllers/incline/access_groups_controller.rb
Incline.AccessGroupsController.access_group_params
ruby
def access_group_params(mode = :all) list = [] list += [ :name ] if mode == :before_create || mode == :all list += [ { group_ids: [], user_ids: [] } ] if mode == :after_create || mode == :all params.require(:access_group).permit(list) end
Only allow a trusted parameter "white list" through.
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/controllers/incline/access_groups_controller.rb#L119-L125
class AccessGroupsController < ApplicationController before_action :set_access_group, only: [ :show, :edit, :update, :destroy ] before_action :set_dt_request, only: [ :index, :locate ] require_admin true layout :layout_to_use ## # GET /incline/access_groups def index end ## ...
amatsuda/rfd
lib/rfd/commands.rb
Rfd.Commands.ctrl_a
ruby
def ctrl_a mark = marked_items.size != (items.size - 2) # exclude . and .. items.each {|i| i.toggle_mark unless i.marked? == mark} draw_items draw_marked_items move_cursor current_row end
Mark or unmark "a"ll files and directories.
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L190-L196
module Commands # Change permission ("A"ttributes) of selected files and directories. def a process_command_line preset_command: 'chmod' end # "c"opy selected files and directories. def c process_command_line preset_command: 'cp' end # Soft "d"elete (actually mv to the trash ...
jeremytregunna/ruby-trello
lib/trello/client.rb
Trello.Client.find
ruby
def find(path, id, params = {}) response = get("/#{path.to_s.pluralize}/#{id}", params) trello_class = class_from_path(path) trello_class.parse response do |data| data.client = self end end
Finds given resource by id Examples: client.find(:board, "board1234") client.find(:member, "user1234")
train
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/client.rb#L43-L49
class Client extend Forwardable include Authorization def_delegators :configuration, :credentials, *Configuration.configurable_attributes def initialize(attrs = {}) self.configuration.attributes = attrs end def get(path, params = {}) uri = Addressable::URI.parse("https://api.tre...
OSHPark/ruby-api-client
lib/oshpark/client.rb
Oshpark.Client.add_order_item
ruby
def add_order_item id, project_id, quantity post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}} end
Add a Project to an Order @param id @param project_id @param quantity
train
https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L117-L119
class Client attr_accessor :token, :connection # Create an new Client object. # # @param connection: # pass in a subclass of connection which implements the `request` method # with whichever HTTP client library you prefer. Default is Net::HTTP. def initialize args = {} url = args.f...
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtPubkey.version
ruby
def version return ExtPubkey.version_from_purpose(number) if depth == 1 ver ? ver : Bitcoin.chain_params.extended_pubkey_version end
get version bytes using serialization format
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L273-L276
class ExtPubkey attr_accessor :ver attr_accessor :depth attr_accessor :number attr_accessor :chain_code attr_accessor :pubkey # hex format attr_accessor :parent_fingerprint # serialize extended pubkey def to_payload version.htb << [depth].pack('C') << parent_fingerpri...
nbulaj/proxy_fetcher
lib/proxy_fetcher/configuration.rb
ProxyFetcher.Configuration.setup_custom_class
ruby
def setup_custom_class(klass, required_methods: []) unless klass.respond_to?(*required_methods) raise ProxyFetcher::Exceptions::WrongCustomClass.new(klass, required_methods) end klass end
Checks if custom class has some required class methods
train
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/configuration.rb#L175-L181
class Configuration # @!attribute client_timeout # @return [Integer] HTTP request timeout (connect / open) for [ProxyFetcher::Client] attr_accessor :client_timeout # @!attribute provider_proxies_load_timeout # @return [Integer] HTTP request timeout (connect / open) for loading of proxies list...
TelAPI/telapi-ruby
lib/telapi/participant.rb
Telapi.Participant.undeaf
ruby
def undeaf response = Network.post(['Conferences', self.conference_sid, 'Participant', self.call_sid], { :Deaf => false }) Participant.new(response) end
Undeaf a participant of a conference call, returning a Telapi::Participant object See http://www.telapi.com/docs/api/rest/conferences/deaf-or-mute/
train
https://github.com/TelAPI/telapi-ruby/blob/880fd4539c97a5d2eebc881adc843afff341bca5/lib/telapi/participant.rb#L27-L30
class Participant < Resource class << self # Convenient alternative to Conference::participants def list(conference_sid, optional_params = {}) Conference.participants(conference_sid, optional_params) end # Convenient alternative to Conference::participant def get(conference_...
thumblemonks/riot
lib/riot/assertion_macros/equivalent_to.rb
Riot.EquivalentToMacro.evaluate
ruby
def evaluate(actual, expected) if expected === actual pass new_message.is_equivalent_to(expected) else fail expected_message(actual).to_be_equivalent_to(expected) end end
(see Riot::AssertionMacro#evaluate) @param [Object] expected the object value to compare actual to
train
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/assertion_macros/equivalent_to.rb#L21-L27
class EquivalentToMacro < AssertionMacro register :equivalent_to # (see Riot::AssertionMacro#evaluate) # @param [Object] expected the object value to compare actual to # (see Riot::AssertionMacro#devaluate) # @param [Object] expected the object value to compare actual to def devaluate(a...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.run_scope
ruby
def run_scope(scope, machine, klass, states) values = states.flatten.map { |state| machine.states.fetch(state).value } scope.call(klass, values) end
Generates the results for the given scope based on one or more states to filter by
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2132-L2135
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
cul/cul-ldap
lib/cul/ldap.rb
Cul.LDAP.search
ruby
def search(args = {}) super(args).tap do |result| if result.is_a?(Array) result.map!{ |e| Cul::LDAP::Entry.new(e) } end end end
Wrapper around Net::LDAP#search, converts Net::LDAP::Entry objects to Cul::LDAP::Entry objects.
train
https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L48-L54
class LDAP < Net::LDAP CONFIG_FILENAME = 'cul_ldap.yml' CONFIG_DEFAULTS = { host: 'ldap.columbia.edu', port: '636', encryption: { method: :simple_tls, tls_options: OpenSSL::SSL::SSLContext::DEFAULT_PARAMS } }.freeze def initialize(options = {}) super(buil...
oleganza/btcruby
lib/btcruby/extensions.rb
BTC.StringExtensions.to_wif
ruby
def to_wif(network: nil, public_key_compressed: nil) BTC::WIF.new(private_key: self, network: network, public_key_compressed: public_key_compressed).to_s end
Converts binary string as a private key to a WIF Base58 format.
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/extensions.rb#L5-L7
module StringExtensions # Converts binary string as a private key to a WIF Base58 format. # Decodes string in WIF format into a binary private key (32 bytes) def from_wif addr = BTC::WIF.new(string: self) addr ? addr.private_key : nil end # Converts binary data into hex string ...
hoanganhhanoi/dhcp_parser
lib/dhcp_parser.rb
DHCPParser.Conf.pools
ruby
def pools pool = [] index = 0 while index < @datas.count index += 1 data = DHCPParser::Conf.get_pool(@datas["net#{index}"]) i = 0 tmp_hash = {} while i < data["hosts"].count i += 1 tmp_hash["#{i}"] = data["hosts"]["host#{i}"] end ...
Get pool
train
https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L298-L313
class Conf attr_accessor :datas # Function constructor of DHCP def initialize(path) @datas = DHCPParser::Conf.read_file(path) @array_net = [] end # Read file config return Net. Net is hash def self.read_file(path) str = "" count = 0 counter = ...
senchalabs/jsduck
lib/jsduck/tag/type.rb
JsDuck::Tag.Type.parse_doc
ruby
def parse_doc(p, pos) tag = p.standard_tag({:tagname => :type, :type => true, :optional => true}) tag[:type] = curlyless_type(p) unless tag[:type] tag end
matches @type {type} or @type type The presence of @type implies that we are dealing with property. ext-doc allows type name to be either inside curly braces or without them at all.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag/type.rb#L19-L23
class Type < Tag def initialize @pattern = "type" @tagname = :type # We don't really care about the position as we don't output any # HTML. We just need to set this up to do the formatting. @html_position = POS_DOC end # matches @type {type} or @type type # # The ...
sds/haml-lint
lib/haml_lint/linter.rb
HamlLint.Linter.next_node
ruby
def next_node(node) return unless node siblings = node.parent ? node.parent.children : [node] next_sibling = siblings[siblings.index(node) + 1] if siblings.count > 1 return next_sibling if next_sibling next_node(node.parent) end
Gets the next node following this node, ascending up the ancestor chain recursively if this node has no siblings. @param node [HamlLint::Tree::Node] @return [HamlLint::Tree::Node,nil]
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L153-L161
class Linter include HamlVisitor # List of lints reported by this linter. # # @todo Remove once spec/support/shared_linter_context returns an array of # lints for the subject instead of the linter itself. attr_reader :lints # Initializes a linter with the specified configuration. #...
huacnlee/rucaptcha
lib/rucaptcha/controller_helpers.rb
RuCaptcha.ControllerHelpers.generate_rucaptcha
ruby
def generate_rucaptcha res = RuCaptcha.generate() session_val = { code: res[0], time: Time.now.to_i } RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in) res[1] end
Generate a new Captcha
train
https://github.com/huacnlee/rucaptcha/blob/b7074ed9fd84e9768e91b39555ea037ffd327032/lib/rucaptcha/controller_helpers.rb#L17-L25
module ControllerHelpers extend ActiveSupport::Concern included do helper_method :verify_rucaptcha? end # session key of rucaptcha def rucaptcha_sesion_key_key session_id = session.respond_to?(:id) ? session.id : session[:session_id] warning_when_session_invalid if session_id.b...
mailgun/mailgun-ruby
lib/mailgun/messages/batch_message.rb
Mailgun.BatchMessage.add_recipient
ruby
def add_recipient(recipient_type, address, variables = nil) # send the message when we have 1000, not before send_message if @counters[:recipients][recipient_type] == Mailgun::Chains::MAX_RECIPIENTS compiled_address = parse_address(address, variables) set_multi_complex(recipient_type, compiled_...
Public: Creates a new BatchMessage object. Adds a specific type of recipient to the batch message object. @param [String] recipient_type The type of recipient. "to". @param [String] address The email address of the recipient to add to the message object. @param [Hash] variables A hash of the variables associated w...
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/batch_message.rb#L46-L56
class BatchMessage < MessageBuilder attr_reader :message_ids, :domain, :recipient_variables # Public: Creates a new BatchMessage object. def initialize(client, domain) @client = client @recipient_variables = {} @domain = domain @message_ids = {} @message = Hash.new { |hash,...
litaio/lita
lib/lita/configuration_builder.rb
Lita.ConfigurationBuilder.build_nested
ruby
def build_nested(object) this = self nested_object = Configuration.new children.each { |child| child.build(nested_object) } object.instance_exec { define_singleton_method(this.name) { nested_object } } object end
Finalize the root builder or any builder with children.
train
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L198-L206
class ConfigurationBuilder # An array of any nested configuration builders. # @return [Array<ConfigurationBuilder>] The array of child configuration builders. # @api private attr_reader :children # An array of valid types for the attribute. # @return [Array<Object>] The array of valid types. ...
seamusabshere/weighted_average
lib/weighted_average/arel_select_manager_instance_methods.rb
WeightedAverage.ArelSelectManagerInstanceMethods.weighted_average_relation
ruby
def weighted_average_relation(data_column_names, options = {}) unless options[:safe] == true return clone.weighted_average_relation(data_column_names, options.merge(:safe => true)) end data_column_names = Array.wrap data_column_names left = self.source.left weighted_by_column = c...
In case you want to get the relation and/or the SQL of the calculation query before actually runnnig it. @example Get the SQL Arel::Table.new(:flight_segments).weighted_average_relation(:load_factor, :weighted_by => :passengers).to_sql @return [Arel::SelectManager] A relation you can play around with.
train
https://github.com/seamusabshere/weighted_average/blob/42f3d62d321b062353510778d4c151bdf7411b90/lib/weighted_average/arel_select_manager_instance_methods.rb#L28-L86
module ArelSelectManagerInstanceMethods # Calculate the weighted average of column(s). # # @param [Symbol,Array<Symbol>] data_column_names One or more column names whose average should be calculated. Added together before being multiplied by the weighting if more than one. # @param [Hash] options ...
gollum/gollum
lib/gollum/helpers.rb
Precious.Helpers.extract_path
ruby
def extract_path(file_path) return nil if file_path.nil? last_slash = file_path.rindex("/") if last_slash file_path[0, last_slash] end end
Extract the path string that Gollum::Wiki expects
train
https://github.com/gollum/gollum/blob/f44367c31baac5c154888a9e09b2833fa62e1c61/lib/gollum/helpers.rb#L10-L16
module Helpers EMOJI_PATHNAME = Pathname.new(Gemojione.images_path).freeze # Extract the path string that Gollum::Wiki expects # Extract the 'page' name from the file_path def extract_name(file_path) if file_path[-1, 1] == "/" return nil end # File.basename is too eager ...
winston/google_visualr
lib/google_visualr/base_chart.rb
GoogleVisualr.BaseChart.to_js
ruby
def to_js(element_id) js = "" js << "\n<script type='text/javascript'>" js << load_js(element_id) js << draw_js(element_id) js << "\n</script>" js end
Generates JavaScript and renders the Google Chart in the final HTML output. Parameters: *div_id [Required] The ID of the DIV element that the Google Chart should be rendered in.
train
https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/base_chart.rb#L63-L70
class BaseChart include GoogleVisualr::ParamHelpers DEFAULT_VERSION = "1.0".freeze attr_accessor :data_table, :listeners, :version, :language, :material def initialize(data_table, options={}) @data_table = data_table @listeners = [] @version = options.delete(:version) || D...
zhimin/rwebspec
lib/rwebspec-common/core.rb
RWebSpec.Core.process_each_row_in_csv_file
ruby
def process_each_row_in_csv_file(csv_file, &block) require 'faster_csv' connect_to_testwise("CSV_START", csv_file) if $testwise_support has_error = false idx = 0 FasterCSV.foreach(csv_file, :headers => :first_row, :encoding => 'u') do |row| connect_to_testwise("CSV_ON_ROW", idx.to_s) if ...
Data Driven Tests Processing each row in a CSV file, must have heading rows Usage: process_each_row_in_csv_file(@csv_file) { |row| goto_page("/") enter_text("username", row[1]) enter_text("password", row[2]) click_button("Sign in") page_text.should contain(row[3]) failsafe{ click...
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L488-L508
module Core # open a browser, and set base_url via hash, but does not acually # # example: # open_browser :base_url => http://localhost:8080, :browser => :ie # # There are 3 ways to set base url # 1. pass as first argument # 2. If running using TestWise, used as ...
markdownlint/markdownlint
lib/mdl/doc.rb
MarkdownLint.Doc.find_type_elements
ruby
def find_type_elements(type, nested=true, elements=@elements) results = [] if type.class == Symbol type = [type] end elements.each do |e| results.push(e) if type.include?(e.type) if nested and not e.children.empty? results.concat(find_type_elements(type, nested,...
Find all elements of a given type, returning a list of the element objects themselves. Instead of a single type, a list of types can be provided instead to find all types. If +nested+ is set to false, this returns only top level elements of a given type.
train
https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L86-L98
class Doc ## # A list of raw markdown source lines. Note that the list is 0-indexed, # while line numbers in the parsed source are 1-indexed, so you need to # subtract 1 from a line number to get the correct line. The element_line* # methods take care of this for you. attr_reader :lines ...
schasse/mandrill_batch_mailer
lib/mandrill_batch_mailer/base_mailer.rb
MandrillBatchMailer.BaseMailer.mandrill_parameters
ruby
def mandrill_parameters { key: MandrillBatchMailer.api_key, template_name: template_name, template_content: [], message: { subject: subject, from_email: from_email, from_name: from_name, to: to, important: false,...
rubocop:disable MethodLength
train
https://github.com/schasse/mandrill_batch_mailer/blob/6f8902b2ee3cc6e4758c57c1ef061e86db369972/lib/mandrill_batch_mailer/base_mailer.rb#L59-L86
class BaseMailer private attr_accessor :caller_method_name public def initialize(method) self.caller_method_name = method end def mail(to: nil) @tos = tos_from(to) send_template mandrill_parameters end # feel free to override def from_emai...
sds/haml-lint
lib/haml_lint/linter/rubocop.rb
HamlLint.Linter::RuboCop.extract_lints_from_offenses
ruby
def extract_lints_from_offenses(offenses, source_map) dummy_node = Struct.new(:line) offenses.reject { |offense| Array(config['ignored_cops']).include?(offense.cop_name) } .each do |offense| record_lint(dummy_node.new(source_map[offense.line]), offense.message, off...
Aggregates RuboCop offenses and converts them to {HamlLint::Lint}s suitable for reporting. @param offenses [Array<RuboCop::Cop::Offense>] @param source_map [Hash]
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/rubocop.rb#L68-L76
class Linter::RuboCop < Linter include LinterRegistry # Maps the ::RuboCop::Cop::Severity levels to our own levels. SEVERITY_MAP = { error: :error, fatal: :error, convention: :warning, refactor: :warning, warning: :warning, }.freeze def visit_root(_node) extr...
oniram88/imdb-scan
lib/imdb/movie.rb
IMDB.Movie.genres
ruby
def genres doc.xpath("//h4[contains(., 'Genre')]/..").search("a").map { |g| g.content.strip unless g.content =~ /See more/ }.compact rescue nil end
Genre List @return [Array]
train
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L115-L121
class Movie < IMDB::Skeleton attr_accessor :link, :imdb_id def initialize(id_of) # !!!DON'T FORGET DEFINE NEW METHODS IN SUPER!!! super("Movie", { :imdb_id => String, :poster => String, :title => String, :release_date => String,...
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby
lib/groupdocs_signature_cloud/models/border_line_data.rb
GroupDocsSignatureCloud.BorderLineData.list_invalid_properties
ruby
def list_invalid_properties invalid_properties = [] if @style.nil? invalid_properties.push("invalid value for 'style', style cannot be nil.") end if @transparency.nil? invalid_properties.push("invalid value for 'transparency', transparency cannot be nil.") end if @w...
Initializes the object @param [Hash] attributes Model attributes in the form of hash Show invalid properties with the reasons. Usually used together with valid? @return Array for valid properies with the reasons
train
https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/models/border_line_data.rb#L120-L135
class BorderLineData # Gets or sets the signature border style. attr_accessor :style # Gets or sets the signature border transparency (value from 0.0 (opaque) through 1.0 (clear)). attr_accessor :transparency # Gets or sets the weight of the signature border. attr_accessor :weight # G...
giraffi/zcloudjp
lib/zcloudjp/machine.rb
Zcloudjp.Machine.start
ruby
def start(params={}) id = params.delete(:id) || self.id response = Zcloudjp::Client.post("/machines/#{id}/start", self.request_options) update_attributes(response.parsed_response) end
POST /machines/:id/start.json
train
https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/machine.rb#L41-L45
module Machine # GET /machines.json def index(params={}) self.request_options = self.request_options.merge(params[:query] || {}) response = Zcloudjp::Client.get("/machines", self.request_options) response.parsed_response.map do |res| update_attributes(res).clone end end ...
mongodb/mongoid
lib/mongoid/positional.rb
Mongoid.Positional.positionally
ruby
def positionally(selector, operations, processed = {}) if selector.size == 1 || selector.values.any? { |val| val.nil? } return operations end keys = selector.keys.map{ |m| m.sub('._id','') } - ['_id'] keys = keys.sort_by { |s| s.length*-1 } process_operations(keys, operations, proc...
Takes the provided selector and atomic operations and replaces the indexes of the embedded documents with the positional operator when needed. @note The only time we can accurately know when to use the positional operator is at the exact time we are going to persist something. So we can tell by the selector t...
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/positional.rb#L37-L44
module Positional # Takes the provided selector and atomic operations and replaces the # indexes of the embedded documents with the positional operator when # needed. # # @note The only time we can accurately know when to use the positional # operator is at the exact time we are going to pe...
RobertAudi/TaskList
lib/task-list/parser.rb
TaskList.Parser.unglobify
ruby
def unglobify(glob) chars = glob.split("") chars = smoosh(chars) curlies = 0 escaping = false string = chars.map do |char| if escaping escaping = false char else case char when "**" "([^/]+/)*" when '*' ...
NOTE: This is actually a glob-to-regex method
train
https://github.com/RobertAudi/TaskList/blob/98ac82f449eec7a6958f88c19c9637845eae68f2/lib/task-list/parser.rb#L165-L213
class Parser attr_reader :files, :tasks, :search_path, :github def initialize(arguments: [], options: {}) self.search_path = options[:search_path] @github = options[:github] if options[:github] @plain = options[:plain] if options[:plain] @type = options[:type].upcase if options[:type]...
mailgun/mailgun-ruby
lib/mailgun/messages/message_builder.rb
Mailgun.MessageBuilder.add_tag
ruby
def add_tag(tag) if @counters[:attributes][:tag] >= Mailgun::Chains::MAX_TAGS fail Mailgun::ParameterError, 'Too many tags added to message.', tag end set_multi_complex('o:tag', tag) @counters[:attributes][:tag] += 1 end
Add tags to message. Limit of 3 per message. @param [String] tag A defined campaign ID to add to the message. @return [void]
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L187-L193
class MessageBuilder attr_reader :message, :counters # Public: Creates a new MessageBuilder object. def initialize @message = Hash.new { |hash, key| hash[key] = [] } @counters = { recipients: { to: 0, cc: 0, bcc: 0 }, attributes: { attachment: 0, campaign_id: 0, custom_optio...
jeremytregunna/ruby-trello
lib/trello/card.rb
Trello.Card.add_attachment
ruby
def add_attachment(attachment, name = '') # Is it a file object or a string (url)? if attachment.respond_to?(:path) && attachment.respond_to?(:read) client.post("/cards/#{id}/attachments", { file: attachment, name: name }) else client.post("/cards/#{id...
Add an attachment to this card
train
https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L421-L434
class Card < BasicData register_attributes :id, :short_id, :name, :desc, :due, :due_complete, :closed, :url, :short_url, :board_id, :member_ids, :list_id, :pos, :last_activity_date, :labels, :card_labels, :cover_image_id, :badges, :card_members, :source_card_id, :source_card_properties, readonly...
puppetlabs/beaker-aws
lib/beaker/hypervisor/aws_sdk.rb
Beaker.AwsSdk.add_ingress_rule
ruby
def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp') cl.authorize_security_group_ingress( :cidr_ip => cidr_ip, :ip_protocol => protocol, :from_port => from_port, :to_port => to_port, :group_id => sg_group.group_id, ) end
Authorizes connections from certain CIDR to a range of ports @param cl [Aws::EC2::Client] @param sg_group [Aws::EC2::SecurityGroup] the AWS security group @param cidr_ip [String] CIDR used for outbound security group rule @param from_port [String] Starting Port number in the range @param to_port [String] Ending P...
train
https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1105-L1113
class AwsSdk < Beaker::Hypervisor ZOMBIE = 3 #anything older than 3 hours is considered a zombie PING_SECURITY_GROUP_NAME = 'beaker-ping' attr_reader :default_region # Initialize AwsSdk hypervisor driver # # @param [Array<Beaker::Host>] hosts Array of Beaker::Host objects # @param [Hash<S...
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.AttributeTransitionCollection.rollback
ruby
def rollback super each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?} end
Resets the event attribute so it can be re-evaluated if attempted again
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L241-L244
class AttributeTransitionCollection < TransitionCollection def initialize(transitions = [], options = {}) #:nodoc: super(transitions, {use_transactions: false, :actions => false}.merge(options)) end private # Hooks into running transition callbacks so that event / event transition #...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.unarchive
ruby
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| File...
Unarchive .zip and .tar.gz files within selected files and directories into current_directory.
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L533-L582
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...
phallguy/scorpion
lib/scorpion/hunt.rb
Scorpion.Hunt.inject
ruby
def inject( object ) trip.object = object object.send :scorpion_hunt=, self object.injected_attributes.each do |attr| next if object.send "#{ attr.name }?" next if attr.lazy? object.send :inject_dependency, attr, fetch( attr.contract ) end object.send :on_injecte...
Inject given `object` with its expected dependencies. @param [Scorpion::Object] object to be injected. @return [Scorpion::Object] the injected object.
train
https://github.com/phallguy/scorpion/blob/0bc9c1111a37e35991d48543dec88a36f16d7aee/lib/scorpion/hunt.rb#L80-L94
class Hunt extend Forwardable # ============================================================================ # @!group Attributes # # @!attribute # @return [Scorpion] scorpion used to fetch uncaptured dependency. attr_reader :scorpion # @!attribute # @return [Array<Array>] the...
FormAPI/formapi-ruby
lib/form_api/api_client.rb
FormAPI.ApiClient.call_api
ruby
def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) response = request.run if @config.debugging @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? if response.timed_out? ...
Call an API with given options. @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements: the data deserialized from response body (could be nil), response status code and response headers.
train
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api_client.rb#L49-L95
class ApiClient # The Configuration object holding settings to be used in the API client. attr_accessor :config # Defines the headers to be used in HTTP requests of all API calls by default. # # @return [Hash] attr_accessor :default_headers # Initializes the ApiClient # @option confi...
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.dep
ruby
def dep(params = {}) extension = File.extname(params[:source]) dep = params[:dep] source = params[:source] incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}" case when cpp_source_extensions.include?(extension) flags = @settings['CXXFLAGS'] + ' ' + pa...
Creates dependency @param [Hash] params @option params [String] :source source filename with path @option params [String] :dep dependency filename path @option params [Hash] :settings project specific settings @option params [Array] :includes include paths used
train
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L434-L453
class Toolchain attr_reader :qt, :settings, :target, :config # Initializes object # # @param [RakeOE::Config] config Project wide configurations # def initialize(config) raise 'Configuration failure' unless config.checks_pass? @config = config begin @kvr = KeyValueReader.new(confi...
DigitPaint/roger
lib/roger/template.rb
Roger.Template.extract_front_matter
ruby
def extract_front_matter(source) fm_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m return [{}, source] unless match = source.match(fm_regex) source = source.sub(fm_regex, "") begin data = (YAML.safe_load(match[1]) || {}).inject({}) do |memo, (k, v)| memo[k.to_sym] = v ...
Get the front matter portion of the file and extract it.
train
https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/template.rb#L90-L110
class Template < BlankTemplate # The source attr_accessor :source # Store the frontmatter attr_accessor :data # The path to the source file for this template attr_accessor :source_path # The current tilt template being used attr_reader :current_tilt_template class << self ...
zhimin/rwebspec
lib/rwebspec-common/assert.rb
RWebSpec.Assert.assert_button_not_present
ruby
def assert_button_not_present(button_id) @web_browser.buttons.each { |button| the_button_id = RWebSpec.framework == "Watir" ? button.id : button["id"] perform_assertion { assert(the_button_id != button_id, "unexpected button id: #{button_id} found") } } end
Button
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L328-L333
module Assert # own assert method def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true en...
state-machines/state_machines
lib/state_machines/event_collection.rb
StateMachines.EventCollection.valid_for
ruby
def valid_for(object, requirements = {}) match(requirements).select { |event| event.can_fire?(object, requirements) } end
Gets the list of events that can be fired on the given object. Valid requirement options: * <tt>:from</tt> - One or more states being transitioned from. If none are specified, then this will be the object's current state. * <tt>:to</tt> - One or more states being transitioned to. If none are specified, then...
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event_collection.rb#L41-L43
class EventCollection < NodeCollection def initialize(machine) #:nodoc: super(machine, :index => [:name, :qualified_name]) end # Gets the list of events that can be fired on the given object. # # Valid requirement options: # * <tt>:from</tt> - One or more states being transitioned from...
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.verify
ruby
def verify(sig, origin) return false unless valid_pubkey? begin sig = ecdsa_signature_parse_der_lax(sig) secp256k1_module.verify_sig(origin, sig, pubkey) rescue Exception false end end
verify signature using public key @param [String] sig signature data with binary format @param [String] origin original message @return [Boolean] verify result
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L110-L118
class Key PUBLIC_KEY_SIZE = 65 COMPRESSED_PUBLIC_KEY_SIZE = 33 SIGNATURE_SIZE = 72 COMPACT_SIGNATURE_SIZE = 65 attr_accessor :priv_key attr_accessor :pubkey attr_accessor :key_type attr_reader :secp256k1_module TYPES = {uncompressed: 0x00, compressed: 0x01, p2pkh: 0x10, p2wpkh: ...
projectcypress/health-data-standards
lib/hqmf-parser/converter/pass1/data_criteria_converter.rb
HQMF.DataCriteriaConverter.create_group_data_criteria
ruby
def create_group_data_criteria(preconditions, type, value, parent_id, id, standard_category, qds_data_type) extract_group_data_criteria_tree(HQMF::DataCriteria::UNION,preconditions, type, parent_id) end
grouping data criteria are used to allow a single reference off of a temporal reference or subset operator grouping data criteria can reference either regular data criteria as children, or other grouping data criteria
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/converter/pass1/data_criteria_converter.rb#L46-L48
class DataCriteriaConverter attr_reader :v1_data_criteria_by_id, :v2_data_criteria, :v2_data_criteria_to_delete, :measure_period_criteria, :measure_period_v1_keys, :specific_occurrences def initialize(doc, measure_period) @doc = doc @v1_data_criteria_by_id = {} @v2_data_criteria = [] ...
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.status_message
ruby
def status_message(bucket_name, state) message = ['', "Bucket s3://#{bucket_name} #{state}"] message << "Config dir #{config_dir} #{state}" state = 'complete' if state == 'created' message << "Config #{state}" message.join("\n") end
Notifies user of results of init or destroy commands.
train
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L232-L240
class Config CONFIG_DIR = '.elasticrawl' DATABASE_FILE = 'elasticrawl.sqlite3' TEMPLATES_DIR = '../../templates' TEMPLATE_FILES = ['aws.yml', 'cluster.yml', 'jobs.yml'] attr_reader :access_key_id attr_reader :secret_access_key # Sets the AWS access credentials needed for the S3 and EMR A...
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/generator.rb
BeakerHostGenerator.Generator.unstringify_values!
ruby
def unstringify_values!(config) config['HOSTS'].each do |host, settings| settings.each do |k, v| config['HOSTS'][host][k] = unstringify_value(v) end end config['CONFIG'].each do |k, v| config['CONFIG'][k] = unstringify_value(v) end end
Passes over all the values of config['HOSTS'] and config['CONFIG'] and subsequent arrays to convert numbers or booleans into proper integer or boolean types.
train
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/generator.rb#L128-L137
class Generator include BeakerHostGenerator::Data include BeakerHostGenerator::Parser include BeakerHostGenerator::Roles # Main host generation entry point, returns a Ruby map for the given host # specification and optional configuration. # # @param layout [String] The raw hosts specifica...
mswart/cany
lib/cany/recipe.rb
Cany.Recipe.exec
ruby
def exec(*args) args.flatten! Cany.logger.info args.join(' ') unless system(*args) raise CommandExecutionFailed.new args end end
API to use inside the recipe @api public Run a command inside the build directory. In most cases it is not needed to call this method directly. Look at the other helper methods. The method expects as arguments the program name and additional parameters for the program. The arguments can be group with arguments, ...
train
https://github.com/mswart/cany/blob/0d2bf4d3704d4e9a222b11f6d764b57234ddf36d/lib/cany/recipe.rb#L69-L75
class Recipe # @api public # This method should be call in subclasses to register new recipe instances. Cany ignores any # recipe subclasses which does not call register_as. If multiple recipes register on the same # name the later one will overwrite the earlier one and therefore used by Cany. # ...
fnando/troy
lib/troy/page.rb
Troy.Page.render
ruby
def render ExtensionMatcher.new(path) .default { content } .on("html") { compress render_erb } .on("md") { compress render_erb } .on("erb") { compress render_erb } .match end
Render the current page.
train
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L73-L80
class Page extend Forwardable def_delegators :meta, :template # Set the page path, which must contain a valid # meta section and page content. # attr_reader :path # Set the meta data for this particular page. # attr_reader :meta # Set the current site object, which contains...
sugaryourcoffee/syclink
lib/syclink/designer.rb
SycLink.Designer.remove_links_from_file
ruby
def remove_links_from_file(file) urls = File.foreach(file).map { |url| url.chomp unless url.empty? } remove_links(urls) end
Deletes links based on URLs that are provided in a file. Each URL has to be in one line
train
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L122-L125
class Designer # extend Forwardable # def_delegators :@website, :report_links_availability include Infrastructure # The website the designer is working on attr_accessor :website # Creates a new website where designer can operate on def new_website(title = "SYC LINK") @website = Web...
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.has_update?
ruby
def has_update?(version=nil, download_options: {}) if !@metadata_url raise Errors::BoxUpdateNoMetadata, name: @name end if download_options.delete(:automatic_check) && !automatic_update_check_allowed? @logger.info("Skipping box update check") return end version +=...
Checks if the box has an update and returns the metadata, version, and provider. If the box doesn't have an update that satisfies the constraints, it will return nil. This will potentially make a network call if it has to load the metadata from the network. @param [String] version Version constraints the update ...
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L155-L173
class Box include Comparable # Number of seconds to wait between checks for box updates BOX_UPDATE_CHECK_INTERVAL = 3600 # The box name. This is the logical name used when adding the box. # # @return [String] attr_reader :name # This is the provider that this box is built for. #...
igrigorik/http-2
lib/http/2/framer.rb
HTTP2.Framer.generate
ruby
def generate(frame) bytes = Buffer.new length = 0 frame[:flags] ||= [] frame[:stream] ||= 0 case frame[:type] when :data bytes << frame[:payload] length += frame[:payload].bytesize when :headers if frame[:weight] || frame[:stream_dependency] || !fram...
Generates encoded HTTP/2 frame. - http://tools.ietf.org/html/draft-ietf-httpbis-http2 @param frame [Hash]
train
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/framer.rb#L177-L320
class Framer include Error # Default value of max frame size (16384 bytes) DEFAULT_MAX_FRAME_SIZE = 2**14 # Current maximum frame size attr_accessor :max_frame_size # Maximum stream ID (2^31) MAX_STREAM_ID = 0x7fffffff # Maximum window increment value (2^31) MAX_WINDOWINC = 0x7...
hashicorp/vagrant
lib/vagrant/bundler.rb
Vagrant.Bundler.generate_builtin_set
ruby
def generate_builtin_set(system_plugins=[]) builtin_set = BuiltinSet.new @logger.debug("Generating new builtin set instance.") vagrant_internal_specs.each do |spec| if !system_plugins.include?(spec.name) builtin_set.add_builtin_spec(spec) end end builtin_set e...
Generate the builtin resolver set
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L446-L455
class Bundler # Location of HashiCorp gem repository HASHICORP_GEMSTORE = "https://gems.hashicorp.com/".freeze # Default gem repositories DEFAULT_GEM_SOURCES = [ HASHICORP_GEMSTORE, "https://rubygems.org/".freeze ].freeze def self.instance @bundler ||= self.new end ...
chicks/sugarcrm
lib/sugarcrm/associations/association.rb
SugarCRM.Association.resolve_target
ruby
def resolve_target # Use the link_field name first klass = @link_field.singularize.camelize namespace = @owner.class.session.namespace_const return namespace.const_get(klass) if namespace.const_defined? klass # Use the link_field attribute "module" if @attributes["module"].length > 0...
Attempts to determine the class of the target in the association
train
https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L67-L83
class Association attr_accessor :owner, :target, :link_field, :relationship, :attributes, :proxy_methods, :cardinality # Creates a new instance of an Association def initialize(owner,link_field,opts={}) @options = { :define_methods? => true }.merge! opts @owner = owner check_valid_o...
charypar/cyclical
lib/cyclical/occurrence.rb
Cyclical.Occurrence.list_occurrences
ruby
def list_occurrences(from, direction = :forward, &block) raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time) results = [] n, current = init_loop(from, direction) loop do # Rails.logger.debug("Listing oc...
yields valid occurrences, return false from the block to stop
train
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/occurrence.rb#L70-L93
class Occurrence attr_reader :rule, :start_time attr_accessor :duration def initialize(rule, start_time) @rule = rule @start_time = @rule.match?(start_time, start_time) ? start_time : @rule.next(start_time, start_time) end def next_occurrence(after) next_occurrences(1, after...
wvanbergen/request-log-analyzer
lib/request_log_analyzer/file_format.rb
RequestLogAnalyzer::FileFormat.CommonRegularExpressions.timestamp
ruby
def timestamp(format_string, blank = false) regexp = '' format_string.scan(/([^%]*)(?:%([A-Za-z%]))?/) do |literal, variable| regexp << Regexp.quote(literal) if variable if TIMESTAMP_PARTS.key?(variable) regexp << TIMESTAMP_PARTS[variable] else fai...
Create a regular expression for a timestamp, generated by a strftime call. Provide the format string to construct a matching regular expression. Set blank to true to allow and empty string, or set blank to a string to set a substitute for the nil value.
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/file_format.rb#L143-L157
module CommonRegularExpressions TIMESTAMP_PARTS = { 'a' => '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)', 'b' => '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)', 'y' => '\d{2}', 'Y' => '\d{4}', 'm' => '\d{2}', 'd' => '\d{2}', 'H' => '\d{2}', 'M' => '\d{2}', 'S' => '\d{2}', 'k' => '(?:\d| )\d', ...
weshatheleopard/rubyXL
lib/rubyXL/convenience_methods/cell.rb
RubyXL.CellConvenienceMethods.change_font_size
ruby
def change_font_size(font_size = 10) validate_worksheet raise 'Argument must be a number' unless font_size.is_a?(Integer) || font_size.is_a?(Float) font = get_cell_font.dup font.set_size(font_size) update_font_references(font) end
Changes font size of cell
train
https://github.com/weshatheleopard/rubyXL/blob/e61d78de9486316cdee039d3590177dc05db0f0c/lib/rubyXL/convenience_methods/cell.rb#L167-L174
module CellConvenienceMethods def change_contents(data, formula_expression = nil) validate_worksheet if formula_expression then self.datatype = nil self.formula = RubyXL::Formula.new(:expression => formula_expression) else self.datatype = case data ...
projectcypress/health-data-standards
lib/hqmf-parser/2.0/types.rb
HQMF2.Value.to_model
ruby
def to_model HQMF::Value.new(type, unit, value, inclusive?, derived?, expression) end
Generates this classes hqmf-model equivalent
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/types.rb#L106-L108
class Value include HQMF2::Utilities attr_reader :type, :unit, :value def initialize(entry, default_type = 'PQ', force_inclusive = false, _parent = nil) @entry = entry @type = attr_val('./@xsi:type') || default_type @unit = attr_val('./@unit') @value = attr_val('./@value') ...
Falkor/falkorlib
lib/falkorlib/common.rb
FalkorLib.Common.normalized_path
ruby
def normalized_path(dir = Dir.pwd, options = {}) rootdir = (FalkorLib::Git.init?(dir)) ? FalkorLib::Git.rootdir(dir) : dir path = dir path = Dir.pwd if dir == '.' path = File.join(Dir.pwd, dir) unless (dir =~ /^\// || (dir == '.')) if (options[:relative] || options[:relative_to]) r...
normalize_path Normalize a path and return the absolute path foreseen Ex: '.' return Dir.pwd Supported options: * :relative [boolean] return relative path to the root dir
train
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L479-L490
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...
hashicorp/vault-ruby
lib/vault/api/auth_token.rb
Vault.AuthToken.lookup_accessor
ruby
def lookup_accessor(accessor, options = {}) headers = extract_headers!(options) json = client.post("/v1/auth/token/lookup-accessor", JSON.fast_generate( accessor: accessor, ), headers) return Secret.decode(json) end
Lookup information about the given token accessor. @example Vault.auth_token.lookup_accessor("acbd-...") #=> #<Vault::Secret lease_id=""> @param [String] accessor @param [Hash] options
train
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L126-L132
class AuthToken < Request # Lists all token accessors. # # @example Listing token accessors # result = Vault.auth_token.accessors #=> #<Vault::Secret> # result.data[:keys] #=> ["476ea048-ded5-4d07-eeea-938c6b4e43ec", "bb00c093-b7d3-b0e9-69cc-c4d85081165b"] # # @return [Array<Secret>] ...
ikayzo/SDL.rb
lib/sdl4r/tag.rb
SDL4R.Tag.remove_attribute
ruby
def remove_attribute(namespace, key = nil) namespace, key = to_nns namespace, key attributes = @attributesByNamespace[namespace] return attributes.nil? ? nil : attributes.delete(key) end
remove_attribute(key) remove_attribute(namespace, key) Removes the attribute, whose name and namespace are specified. _key_:: name of the removed atribute _namespace_:: namespace of the removed attribute (equal to "", default namespace, by default) Returns the value of the removed attribute or +nil+ if it did...
train
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L615-L619
class Tag # the name of this Tag # attr_reader :name # the namespace of this Tag or an empty string when there is no namespace (i.e. default # namespace). # attr_reader :namespace # Convenient method to check and handle a pair of parameters namespace/name where, in some ...
lostisland/faraday
lib/faraday/encoders/nested_params_encoder.rb
Faraday.DecodeMethods.dehash
ruby
def dehash(hash, depth) hash.each do |key, value| hash[key] = dehash(value, depth + 1) if value.is_a?(Hash) end if depth.positive? && !hash.empty? && hash.keys.all? { |k| k =~ /^\d+$/ } hash.sort.map(&:last) else hash end end
Internal: convert a nested hash with purely numeric keys into an array. FIXME: this is not compatible with Rack::Utils.parse_nested_query @!visibility private
train
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/encoders/nested_params_encoder.rb#L145-L155
module DecodeMethods # @param query [nil, String] # # @return [Array<Array, String>] the decoded params # # @raise [TypeError] if the nesting is incorrect def decode(query) return nil if query.nil? params = {} query.split('&').each do |pair| next if pair.empty? ...
alexreisner/geocoder
lib/geocoder/lookups/latlon.rb
Geocoder::Lookup.Latlon.query_url_params
ruby
def query_url_params(query) if query.reverse_geocode? { :token => configuration.api_key, :lat => query.coordinates[0], :lon => query.coordinates[1] }.merge(super) else { :token => configuration.api_key, :address => query.sanitized_tex...
---------------------------------------------------------------
train
https://github.com/alexreisner/geocoder/blob/e087dc2759264ee6f307b926bb2de4ec2406859e/lib/geocoder/lookups/latlon.rb#L43-L56
class Latlon < Base def name "LatLon.io" end def required_api_key_parts ["api_key"] end private # --------------------------------------------------------------- def base_query_url(query) "#{protocol}://latlon.io/api/v1/#{'reverse_' if query.reverse_geocode?}geocode?" ...
sds/haml-lint
lib/haml_lint/document.rb
HamlLint.Document.convert_tree
ruby
def convert_tree(haml_node, parent = nil) new_node = @node_transformer.transform(haml_node) new_node.parent = parent new_node.children = haml_node.children.map do |child| convert_tree(child, new_node) end new_node end
Converts a HAML parse tree to a tree of {HamlLint::Tree::Node} objects. This provides a cleaner interface with which the linters can interact with the parse tree. @param haml_node [Haml::Parser::ParseNode] @param parent [Haml::Tree::Node] @return [Haml::Tree::Node]
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/document.rb#L78-L87
class Document # File name given to source code parsed from just a string. STRING_SOURCE = '(string)' # @return [HamlLint::Configuration] Configuration used to parse template attr_reader :config # @return [String] Haml template file path attr_reader :file # @return [HamlLint::Tree::Node...
amatsuda/active_decorator
lib/active_decorator/decorator.rb
ActiveDecorator.Decorator.decorator_for
ruby
def decorator_for(model_class) return @@decorators[model_class] if @@decorators.key? model_class decorator_name = "#{model_class.name}#{ActiveDecorator.config.decorator_suffix}" d = Object.const_get decorator_name, false unless Class === d d.send :include, ActiveDecorator::Helpers ...
Returns a decorator module for the given class. Returns `nil` if no decorator module was found.
train
https://github.com/amatsuda/active_decorator/blob/e7cfa764e657ea8bbb4cbe92cb220ee67ebae58e/lib/active_decorator/decorator.rb#L68-L87
class Decorator include Singleton def initialize @@decorators = {} end # Decorates the given object. # Plus, performs special decoration for the classes below: # Array: decorates its each element # Hash: decorates its each value # AR::Relation: decorates its each record l...
giraffi/zcloudjp
lib/zcloudjp/client.rb
Zcloudjp.Client.method_missing
ruby
def method_missing(method, *args, &block) self.class.class_eval do attr_accessor method.to_sym # Defined a method according to the given method name define_method method.to_sym do obj = OpenStruct.new(request_options: @request_options) obj.extend Zcloudjp.const_get(met...
Defines the method if not defined yet.
train
https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/client.rb#L33-L47
class Client include HTTParty format :json attr_reader :base_uri, :api_key def initialize(options={}) @api_key = options.delete(:api_key) || ENV['ZCLOUDJP_API_KEY'] @base_uri = options[:endpoint] || "https://my.z-cloud.jp" unless @api_key; raise ArgumentError, "options[:api_key] r...
rossf7/elasticrawl
lib/elasticrawl/cluster.rb
Elasticrawl.Cluster.create_job_flow
ruby
def create_job_flow(job, emr_config = nil) config = Config.new Elasticity.configure do |c| c.access_key = config.access_key_id c.secret_key = config.secret_access_key end job_flow = Elasticity::JobFlow.new job_flow.name = "Job: #{job.job_name} #{job.job_desc}" job_f...
Returns a configured job flow to the calling job.
train
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L12-L29
class Cluster def initialize @master_group = instance_group('master') @core_group = instance_group('core') @task_group = instance_group('task') if has_task_group? end # Returns a configured job flow to the calling job. # Describes the instances that will be launched. This is used...
zed-0xff/zpng
lib/zpng/color.rb
ZPNG.Color.to_ansi
ruby
def to_ansi return to_depth(8).to_ansi if depth != 8 a = ANSI_COLORS.map{|c| self.class.const_get(c.to_s.upcase) } a.map!{ |c| self.euclidian(c) } ANSI_COLORS[a.index(a.min)] end
convert to ANSI color name
train
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L142-L147
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...
forward3d/rbhive
lib/rbhive/t_c_l_i_connection.rb
RBHive.TCLIConnection.fetch_rows
ruby
def fetch_rows(op_handle, orientation = :first, max_rows = 1000) fetch_req = prepare_fetch_results(op_handle, orientation, max_rows) fetch_results = @client.FetchResults(fetch_req) raise_error_if_failed!(fetch_results) rows = fetch_results.results.rows TCLIResultSet.new(rows, TCLISchemaDef...
Pull rows from the query result
train
https://github.com/forward3d/rbhive/blob/a630b57332f2face03501da3ecad2905c78056fa/lib/rbhive/t_c_l_i_connection.rb#L300-L306
class TCLIConnection attr_reader :client def initialize(server, port = 10_000, options = {}, logger = StdOutLogger.new) options ||= {} # backwards compatibility raise "'options' parameter must be a hash" unless options.is_a?(Hash) if options[:transport] == :sasl and options[:sasl_par...
sosedoff/lxc-ruby
lib/lxc/container.rb
LXC.Container.clone_to
ruby
def clone_to(target) raise ContainerError, "Container does not exist." unless exists? if LXC.container(target).exists? raise ContainerError, "New container already exists." end LXC.run("clone", "-o", name, "-n", target) LXC.container(target) end
Clone to a new container from self @param [String] target name of new container @return [LXC::Container] new container instance
train
https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L187-L196
class Container attr_accessor :name # Initialize a new LXC::Container instance # @param [String] name container name # @return [LXC::Container] container instance def initialize(name) @name = name end # Get container attributes hash # @return [Hash] def to_hash status...
charypar/cyclical
lib/cyclical/rules/monthly_rule.rb
Cyclical.MonthlyRule.aligned?
ruby
def aligned?(time, base) return false unless ((12 * base.year + base.mon) - (12 * time.year + time.mon)) % @interval == 0 return false unless [time.hour, time.min, time.sec] == [base.hour, base.min, base.sec] # the shortest filter we support is for days return false unless base.day == time.day || mont...
check if time is aligned to a base time, including interval check
train
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/rules/monthly_rule.rb#L8-L14
class MonthlyRule < Rule # check if time is aligned to a base time, including interval check # default step of the rule def step @interval.months end protected def potential_next(current, base) candidate = super(current, base) rem = ((12 * base.year + base.mon) - (12 * ...
altabyte/ebay_trader
lib/ebay_trader/xml_builder.rb
EbayTrader.XMLBuilder.node
ruby
def node(name, args, &block) content = get_node_content(args) options = format_node_attributes(get_node_attributes(args)) @_segments ||= [] @_segments << "#{indent_new_line}<#{name}#{options}>#{content}" if block_given? @depth += 1 instance_eval(&block) @depth -= 1...
Create an XML node @param [String|Symbol] name the name of the XML element (ul, li, strong, etc...) @param [Array] args Can contain a String of text or a Hash of attributes @param [Block] block An optional block which will further nest XML
train
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L54-L68
class XMLBuilder attr_reader :context, :xml, :depth, :tab_width def initialize(args = {}) @xml = '' @depth = 0 @tab_width = (args[:tab_width] || 0).to_i end # Catch-all method to avoid having to create individual methods for each XML tag name. def method_missing(method_name, *...
couchrest/couchrest_extended_document
lib/couchrest/extended_document.rb
CouchRest.ExtendedDocument.destroy
ruby
def destroy(bulk=false) caught = catch(:halt) do _run_destroy_callbacks do result = database.delete_doc(self, bulk) if result['ok'] self.delete('_rev') self.delete('_id') end result['ok'] end end end
Deletes the document from the database. Runs the :destroy callbacks. Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the document to be saved to a new <tt>_id</tt>.
train
https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/extended_document.rb#L247-L258
class ExtendedDocument < Document VERSION = "1.0.0" include CouchRest::Mixins::Callbacks include CouchRest::Mixins::DocumentQueries include CouchRest::Mixins::Views include CouchRest::Mixins::DesignDoc include CouchRest::Mixins::ExtendedAttachments include CouchRest::Mixins::ClassPro...
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_post
ruby
def get_post(user_name, intra_hash) response = @conn.get @url_post.expand({ :user_name => user_name, :intra_hash => intra_hash, :format => @format ...
Initializes the client with the given credentials. @param user_name [String] the name of the user account used for accessing the API @param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1 @param format [String] The requested return fo...
train
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L78-L90
class API # Initializes the client with the given credentials. # # @param user_name [String] the name of the user account used for accessing the API # @param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1 # # @p...