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 |
|---|---|---|---|---|---|---|---|---|
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtPubkey.derive | ruby | def derive(number)
new_key = ExtPubkey.new
new_key.depth = depth + 1
new_key.number = number
new_key.parent_fingerprint = fingerprint
raise 'hardened key is not support' if number > (HARDENED_THRESHOLD - 1)
data = pub.htb << [number].pack('N')
l = Bitcoin.hmac_sha512(chain_code... | derive child key | train | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L254-L270 | 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... |
caruby/core | lib/caruby/database/persistable.rb | CaRuby.Persistable.saved_attributes_to_fetch | ruby | def saved_attributes_to_fetch(operation)
# only fetch a create, not an update (note that subclasses can override this condition)
if operation.type == :create or operation.autogenerated? then
# Filter the class saved fetch attributes for content.
self.class.saved_attributes_to_fetch.select { ... | Returns this domain object's attributes which must be fetched to reflect the database state.
This default implementation returns the {Propertied#autogenerated_logical_dependent_attributes}
if this domain object does not have an identifier, or an empty array otherwise.
Subclasses can override to relax or restrict the... | train | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L328-L336 | module Persistable
# @return [{Symbol => Object}] the content value hash at the point of the last snapshot
attr_reader :snapshot
# @param [Jinx::Resource, <Jinx::Resource>, nil] obj the object(s) to check
# @return [Boolean] whether the given object(s) have an identifier
def self.saved?(obj... |
marcbowes/UsingYAML | lib/using_yaml.rb | UsingYAML.ClassMethods.using_yaml_file | ruby | def using_yaml_file(filename)
# Define an reader for filename such that the corresponding
# YAML file is loaded. Example: using_yaml_file(:foo) will look
# for foo.yml in the specified path.
define_method(filename) do
# Work out the absolute path for the filename and get a handle
... | Special attr_accessor for the suppiled +filename+ such that
files are intelligently loaded/written to disk.
using_yaml_file(:foo) # => attr_accessor(:foo) + some magic
If class Example is setup with the above, then:
example = Example.new
example.foo # => loads from foo.yml
example.foo.bar # => eq... | train | https://github.com/marcbowes/UsingYAML/blob/4485476ad0ad14850d41c8ed61673f7b08b9f007/lib/using_yaml.rb#L133-L171 | module ClassMethods
# Used to configure UsingYAML for a class by defining what files
# should be loaded and from where.
#
# include UsingYAML
# using_yaml :foo, :bar, :path => "/some/where"
#
# +args+ can contain either filenames or a hash which specifices a
# path which contains t... |
koraktor/metior | lib/metior/repository.rb | Metior.Repository.file_stats | ruby | def file_stats(range = current_branch)
support! :file_stats
stats = {}
commits(range).each_value do |commit|
commit.added_files.each do |file|
stats[file] = { :modifications => 0 } unless stats.key? file
stats[file][:added_date] = commit.authored_date
stats[file]... | This evaluates basic statistics about the files in a given commit range.
@example
repo.file_stats
=> {
'a_file.rb' => {
:added_date => Tue Mar 29 16:13:47 +0200 2011,
:deleted_date => Sun Jun 05 12:56:18 +0200 2011,
:last_modified_date => Thu Apr 21 20:08:00 +0200 2011,
... | train | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L179-L201 | class Repository
include AutoIncludeAdapter
# @return [String] The file system path of this repository
attr_reader :path
# Creates a new repository instance with the given file system path
#
# @param [String] path The file system path of the repository
def initialize(path)
@actors... |
iyuuya/jkf | lib/jkf/parser/csa.rb | Jkf::Parser.Csa.parse_moves | ruby | def parse_moves
s0 = @current_pos
s1 = parse_firstboard
if s1 != :failed
s2 = []
s3 = parse_move
while s3 != :failed
s2 << s3
s3 = parse_move
end
parse_comments
@reported_pos = s0
s0 = s2.unshift(s1)
else
@curren... | moves : firstboard move* comment* | train | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/csa.rb#L440-L458 | class Csa < Base
protected
# kifu : csa2 | csa1
def parse_root
@input += "\n" unless @input[-1] =~ /\n|\r|,/ # FIXME
s0 = parse_csa2
s0 = parse_csa1 if s0 == :failed
s0
end
# csa2 : version22 information? initialboard moves?
def parse_csa2
s0 = @current_pos
... |
intridea/hashie | lib/hashie/mash.rb | Hashie.Mash.custom_reader | ruby | def custom_reader(key)
default_proc.call(self, key) if default_proc && !key?(key)
value = regular_reader(convert_key(key))
yield value if block_given?
value
end | Retrieves an attribute set in the Mash. Will convert
any key passed in to a string before retrieving. | train | https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/mash.rb#L144-L149 | class Mash < Hash
include Hashie::Extensions::PrettyInspect
include Hashie::Extensions::RubyVersionCheck
ALLOWED_SUFFIXES = %w[? ! = _].freeze
class CannotDisableMashWarnings < StandardError
def initialize
super(
'You cannot disable warnings on the base Mash class. ' \
... |
kmuto/review | lib/review/latexbuilder.rb | ReVIEW.LATEXBuilder.inline_list | ruby | def inline_list(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
macro('reviewlistref', I18n.t('format_number_without_chapter', [chapter.list(id).number]))
else
macro('reviewlistref', I18n.t('format_number', [get_chap(chapter), chapter.list(id).number]))
end
... | FIXME: use TeX native label/ref. | train | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/latexbuilder.rb#L934-L943 | class LATEXBuilder < Builder
include LaTeXUtils
include TextUtils
%i[dtp hd_chap].each do |e|
Compiler.definline(e)
end
Compiler.defsingle(:latextsize, 1)
def extname
'.tex'
end
def builder_init_file
@chapter.book.image_types = %w[.ai .eps .pdf .tif .tiff .png .bm... |
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.find_id_metadata | ruby | def find_id_metadata(collection_name)
collection_data = @collections.fetch(collection_name)
class_metadata = @class_metadata.fetch(collection_data[:type].to_s)
key = class_metadata.select{|k,h| h.is_key }.collect{|k,h| h.name }[0]
class_metadata[key]
end | Finds the metadata associated with the given collection's first id property
Remarks: This is used for single item lookup queries using the ID, e.g. Products(1), not complex primary keys
@param [String] collection_name the name of the collection | train | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L199-L204 | 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... |
PierreRambaud/gemirro | lib/gemirro/cache.rb | Gemirro.Cache.cache | ruby | def cache(key)
key_hash = key2hash(key)
read(key_hash) || (write(key_hash, yield) if block_given?)
end | Cache data
@param [String] key
@return [Mixed] | train | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/cache.rb#L54-L57 | class Cache
attr_reader :root_path
##
# Initialize cache root path
#
# @param [String] path
#
def initialize(path)
@root_path = path
create_root_path
end
##
# Create root path
#
def create_root_path
FileUtils.mkdir_p(@root_path)
end
##
#... |
kontena/kontena | server/app/services/docker/streaming_executor.rb | Docker.StreamingExecutor.start | ruby | def start(ws)
@ws = ws
@ws.on(:message) do |event|
on_websocket_message(event.data)
end
@ws.on(:error) do |exc|
warn exc
end
@ws.on(:close) do |event|
on_websocket_close(event.code, event.reason)
end
started!
end | Does not raise.
@param ws [Faye::Websocket] | train | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/services/docker/streaming_executor.rb#L137-L153 | class StreamingExecutor
include Logging
# @param [Container] container
# @param [Boolean] shell
# @param [Boolean] stdin
# @param [Boolean] tty
def initialize(container, shell: false, interactive: false, tty: false)
@container = container
@shell = shell
@interactive = intera... |
tbpgr/tudu | lib/tudu_dsl.rb | Tudu.Dsl.target_type | ruby | def target_type(target_type)
return if target_type.nil?
return unless [String, Symbol].include?(target_type.class)
target_type = target_type.to_sym if target_type.instance_of? String
return unless TARGET_TYPES.include? target_type
@_target_type = target_type
end | == initialize Dsl
== initialize Dsl
=== Params
- target_type: target notice type | train | https://github.com/tbpgr/tudu/blob/4098054b836c0d0b18f89ae71a449e2fe26a0647/lib/tudu_dsl.rb#L27-L33 | class Dsl
# == TARGET_TYPES
# notice target types
# === types
#- none: no notice
#- mail: mail notice
TARGET_TYPES = { none: :none, mail: :mail }
# == notice target type
attr_accessor :_target_type
# == notice targets
attr_accessor :_targets
# == initialize Dsl
def ini... |
kikonen/capybara-ng | lib/angular/dsl.rb | Angular.DSL.ng_repeater_column | ruby | def ng_repeater_column(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_repeater_columns(repeater, binding, opt)[row]
end | Node for column binding value in row
@param opt
- :row
- :root_selector
- :wait
@return nth node | train | https://github.com/kikonen/capybara-ng/blob/a24bc9570629fe2bb441763803dd8aa0d046d46d/lib/angular/dsl.rb#L309-L313 | module DSL
def ng
Capybara.current_session.ng
end
#
# Get or set selector to find ng-app for current capybara test session
#
# TIP: try using '[ng-app]', which will find ng-app as attribute anywhere.
#
# @param root_selector if nil then return current value without change
# @return test specific ... |
xi-livecode/xi | lib/xi/pattern.rb | Xi.Pattern.each_event | ruby | def each_event(cycle=0)
return enum_for(__method__, cycle) unless block_given?
EventEnumerator.new(self, cycle).each { |v, s, d, i| yield v, s, d, i }
end | Calls the given block once for each event, passing its value, start
position, duration and iteration as parameters.
+cycle+ can be any number, even if there is no event that starts exactly
at that moment. It will start from the next event.
If no block is given, an enumerator is returned instead.
Enumeration lo... | train | https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L194-L197 | class Pattern
extend Generators
include Transforms
# Array or Proc that produces values or events
attr_reader :source
# Event delta in terms of cycles (default: 1)
attr_reader :delta
# Hash that contains metadata related to pattern usage
attr_reader :metadata
# Size of pattern... |
mongodb/mongoid | lib/mongoid/serializable.rb | Mongoid.Serializable.relation_options | ruby | def relation_options(inclusions, options, name)
if inclusions.is_a?(Hash)
inclusions[name]
else
{ except: options[:except], only: options[:only] }
end
end | Since the inclusions can be a hash, symbol, or array of symbols, this is
provided as a convenience to parse out the options.
@example Get the association options.
document.relation_names(:include => [ :addresses ])
@param [ Hash, Symbol, Array<Symbol> ] inclusions The inclusions.
@param [ Hash ] options The op... | train | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/serializable.rb#L164-L170 | 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... |
dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.count | ruby | def count ids: nil, tags: nil, dom: nil, active: true
f = Helpers.filter(ids: ids, tags: tags, dom: dom)
a = Helpers.pending_or_waiting(active)
Execute.task_popen3(*@override_a, f, a, "count") do |i, o, e, t|
return Integer(o.read)
end
end | Count the number of tasks that match a given filter. Faster than counting
an array returned by Controller#all or Controller#some.
@param ids [Array<Range, Fixnum, String>, String, Range, Fixnum]
@param tags [Array<String>, String]
@param dom [Array<String>, String]
@param active [Boolean] return only pending & wa... | train | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L124-L130 | module Controller
extend self
# Retrieves the current task list from the TaskWarrior database. Defaults
# to just show active (waiting & pending) tasks, which is usually what is
# exposed to the end user through the default reports. To see everything
# including completed, deleted, and parent rec... |
sunspot/sunspot | sunspot/lib/sunspot/text_field_setup.rb | Sunspot.TextFieldSetup.field | ruby | def field(name)
fields = @setup.text_fields(name)
if fields
if fields.length == 1
fields.first
else
raise(
Sunspot::UnrecognizedFieldError,
"The text field with name #{name} has incompatible configurations for the classes #{@setup.type_names.join('... | :nodoc:
Return a text field with the given name. Duck-type compatible with
Setup and CompositeSetup, but return text fields instead. | train | https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/text_field_setup.rb#L15-L27 | class TextFieldSetup #:nodoc:
def initialize(setup)
@setup = setup
end
#
# Return a text field with the given name. Duck-type compatible with
# Setup and CompositeSetup, but return text fields instead.
#
end
|
wvanbergen/request-log-analyzer | lib/request_log_analyzer/source/log_parser.rb | RequestLogAnalyzer::Source.LogParser.update_current_request | ruby | def update_current_request(request_data, &block) # :yields: request
if alternative_header_line?(request_data)
if @current_request
@current_request << request_data
else
@current_request = @file_format.request(request_data)
end
elsif header_line?(request_data)
... | Combines the different lines of a request into a single Request object. It will start a
new request when a header line is encountered en will emit the request when a footer line
is encountered.
Combining the lines is done using heuristics. Problems can occur in this process. The
current parse strategy defines how ... | train | https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/source/log_parser.rb#L285-L320 | class LogParser < Base
include Enumerable
# The maximum number of bytes to read from a line.
DEFAULT_MAX_LINE_LENGTH = 8096
DEFAULT_LINE_DIVIDER = "\n"
# The default parse strategy that will be used to parse the input.
DEFAULT_PARSE_STRATEGY = 'assume-correct'
# All available parse str... |
forward3d/rbhive | lib/rbhive/t_c_l_i_connection.rb | RBHive.TCLIConnection.explain | ruby | def explain(query)
rows = []
fetch_in_batch("EXPLAIN " + query) do |batch|
rows << batch.map { |b| b[:Explain] }
end
ExplainResult.new(rows.flatten)
end | Performs a explain on the supplied query on the server, returns it as a ExplainResult.
(Only works on 0.12 if you have this patch - https://issues.apache.org/jira/browse/HIVE-5492) | train | https://github.com/forward3d/rbhive/blob/a630b57332f2face03501da3ecad2905c78056fa/lib/rbhive/t_c_l_i_connection.rb#L310-L316 | 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... |
Sage/fudge | lib/fudge/cli.rb | Fudge.Cli.init | ruby | def init
generator = Fudge::Generator.new(Dir.pwd)
msg = generator.write_fudgefile
shell.say msg
end | Initalizes the blank Fudgefile | train | https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/cli.rb#L8-L12 | class Cli < Thor
desc "init", "Initialize a blank Fudgefile"
# Initalizes the blank Fudgefile
desc "build [BUILD_NAME]",
"Run a build with the given name (default: 'default')"
method_option :callbacks, :type => :boolean, :default => false
method_option :time, :type => :boolean, :default =>... |
projectcypress/health-data-standards | lib/hqmf-parser/2.0/data_criteria_helpers/dc_base_extract.rb | HQMF2.DataCriteriaBaseExtractions.all_subset_operators | ruby | def all_subset_operators
@entry.xpath('./*/cda:excerpt', HQMF2::Document::NAMESPACES).collect do |subset_operator|
SubsetOperator.new(subset_operator)
end
end | Extracts all subset operators contained in the entry xml | train | https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/data_criteria_helpers/dc_base_extract.rb#L56-L60 | class DataCriteriaBaseExtractions
include HQMF2::Utilities
CONJUNCTION_CODE_TO_DERIVATION_OP = {
'OR' => 'UNION',
'AND' => 'XPRODUCT'
}
def initialize(entry)
@entry = entry
end
# Extract the local variable name (held in the value of the localVariableName element)
def ex... |
murb/workbook | lib/workbook/row.rb | Workbook.Row.+ | ruby | def +(row)
rv = super(row)
rv = Workbook::Row.new(rv) unless rv.class == Workbook::Row
return rv
end | plus
@param [Workbook::Row, Array] row to add
@return [Workbook::Row] a new row, not linked to the table | train | https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/row.rb#L82-L86 | 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... |
jferris/effigy | lib/effigy/view.rb | Effigy.View.html | ruby | def html(selector, inner_html)
select(selector).each do |node|
node.inner_html = inner_html
end
end | Replaces the contents of the selected elements with live markup.
@param [String] selector a CSS or XPath string describing the elements to
transform
@param [String] inner_html the new contents of the selected elements. Markup is
@example
html('p', '<b>Welcome!</b>')
find('p').html('<b>Welcome!</b>') | train | https://github.com/jferris/effigy/blob/366ad3571b0fc81f681472eb0ae911f47c60a405/lib/effigy/view.rb#L155-L159 | class View
# Replaces the text content of the selected elements.
#
# Markup in the given content is escaped. Use {#html} if you want to
# replace the contents with live markup.
#
# @param [String] selector a CSS or XPath string describing the elements to
# transform
# @param [String]... |
thelabtech/questionnaire | app/models/qe/element.rb | Qe.Element.duplicate | ruby | def duplicate(page, parent = nil)
new_element = self.class.new(self.attributes)
case parent.class.to_s
when ChoiceField
new_element.conditional_id = parent.id
when QuestionGrid, QuestionGridWithTotal
new_element.question_grid_id = parent.id
end
new_element.save(:valid... | copy an item and all it's children | train | https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/models/qe/element.rb#L116-L133 | class Element < ActiveRecord::Base
# self.table_name = "#{self.table_name}"
belongs_to :question_grids, :foreign_key => "question_grid_id"
belongs_to :choice_fields, :foreign_key => "conditional_id"
self.inheritance_column = :kind
has_many :page_elements, :dependent => :destroy
has_m... |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.delete | ruby | def delete(entry)
return true if !entry.id
@lock.synchronize do
with_index_lock do
return true if !@machines[entry.id]
# If we don't have the lock, then we need to acquire it.
if !@machine_locks[entry.id]
raise "Unlocked delete on machine: #{entry.id}"
... | Initializes a MachineIndex at the given file location.
@param [Pathname] data_dir Path to the directory where data for the
index can be stored. This folder should exist and must be writable.
Deletes a machine by UUID.
The machine being deleted with this UUID must either be locked
by this index or must be unloc... | train | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L64-L87 | class MachineIndex
include Enumerable
# Initializes a MachineIndex at the given file location.
#
# @param [Pathname] data_dir Path to the directory where data for the
# index can be stored. This folder should exist and must be writable.
def initialize(data_dir)
@data_dir = data_dir
... |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.leave_image_comment | ruby | def leave_image_comment(image, comment)
configure_comment_connection
Instagram.client.create_media_comment(image.external_identifier, comment)
end | Leave a comment containing the donor agreement on an Instagram image
@param image [type] An Image model object from the Instagram service
@raise [Exception] If a comment submission fails
@authenticated true
@return [Hashie::Mash] Instagram response | train | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L275-L278 | class InstagramHarvester
#
# Configure the Instagram class in preparation requests.
#
# @options opts [String] :client_id (Lentil::Engine::APP_CONFIG["instagram_client_id"]) The Instagram client ID
# @options opts [String] :client_secret (Lentil::Engine::APP_CONFIG["instagram_client_secret"]) The... |
marcinwyszynski/statefully | lib/statefully/state.rb | Statefully.State.respond_to_missing? | ruby | def respond_to_missing?(name, _include_private = false)
str_name = name.to_s
key?(name.to_sym) || %w[? !].any?(&str_name.method(:end_with?)) || super
end | Companion to `method_missing`
This method reeks of :reek:BooleanParameter.
@param name [Symbol|String]
@param _include_private [Boolean]
@return [Boolean]
@api private | train | https://github.com/marcinwyszynski/statefully/blob/affca50625a26229e1af7ee30f2fe12bf9cddda9/lib/statefully/state.rb#L295-L298 | class State
include Enumerable
extend Forwardable
# Return the previous {State}
#
# @return [State]
# @api public
# @example
# Statefully::State.create.previous
# => #<Statefully::State::None>
#
# Statefully::State.create.succeed.previous
# => #<Statefully::Sta... |
mongodb/mongoid | lib/mongoid/attributes.rb | Mongoid.Attributes.typed_value_for | ruby | def typed_value_for(key, value)
fields.key?(key) ? fields[key].mongoize(value) : value.mongoize
end | Return the typecasted value for a field.
@example Get the value typecasted.
person.typed_value_for(:title, :sir)
@param [ String, Symbol ] key The field name.
@param [ Object ] value The uncast value.
@return [ Object ] The cast value.
@since 1.0.0 | train | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/attributes.rb#L287-L289 | module Attributes
extend ActiveSupport::Concern
include Nested
include Processing
include Readonly
attr_reader :attributes
alias :raw_attributes :attributes
# Determine if an attribute is present.
#
# @example Is the attribute present?
# person.attribute_present?("title")
... |
mongodb/mongo-ruby-driver | lib/mongo/session.rb | Mongo.Session.start_transaction | ruby | def start_transaction(options = nil)
if options
Lint.validate_read_concern_option(options[:read_concern])
end
check_if_ended!
if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error... | Places subsequent operations in this session into a new transaction.
Note that the transaction will not be started on the server until an
operation is performed after start_transaction is called.
@example Start a new transaction
session.start_transaction(options)
@param [ Hash ] options The options for the tr... | train | https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L580-L602 | 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... |
PierreRambaud/gemirro | lib/gemirro/mirror_directory.rb | Gemirro.MirrorDirectory.add_file | ruby | def add_file(name, content)
full_path = File.join(@path, name)
file = MirrorFile.new(full_path)
file.write(content)
file
end | Creates a new file with the given name and content.
@param [String] name
@param [String] content
@return [Gem::MirrorFile] | train | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/mirror_directory.rb#L39-L46 | class MirrorDirectory
attr_reader :path
##
# @param [String] path
#
def initialize(path)
@path = path
end
##
# Creates directory or directories with the given path.
#
# @param [String] dir_path
# @return [Gemirro::MirrorDirectory]
#
def add_directory(dir_pat... |
sunspot/sunspot | sunspot/lib/sunspot/setup.rb | Sunspot.Setup.add_field_factory | ruby | def add_field_factory(name, type, options = {}, &block)
stored, more_like_this = options[:stored], options[:more_like_this]
field_factory = FieldFactory::Static.new(name, type, options, &block)
@field_factories[field_factory.signature] = field_factory
@field_factories_cache[field_factory.name] =... | Add field factory for scope/ordering | train | https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/setup.rb#L28-L39 | class Setup #:nodoc:
attr_reader :class_object_id
def initialize(clazz)
@class_object_id = clazz.object_id
@class_name = clazz.name
@field_factories, @text_field_factories, @dynamic_field_factories,
@field_factories_cache, @text_field_factories_cache,
@dynamic_field_factories... |
chikamichi/logg | lib/logg/core.rb | Logg.Dispatcher.method_missing | ruby | def method_missing(meth, *args, &block)
@namespace = meth.to_s
@message = (args.first.to_s == 'debug') ? nil : args.first.to_s
self.send :output!
end | The Dispatcher default behavior relies on #method_missing. It sets both the
message and a namespace, then auto-sends the order to output. | train | https://github.com/chikamichi/logg/blob/fadc70f80ee48930058db131888aabf7da21da2d/lib/logg/core.rb#L85-L89 | class Dispatcher
class Render
# Render a template. Just a mere proxy for Tilt::Template#render method,
# the first argument being the filepath or file, and the latter,
# the usual arguments for Tilt's #render.
#
# @param [String, #path, #realpath] path filepath or an object behaving
... |
metanorma/relaton | lib/relaton/db.rb | Relaton.Db.to_xml | ruby | def to_xml
db = @local_db || @db || return
Nokogiri::XML::Builder.new(encoding: "UTF-8") do |xml|
xml.documents do
xml.parent.add_child db.all.join(" ")
end
end.to_xml
end | list all entries as a serialization
@return [String] | train | https://github.com/metanorma/relaton/blob/2fac19da2f3ef3c30b8e8d8815a14d2115df0be6/lib/relaton/db.rb#L90-L97 | class Db
SUPPORTED_GEMS = %w[isobib ietfbib gbbib iecbib nistbib].freeze
# @param global_cache [String] directory of global DB
# @param local_cache [String] directory of local DB
def initialize(global_cache, local_cache)
register_gems
@registry = Relaton::Registry.instance
@db = ope... |
Falkor/falkorlib | lib/falkorlib/git/base.rb | FalkorLib.Git.list_branch | ruby | def list_branch(path = Dir.pwd)
cg = MiniGit::Capturing.new(path)
res = cg.branch :a => true
res = res.split("\n")
# Eventually reorder to make the first element of the array the current branch
i = res.find_index { |e| e =~ /^\*\s/ }
res[0], res[i] = res[i], res[0] unless (i.nil? || ... | Get an array of the local branches present (first element is always the
current branch) | train | https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L181-L190 | module Git
module_function
## Check if a git directory has been initialized
def init?(path = Dir.pwd)
begin
MiniGit.new(path)
rescue Exception
return false
end
true
end
## Check if the repositories already holds some commits
def commits?(path)
r... |
rmagick/rmagick | ext/RMagick/extconf.rb | RMagick.Extconf.set_archflags_for_osx | ruby | def set_archflags_for_osx
archflags = []
fullpath = `which convert`
fileinfo = `file #{fullpath}`
# default ARCHFLAGS
archs = $ARCH_FLAG.scan(/-arch\s+(\S+)/).flatten
archs.each do |arch|
archflags << "-arch #{arch}" if fileinfo.include?(arch)
end
$ARCH_FLAG = ... | issue #169
set ARCHFLAGS appropriately for OSX | train | https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/ext/RMagick/extconf.rb#L232-L245 | class Extconf
require 'rmagick/version'
RMAGICK_VERS = ::Magick::VERSION
MIN_RUBY_VERS = ::Magick::MIN_RUBY_VERSION
attr_reader :headers
def initialize
@stdout = $stdout.dup
setup_paths_for_homebrew
configure_compile_options
assert_can_compile!
configure_headers
... |
mitukiii/userstream | lib/user_stream/configuration.rb | UserStream.Configuration.reset | ruby | def reset
self.consumer_key = DEFAULT_CONSUMER_KEY
self.consumer_secret = DEFAULT_CONSUMER_SECRET
self.oauth_token = DEFAULT_OAUTH_TOKEN
self.oauth_token_secret = DEFAULT_OAUTH_TOKEN_SECRET
self.endpoint = DEFAULT_ENDPOINT
self.user_agent = DEFAULT_U... | Reset all configuration options to defaults | train | https://github.com/mitukiii/userstream/blob/f37e7931f7f934422ae6cbdee10da40715c6b68b/lib/user_stream/configuration.rb#L65-L74 | module Configuration
# An array of keys in the options hash when configuring a {UserStream::API}
OPTIONS_KEYS = [
:consumer_key,
:consumer_secret,
:oauth_token,
:oauth_token_secret,
:endpoint,
:user_agent,
:timeout,
].freeze
# By default, don't set a consumer... |
zhimin/rwebspec | lib/rwebspec-watir/web_browser.rb | RWebSpec.WebBrowser.new_popup_window | ruby | def new_popup_window(options, browser = "ie")
if is_firefox?
raise "not implemented"
else
if options[:url]
Watir::IE.attach(:url, options[:url])
elsif options[:title]
Watir::IE.attach(:title, options[:title])
else
raise 'Please specify t... | Attach a Watir::IE instance to a popup window.
Typical usage
new_popup_window(:url => "http://www.google.com/a.pdf") | train | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/web_browser.rb#L510-L522 | class WebBrowser
attr_accessor :context
def initialize(base_url = nil, existing_browser = nil, options = {})
default_options = {:speed => "zippy",
:visible => true,
:highlight_colour => 'yellow',
:close_others => true
}
options = default_options.merge options
... |
state-machines/state_machines | lib/state_machines/branch.rb | StateMachines.Branch.matches_requirement? | ruby | def matches_requirement?(query, option, requirement)
!query.include?(option) || requirement.matches?(query[option], query)
end | Verifies that an option in the given query matches the values required
for that option | train | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/branch.rb#L171-L173 | class Branch
include EvalHelpers
# The condition that must be met on an object
attr_reader :if_condition
# The condition that must *not* be met on an object
attr_reader :unless_condition
# The requirement for verifying the event being matched
attr_reader :event_requirement
... |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.launch_all_nodes | ruby | def launch_all_nodes
@logger.notify("aws-sdk: launch all hosts in configuration")
ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"]
global_subnet_id = @options['subnet_id']
global_subnets = @options['subnet_ids']
if global_subnet_id and global_subnets
raise RuntimeError, 'Confi... | Create EC2 instances for all hosts, tag them, and wait until
they're running. When a host provides a subnet_id, create the
instance in that subnet, otherwise prefer a CONFIG subnet_id.
If neither are set but there is a CONFIG subnet_ids list,
attempt to create the host in each specified subnet, which might
fail d... | train | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L432-L482 | 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... |
bdwyertech/chef-rundeck2 | lib/chef-rundeck/auth.rb | ChefRunDeck.Auth.role_admin? | ruby | def role_admin?(run_list = nil)
return false unless run_list.is_a?(Array)
# => This will Authorize Anyone if the RunList is Empty or the Chef Node does not exist!!!
run_list.empty? || auth['roles'].any? { |role| run_list.any? { |r| r =~ /role\[#{role}\]/i } }
end | => Role-Based Administration | train | https://github.com/bdwyertech/chef-rundeck2/blob/5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7/lib/chef-rundeck/auth.rb#L73-L77 | module Auth
extend self
#############################
# => Authorization <= #
#############################
# => This holds the Authorization State
attr_accessor :auth
def auth
# => Define Authorization
@auth ||= reset!
end
def reset!
# => Reset Authoriz... |
algolia/algoliasearch-client-ruby | lib/algolia/index.rb | Algolia.Index.search_rules | ruby | def search_rules(query, params = {}, request_options = {})
anchoring = params[:anchoring]
context = params[:context]
page = params[:page] || params['page'] || 0
hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20
params = {
:query => query,
:page => page,
... | Search rules
@param query the query
@param params an optional hash of :anchoring, :context, :page, :hitsPerPage
@param request_options contains extra parameters to send with your query | train | https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1041-L1054 | 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... |
wvanbergen/request-log-analyzer | lib/request_log_analyzer/controller.rb | RequestLogAnalyzer.Controller.run! | ruby | def run!
# @aggregators.each{|agg| p agg}
@aggregators.each { |agg| agg.prepare }
install_signal_handlers
@source.each_request do |request|
break if @interrupted
aggregate_request(filter_request(request))
end
@aggregators.each { |agg| agg.finalize }
@output.... | Runs RequestLogAnalyzer
1. Call prepare on every aggregator
2. Generate requests from source object
3. Filter out unwanted requests
4. Call aggregate for remaning requests on every aggregator
4. Call finalize on every aggregator
5. Call report on every aggregator
6. Finalize Source | train | https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/controller.rb#L328-L359 | class Controller
attr_reader :source, :filters, :aggregators, :output, :options
# Builds a RequestLogAnalyzer::Controller given parsed command line arguments
# <tt>arguments<tt> A CommandLine::Arguments hash containing parsed commandline parameters.
def self.build_from_arguments(arguments)
opti... |
dwaite/cookiejar | lib/cookiejar/jar.rb | CookieJar.Jar.get_cookie_header | ruby | def get_cookie_header(request_uri, opts = {})
cookies = get_cookies request_uri, opts
ver = [[], []]
cookies.each do |cookie|
ver[cookie.version] << cookie
end
if ver[1].empty?
# can do a netscape-style cookie header, relish the opportunity
cookies.map(&:to_s).join ... | Given a request URI, return a string Cookie header.Cookies will be in
order per RFC 2965 - sorted by longest path length, but otherwise
unordered.
@param [String, URI] request_uri the address the HTTP request will be
sent to
@param [Hash] opts options controlling returned cookies
@option opts [Boolean] :script... | train | https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L254-L281 | class Jar
# Create a new empty Jar
def initialize
@domains = {}
end
# Given a request URI and a literal Set-Cookie header value, attempt to
# add the cookie(s) to the cookie store.
#
# @param [String, URI] request_uri the resource returning the header
# @param [String] cookie_he... |
hashicorp/vault-ruby | lib/vault/api/logical.rb | Vault.Logical.list | ruby | def list(path, options = {})
headers = extract_headers!(options)
json = client.list("/v1/#{encode_path(path)}", {}, headers)
json[:data][:keys] || []
rescue HTTPError => e
return [] if e.code == 404
raise
end | List the secrets at the given path, if the path supports listing. If the
the path does not exist, an exception will be raised.
@example
Vault.logical.list("secret") #=> [#<Vault::Secret>, #<Vault::Secret>, ...]
@param [String] path
the path to list
@return [Array<String>] | train | https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/logical.rb#L26-L33 | class Logical < Request
# List the secrets at the given path, if the path supports listing. If the
# the path does not exist, an exception will be raised.
#
# @example
# Vault.logical.list("secret") #=> [#<Vault::Secret>, #<Vault::Secret>, ...]
#
# @param [String] path
# the path t... |
koraktor/metior | lib/metior/adapter.rb | Metior::Adapter.ClassMethods.register_for | ruby | def register_for(vcs)
vcs = Metior.find_vcs vcs
vcs.register_adapter id, self
class_variable_set :@@vcs, vcs
end | Registers this adapter with a VCS
@param [Symbol] vcs_name The name of the VCS to register this adapter
with | train | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter.rb#L56-L60 | module ClassMethods
# Missing constants may indicate that the adapter is not yet initialized
#
# Trying to access either the `Actor`, `Commit` or `Repository` class
# in a adapter `Module` will trigger auto-loading first.
#
# @param [Symbol] const The symbolic name of the missing constant
... |
sds/haml-lint | lib/haml_lint/linter_selector.rb | HamlLint.LinterSelector.run_linter_on_file? | ruby | def run_linter_on_file?(config, linter, file)
linter_config = config.for_linter(linter)
if linter_config['include'].any? &&
!HamlLint::Utils.any_glob_matches?(linter_config['include'], file)
return false
end
if HamlLint::Utils.any_glob_matches?(linter_config['exclude'], file)
... | Whether to run the given linter against the specified file.
@param config [HamlLint::Configuration]
@param linter [HamlLint::Linter]
@param file [String]
@return [Boolean] | train | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter_selector.rb#L64-L77 | class LinterSelector
# Creates a selector using the given configuration and additional options.
#
# @param config [HamlLint::Configuration]
# @param options [Hash]
def initialize(config, options)
@config = config
@options = options
end
# Returns the set of linters to run again... |
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.parse_response | ruby | def parse_response(response)
check_version_and_warn(response.headers[X_KONTENA_VERSION])
if response.headers[CONTENT_TYPE] =~ JSON_REGEX
parse_json(response)
else
response.body
end
end | Parse response. If the respons is JSON, returns a Hash representation.
Otherwise returns the raw body.
@param [Excon::Response]
@return [Hash,String] | train | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L486-L494 | 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... |
radiant/radiant | app/helpers/radiant/application_helper.rb | Radiant.ApplicationHelper.pagination_for | ruby | def pagination_for(list, options={})
if list.respond_to? :total_pages
options = {
max_per_page: detail['pagination.max_per_page'] || 500,
depaginate: true
}.merge(options.symbolize_keys)
depaginate = options.delete(:depaginate) # supp... | returns the usual set of pagination links.
options are passed through to will_paginate
and a 'show all' depagination link is added if relevant. | train | https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/app/helpers/radiant/application_helper.rb#L216-L232 | module ApplicationHelper
include Radiant::Admin::RegionsHelper
def detail
Radiant::Config
end
def default_page_title
title + ' - ' + subtitle
end
def title
detail['admin.title'] || 'Radiant CMS'
end
def subtitle
detail['admin.subtitle'] || 'Publishing for Sm... |
mojombo/chronic | lib/chronic/handlers.rb | Chronic.Handlers.handle_r | ruby | def handle_r(tokens, options)
dd_tokens = dealias_and_disambiguate_times(tokens, options)
get_anchor(dd_tokens, options)
end | anchors
Handle repeaters | train | https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/handlers.rb#L432-L435 | module Handlers
module_function
# Handle month/day
def handle_m_d(month, day, time_tokens, options)
month.start = self.now
span = month.this(options[:context])
year, month = span.begin.year, span.begin.month
day_start = Chronic.time_class.local(year, month, day)
day_start = ... |
ideonetwork/lato-blog | app/controllers/lato_blog/back/categories_controller.rb | LatoBlog.Back::CategoriesController.index | ruby | def index
core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories])
# find categories to show
@categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC')
@widget_index_categories = core__widgets_index(@categories, search: '... | This function shows the list of possible categories. | train | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L9-L14 | class Back::CategoriesController < Back::BackController
before_action do
core__set_menu_active_item('blog_articles')
end
# This function shows the list of possible categories.
# This function shows a single category. It create a redirect to the edit path.
def show
# use edit as def... |
mongodb/mongo-ruby-driver | lib/mongo/address.rb | Mongo.Address.create_resolver | ruby | def create_resolver(ssl_options)
return Unix.new(seed.downcase) if seed.downcase =~ Unix::MATCH
family = (host == LOCALHOST) ? ::Socket::AF_INET : ::Socket::AF_UNSPEC
error = nil
::Socket.getaddrinfo(host, nil, family, ::Socket::SOCK_STREAM).each do |info|
begin
specific_addre... | To determine which address the socket will connect to, the driver will
attempt to connect to each IP address returned by Socket::getaddrinfo in
sequence. Once a successful connection is made, a resolver with that
IP address specified is returned. If no successful connection is
made, the error made by the last conne... | train | https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/address.rb#L193-L210 | class Address
extend Forwardable
# Mapping from socket family to resolver class.
#
# @since 2.0.0
FAMILY_MAP = {
::Socket::PF_UNIX => Unix,
::Socket::AF_INET6 => IPv6,
::Socket::AF_INET => IPv4
}.freeze
# The localhost constant.
#
# @since 2.1.0
LOCALHOST = ... |
wvanbergen/request-log-analyzer | lib/request_log_analyzer/controller.rb | RequestLogAnalyzer.Controller.handle_progress | ruby | def handle_progress(message, value = nil)
case message
when :started
@progress_bar = CommandLine::ProgressBar.new(File.basename(value), File.size(value), STDERR)
when :finished
@progress_bar.finish
@progress_bar = nil
when :interrupted
if @progress_bar
@... | Builds a new Controller for the given log file format.
<tt>format</tt> Logfile format. Defaults to :rails
Options are passd on to the LogParser.
* <tt>:database</tt> Database the controller should use.
* <tt>:yaml</tt> Yaml Dump the contrller should use.
* <tt>:output</tt> All report outputs get << through this ou... | train | https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/controller.rb#L264-L279 | class Controller
attr_reader :source, :filters, :aggregators, :output, :options
# Builds a RequestLogAnalyzer::Controller given parsed command line arguments
# <tt>arguments<tt> A CommandLine::Arguments hash containing parsed commandline parameters.
def self.build_from_arguments(arguments)
opti... |
klacointe/has_media | lib/has_media.rb | HasMedia.ClassMethods.create_one_accessors | ruby | def create_one_accessors(context, options)
define_method(context) do
media.with_context(context.to_sym).first
end
module_eval <<-"end;", __FILE__, __LINE__
def #{context}=(value)
return if value.blank?
medium = Medium.new_from_value(self, value, "#{context}", "#{op... | create_one_accessors
Create needed accessors on master object for unique relation
@param [String] context
@param [Hash] options | train | https://github.com/klacointe/has_media/blob/a886d36a914d8244f3761455458b9d0226fa22d5/lib/has_media.rb#L262-L278 | module ClassMethods
##
# has_one_medium
# Define a class method to link to a medium
#
# @param [String] context, the context (or accessor) to link medium
# @param [Hash] options, can be one of : encode, only
#
def has_one_medium(context, options = {})
set_relations(context, :... |
wvanbergen/request-log-analyzer | lib/request_log_analyzer/source/log_parser.rb | RequestLogAnalyzer::Source.LogParser.parse_string | ruby | def parse_string(string, options = {}, &block)
parse_io(StringIO.new(string), options, &block)
end | Parses a string. It will simply call parse_io. This function does not support progress updates.
<tt>string</tt>:: The string that should be parsed.
<tt>options</tt>:: A Hash of options that will be pased to parse_io. | train | https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/source/log_parser.rb#L157-L159 | class LogParser < Base
include Enumerable
# The maximum number of bytes to read from a line.
DEFAULT_MAX_LINE_LENGTH = 8096
DEFAULT_LINE_DIVIDER = "\n"
# The default parse strategy that will be used to parse the input.
DEFAULT_PARSE_STRATEGY = 'assume-correct'
# All available parse str... |
PierreRambaud/gemirro | lib/gemirro/configuration.rb | Gemirro.Configuration.define_source | ruby | def define_source(name, url, &block)
source = Source.new(name, url)
source.instance_eval(&block)
@source = source
end | Define the source to mirror.
@param [String] name
@param [String] url
@param [Proc] block | train | https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L202-L207 | class Configuration < Confstruct::Configuration
attr_accessor :source
attr_writer :logger
LOGGER_LEVEL = {
'debug' => Logger::DEBUG,
'warning' => Logger::WARN,
'info' => Logger::INFO,
'unknown' => Logger::UNKNOWN,
'error' => Logger::ERROR,
'fatal' => Logger::FATAL
... |
shadowbq/snort-thresholds | lib/threshold/thresholds.rb | Threshold.Thresholds.valid? | ruby | def valid?
begin
self.each do |threshold|
if threshold.respond_to?(:valid?)
return false unless threshold.valid?
else
raise InvalidThresholdsObject, "Container object has unknown objects"
end
end
return true
rescue InvalidThreshol... | Check if all objects in the Threshold Instance report .valid? | train | https://github.com/shadowbq/snort-thresholds/blob/e3e9d1b10c2460846e1779fda67e8bec0422f53e/lib/threshold/thresholds.rb#L64-L77 | 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... |
motion-kit/motion-kit | lib/motion-kit-osx/helpers/nswindow_frame_helpers.rb | MotionKit.NSWindowHelpers.above | ruby | def above(from_window, f={})
_calculate_frame(f, from: from_window, relative_to: { x: :reset, y: :above })
end | The first arg can be a window or a frame
@example | train | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit-osx/helpers/nswindow_frame_helpers.rb#L330-L332 | class NSWindowHelpers
def _fix_frame_value(value)
if value.is_a?(Hash) && value[:relative]
return value.merge(flipped: true)
end
return value
end
def frame(value, autosave_name=nil)
value = _fix_frame_value(value)
screen = target.screen || NSScreen.mainScreen
... |
giraffi/zcloudjp | lib/zcloudjp/utils.rb | Zcloudjp.Utils.parse_params | ruby | def parse_params(params, key_word)
body = params.has_key?(:path) ? load_file(params[:path], key_word) : params
body = { key_word => body } unless body.has_key?(key_word.to_sym)
body
end | Parses given params or file and returns Hash including the given key. | train | https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/utils.rb#L7-L11 | module Utils
# Parses given params or file and returns Hash including the given key.
# Loads a specified file and returns Hash including the given key.
def load_file(path, key_word)
begin
data = MultiJson.load(IO.read(File.expand_path(path)), symbolize_keys: true)
rescue RuntimeErro... |
HewlettPackard/hpe3par_ruby_sdk | lib/Hpe3parSdk/client.rb | Hpe3parSdk.Client.logout | ruby | def logout
unless @log_file_path.nil?
if Hpe3parSdk.logger != nil
Hpe3parSdk.logger.close
Hpe3parSdk.logger = nil
end
end
begin
@http.unauthenticate
rescue Hpe3parSdk::HPE3PARException => ex
#Do nothing
end
end | Logout from the 3PAR Array | train | https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L2633-L2645 | 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... |
moneta-rb/moneta | lib/moneta/synchronize.rb | Moneta.SynchronizePrimitive.enter | ruby | def enter(timeout = nil, wait = 0.01)
time_at_timeout = Time.now + timeout if timeout
while !timeout || Time.now < time_at_timeout
return true if try_enter
sleep(wait)
end
false
end | Enter critical section (blocking)
@param [Number] timeout Maximum time to wait
@param [Number] wait Sleep time between tries to acquire lock
@return [Boolean] true if the lock was aquired | train | https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/synchronize.rb#L31-L38 | class SynchronizePrimitive
# Synchronize block
#
# @api public
# @yieldparam Synchronized block
# @return [Object] result of block
def synchronize
enter
yield
ensure
leave
end
# Try to enter critical section (nonblocking)
#
# @return [Boolean] true if the... |
rjurado01/rapidoc | lib/rapidoc/resources_extractor.rb | Rapidoc.ResourcesExtractor.get_routes_doc | ruby | def get_routes_doc
puts "Executing 'rake routes'..." if trace?
routes_doc = RoutesDoc.new
routes = Dir.chdir( ::Rails.root.to_s ) { `rake routes` }
routes.split("\n").each do |entry|
routes_doc.add_route( entry ) unless entry.match(/URI/)
end
routes_doc
end | Reads 'rake routes' output and gets the routes info
@return [RoutesDoc] class with routes info | train | https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/resources_extractor.rb#L18-L29 | module ResourcesExtractor
##
# Reads 'rake routes' output and gets the routes info
# @return [RoutesDoc] class with routes info
#
##
# Create new ResourceDoc for each resource extracted from RoutesDoc
# @return [Array] ResourceDoc array
#
def get_resources
routes_doc = get... |
algolia/algoliasearch-client-ruby | lib/algolia/index.rb | Algolia.Index.add_objects! | ruby | def add_objects!(objects, request_options = {})
res = add_objects(objects, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | Add several objects in this index and wait end of indexing
@param objects the array of objects to add inside the index.
Each object is represented by an associative array
@param request_options contains extra parameters to send with your query | train | https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L91-L95 | 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... |
rmagick/rmagick | examples/identify.rb | Magick.Image.identify | ruby | def identify
printf 'Image: '
puts "#{base_filename}=>" if base_filename != filename
puts filename + "\n"
puts "\tFormat: #{format}\n"
puts "\tGeometry: #{columns}x#{rows}\n"
puts "\tClass: #{class_type}\n"
puts "\tType: #{image_type}\n"
puts "\tEndianess: #{endian}\n"
... | Print information similar to the identify -verbose command | train | https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/examples/identify.rb#L6-L156 | class Image
# Print information similar to the identify -verbose command
end
|
berkshelf/solve | lib/solve/ruby_solver.rb | Solve.RubySolver.requirement_satisfied_by? | ruby | def requirement_satisfied_by?(requirement, activated, spec)
version = spec.version
return false unless requirement.constraint.satisfies?(version)
shared_possibility_versions = possibility_versions(requirement, activated)
return false if !shared_possibility_versions.empty? && !shared_possibility_... | Callback required by Molinillo
Determines whether the given `requirement` is satisfied by the given
`spec`, in the context of the current `activated` dependency graph.
@param [Object] requirement
@param [DependencyGraph] activated the current dependency graph in the
resolution process.
@param [Object] spec
@r... | train | https://github.com/berkshelf/solve/blob/a0e03ede13e2f66b8dd6d0d34c9c9db70fba94d2/lib/solve/ruby_solver.rb#L171-L177 | class RubySolver
class << self
# The timeout (in seconds) to use when resolving graphs. Default is 10. This can be
# configured by setting the SOLVE_TIMEOUT environment variable.
#
# @return [Integer]
def timeout
seconds = 30 unless ( seconds = ENV["SOLVE_TIMEOUT"] )
... |
moneta-rb/moneta | lib/moneta/expires.rb | Moneta.Expires.merge! | ruby | def merge!(pairs, options={})
expires = expires_at(options)
options = Utils.without(options, :expires)
block = if block_given?
lambda do |key, old_entry, entry|
old_entry = invalidate_entry(key, old_entry)
if old_entry.nil?
entry... | (see Defaults#merge!) | train | https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/expires.rb#L124-L146 | 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... |
iyuuya/jkf | lib/jkf/parser/kif.rb | Jkf::Parser.Kif.make_hand | ruby | def make_hand(str)
# Kifu for iPhoneは半角スペース区切り
ret = { "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 }
return ret if str.empty?
str.split(/[ ]/).each do |kind|
next if kind.empty?
ret[kind2csa(kind[0])] = kind.length == 1 ? 1 : kan2n2(kind[1..-1])
... | generate motigoma | train | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kif.rb#L614-L625 | 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... |
sandipransing/rails_tiny_mce | plugins/paperclip/lib/paperclip/thumbnail.rb | Paperclip.Thumbnail.transformation_command | ruby | def transformation_command
scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
trans = []
trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty?
trans << "-crop" << %["#{crop}"] << "+repage" if crop
trans
end | Returns the command ImageMagick's +convert+ needs to transform the image
into the thumbnail. | train | https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/thumbnail.rb#L71-L77 | class Thumbnail < Processor
attr_accessor :current_geometry, :target_geometry, :format, :whiny, :convert_options, :source_file_options
# Creates a Thumbnail object set to work on the +file+ given. It
# will attempt to transform the image into one defined by +target_geometry+
# which is a "WxH"-style... |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.environment | ruby | def environment(vagrantfile, **opts)
path = File.expand_path(vagrantfile, root_path)
file = File.basename(path)
path = File.dirname(path)
Util::SilenceWarnings.silence! do
Environment.new({
child: true,
cwd: path,
home_path: home_path,
u... | Loads another environment for the given Vagrantfile, sharing as much
useful state from this Environment as possible (such as UI and paths).
Any initialization options can be overidden using the opts hash.
@param [String] vagrantfile Path to a Vagrantfile
@return [Environment] | train | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L499-L513 | 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... |
tarcieri/cool.io | lib/cool.io/io.rb | Coolio.IO.on_readable | ruby | def on_readable
begin
on_read @_io.read_nonblock(INPUT_SIZE)
rescue Errno::EAGAIN, Errno::EINTR
return
# SystemCallError catches Errno::ECONNRESET amongst others.
rescue SystemCallError, EOFError, IOError, SocketError
close
end
end | Read from the input buffer and dispatch to on_read | train | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/io.rb#L121-L131 | class IO
extend Meta
# Maximum number of bytes to consume at once
INPUT_SIZE = 16384
def initialize(io)
@_io = io
@_write_buffer ||= ::IO::Buffer.new
@_read_watcher = Watcher.new(io, self, :r)
@_write_watcher = Watcher.new(io, self, :w)
end
#
# Watcher methods,... |
tetradice/neuroncheck | lib/neuroncheck/utils.rb | NeuronCheckSystem.Utils.string_join_using_or_conjunction | ruby | def string_join_using_or_conjunction(strings)
ret = ""
strings.each_with_index do |str, i|
case i
when 0 # 最初の要素
when strings.size - 1 # 最後の要素
ret << " or "
else
ret << ", "
end
ret << str
end
ret
end | 1つ以上の文字列をorで結んだ英語文字列にする | train | https://github.com/tetradice/neuroncheck/blob/0505dedd8f7a8018a3891f7519f7861e1c787014/lib/neuroncheck/utils.rb#L41-L56 | module Utils
module_function
# From ActiveSupport (Thanks for Rails Team!) <https://github.com/rails/rails/tree/master/activesupport>
#
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
#
# 'Once upon a time in a world far far away'.truncate... |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.to_script_code | ruby | def to_script_code(skip_separator_index = 0)
payload = to_payload
if p2wpkh?
payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload
elsif skip_separator_index > 0
payload = subscript_codeseparator(skip_separator_index)
end
Bitcoin.pack_var_string(payload)
end | If this script is witness program, return its script code,
otherwise returns the self payload. ScriptInterpreter does not use this. | train | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L249-L257 | 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... |
metanorma/relaton | lib/relaton/db.rb | Relaton.Db.open_cache_biblio | ruby | def open_cache_biblio(dir, global: true)
return nil if dir.nil?
db = DbCache.new dir
if File.exist? dir
if global
unless db.check_version?
FileUtils.rm_rf(Dir.glob(dir + '/*'), secure: true)
warn "Global cache version is obsolete and cleared."
end
... | if cached reference is undated, expire it after 60 days
@param bib [Hash]
@param year [String]
def valid_bib_entry?(bib, year)
bib&.is_a?(Hash) && bib&.has_key?("bib") && bib&.has_key?("fetched") &&
(year || Date.today - bib["fetched"] < 60)
end
@param dir [String] DB directory
@param global [TrueClass, F... | train | https://github.com/metanorma/relaton/blob/2fac19da2f3ef3c30b8e8d8815a14d2115df0be6/lib/relaton/db.rb#L189-L206 | class Db
SUPPORTED_GEMS = %w[isobib ietfbib gbbib iecbib nistbib].freeze
# @param global_cache [String] directory of global DB
# @param local_cache [String] directory of local DB
def initialize(global_cache, local_cache)
register_gems
@registry = Relaton::Registry.instance
@db = ope... |
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.namespace= | ruby | def namespace=(a_namespace)
a_namespace = a_namespace.to_s
SDL4R.validate_identifier(a_namespace) unless a_namespace.empty?
@namespace = a_namespace
end | The namespace to set. +nil+ will be coerced to the empty string.
Raises +ArgumentError+ if the namespace is non-blank and is not
a legal SDL identifier (see SDL4R#validate_identifier) | train | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L707-L711 | 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
... |
lambda2/rice_cooker | lib/rice_cooker/base/helpers.rb | RiceCooker.Helpers.format_additional_param | ruby | def format_additional_param(additional, context_format = 'searching')
if additional.is_a? Hash
additional = additional.map do |field, value|
if value.is_a?(Hash)
value = {
proc: nil,
all: [],
description: ''
}.merge(value)
... | On va essayer de garder un format commun, qui est:
```
search: {
proc: -> (values) { * je fais des trucs avec les values * },
all: ['les', 'valeurs', 'aceptées'],
description: "La description dans la doc"
}
```
On va donc transformer `additional` dans le format ci-dessus | train | https://github.com/lambda2/rice_cooker/blob/b7ce285d3bd76ae979111f0374c5a43815473332/lib/rice_cooker/base/helpers.rb#L250-L278 | module Helpers
extend ActiveSupport::Concern
# Overridable method for available sortable fields
def sortable_fields_for(model)
if model.respond_to?(:sortable_fields)
model.sortable_fields.map(&:to_sym)
elsif model.respond_to?(:column_names)
model.column_names.map(&:to_sym)
... |
mongodb/mongoid | lib/mongoid/threaded.rb | Mongoid.Threaded.set_current_scope | ruby | def set_current_scope(scope, klass)
if scope.nil?
if Thread.current[CURRENT_SCOPE_KEY]
Thread.current[CURRENT_SCOPE_KEY].delete(klass)
Thread.current[CURRENT_SCOPE_KEY] = nil if Thread.current[CURRENT_SCOPE_KEY].empty?
end
else
Thread.current[CURRENT_SCOPE_KEY] ||... | Set the current Mongoid scope. Safe for multi-model scope chaining.
@example Set the scope.
Threaded.current_scope(scope, klass)
@param [ Criteria ] scope The current scope.
@param [ Class ] klass The current model class.
@return [ Criteria ] The scope.
@since 5.0.1 | train | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/threaded.rb#L263-L273 | module Threaded
DATABASE_OVERRIDE_KEY = "[mongoid]:db-override"
# Constant for the key to store clients.
#
# @since 5.0.0
CLIENTS_KEY = "[mongoid]:clients"
# The key to override the client.
#
# @since 5.0.0
CLIENT_OVERRIDE_KEY = "[mongoid]:client-override"
# The key for the... |
kontena/kontena | agent/lib/kontena/network_adapters/weave.rb | Kontena::NetworkAdapters.Weave.migrate_container | ruby | def migrate_container(container_id, cidr, attached_cidrs)
# first remove any existing addresses
# this is required, since weave will not attach if the address already exists, but with a different netmask
attached_cidrs.each do |attached_cidr|
if cidr != attached_cidr
warn "Migrate co... | Attach container to weave with given CIDR address, first detaching any existing mismatching addresses
@param [String] container_id
@param [String] overlay_cidr '10.81.X.Y/16'
@param [Array<String>] migrate_cidrs ['10.81.X.Y/19'] | train | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/network_adapters/weave.rb#L312-L324 | class Weave
include Celluloid
include Celluloid::Notifications
include Kontena::Observer::Helper
include Kontena::Helpers::IfaceHelper
include Kontena::Helpers::WeaveHelper
include Kontena::Logging
DEFAULT_NETWORK = 'kontena'.freeze
finalizer :finalizer
def initialize(autostart ... |
bitbucket-rest-api/bitbucket | lib/bitbucket_rest_api/issues.rb | BitBucket.Issues.edit | ruby | def edit(user_name, repo_name, issue_id, params={ })
_update_user_repo_params(user_name, repo_name)
_validate_user_repo_params(user, repo) unless user? && repo?
_validate_presence_of issue_id
normalize! params
# _merge_mime_type(:issue, params)
filter! VALID_ISSUE_PARAM_NAMES, param... | Edit an issue
= Inputs
<tt>:title</tt> - Required string
<tt>:content</tt> - Optional string
<tt>:responsible</tt> - Optional string - Login for the user that this issue should be assigned to.
<tt>:milestone</tt> - Optional number - Milestone to associate this issue with
<tt>:version</tt> - Optional number ... | train | https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/issues.rb#L217-L227 | class Issues < API
extend AutoloadHelper
autoload_all 'bitbucket_rest_api/issues',
:Comments => 'comments',
:Components => 'components',
:Milestones => 'milestones'
VALID_ISSUE_PARAM_NAMES = %w[
title
content
component
mileston... |
Falkor/falkorlib | lib/falkorlib/common.rb | FalkorLib.Common.exec_or_exit | ruby | def exec_or_exit(cmd)
status = execute(cmd)
if (status.to_i.nonzero?)
error("The command '#{cmd}' failed with exit status #{status.to_i}")
end
status
end | execute_in_dir
Execute a given command - exit if status != 0 | train | https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L152-L158 | 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... |
tmtysk/swf_ruby | lib/swf_ruby/replace_target.rb | SwfRuby.SpriteReplaceTarget.build_control_tags_string | ruby | def build_control_tags_string
str = ""
valid_control_tag_codes = [0, 1, 4, 5, 12, 18, 19, 26, 28, 43, 45, 70, 72]
@control_tags.each do |t|
next unless valid_control_tag_codes.include? t.code
if @idmap[t.refer_character_id]
str << t.rawdata_with_refer_character_id(@idmap[t.re... | DefineSpriteに埋め込むためのControl tagsのみを抽出する.
参照先のcharacter_idを変更する必要がある場合は付け替える. | train | https://github.com/tmtysk/swf_ruby/blob/97e1e18c4e7b7a67e21378f6e13f40c7b9ea27c8/lib/swf_ruby/replace_target.rb#L106-L118 | class SpriteReplaceTarget < ReplaceTarget
attr_accessor :swf
attr_accessor :frame_count
attr_accessor :define_tags
attr_accessor :control_tags
attr_accessor :idmap
attr_accessor :target_define_tags_string
attr_accessor :target_control_tags_string
attr_reader :target_swf_dumper
def... |
mongodb/mongoid | lib/mongoid/criteria.rb | Mongoid.Criteria.read | ruby | def read(value = nil)
clone.tap do |criteria|
criteria.options.merge!(read: value)
end
end | Set the read preference for the criteria.
@example Set the read preference.
criteria.read(mode: :primary_preferred)
@param [ Hash ] value The mode preference.
@return [ Criteria ] The cloned criteria.
@since 5.0.0 | train | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/criteria.rb#L310-L314 | class Criteria
include Enumerable
include Contextual
include Queryable
include Findable
include Inspectable
include Includable
include Marshalable
include Modifiable
include Scopable
include Clients::Options
include Clients::Sessions
include Options
# Static array ... |
senchalabs/jsduck | lib/jsduck/tag/mixins.rb | JsDuck::Tag.Mixins.to_mixins_array | ruby | def to_mixins_array(ast)
v = ast.to_value
mixins = v.is_a?(Hash) ? v.values : Array(v)
mixins.all? {|mx| mx.is_a? String } ? mixins : []
end | converts AstNode, whether it's a string, array or hash into
array of strings (when possible). | train | https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag/mixins.rb#L21-L25 | class Mixins < ClassListTag
def initialize
@pattern = ["mixin", "mixins"]
@tagname = :mixins
@repeatable = true
@ext_define_pattern = "mixins"
@ext_define_default = {:mixins => []}
end
# Override definition in parent class. In addition to Array
# literal, mixins can be ... |
dicom/rtp-connect | lib/rtp-connect/plan.rb | RTP.Plan.open_file | ruby | def open_file(file)
# Check if file already exists:
if File.exist?(file)
# Is (the existing file) writable?
unless File.writable?(file)
raise "The program does not have permission or resources to create this file: #{file}"
end
else
# File does not exist.
... | Tests if the path/file is writable, creates any folders if necessary, and opens the file for writing.
@param [String] file a path/file string
@raise if the given file cannot be created | train | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan.rb#L574-L599 | class Plan < Record
include Logging
# The Record which this instance belongs to (nil by definition).
attr_reader :parent
# An array of Prescription records (if any) that belongs to this Plan.
attr_reader :prescriptions
# The ExtendedPlan record (if any) that belongs to this Plan.
attr_rea... |
moneta-rb/moneta | lib/moneta/mixins.rb | Moneta.CreateSupport.create | ruby | def create(key, value, options = {})
if key? key
false
else
store(key, value, options)
true
end
end | (see Defaults#create) | train | https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L452-L459 | module CreateSupport
# (see Defaults#create)
def self.included(base)
base.supports(:create) if base.respond_to?(:supports)
end
end
|
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.rebase | ruby | def rebase(upstream, opts = {})
args = []
if opts[:interactive]
logger.info { "Interactively rebasing #{branches.current.name} against #{upstream}" }
args << '-i'
args << upstream
elsif opts[:oldbase]
logger.info { "Doing rebase from #{opts[:oldbase]} against #{upstream... | `git rebase`
@param [String] upstream the commit-ish to rebase against
@option opts :interactive do an interactive rebase
@option opts [String] :oldbase the old base to rebase from
@return [String] the output of 'git rebase' | train | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L277-L291 | class GitLib
# @param [Dir] dir the work dir
# @param [Hash] logging_opts see {log_level}
def initialize(dir, logging_opts)
self.log_level = GitLib.log_level(logging_opts)
self.workdir = dir
end
# @return [GitLogger] the logger to use
def logger
if @logger.nil?
@lo... |
ikayzo/SDL.rb | lib/sdl4r/parser.rb | SDL4R.Parser.parse | ruby | def parse
tags = []
while tokens = @tokenizer.read_line_tokens()
if tokens.last.type == :START_BLOCK
# tag with a block
tag = construct_tag(tokens[0...-1])
add_children(tag)
tags << tag
elsif tokens.first.type == :END_BLOCK
# ... | Creates an SDL parser on the specified +IO+.
IO.open("path/to/sdl_file") { |io|
parser = SDL4R::Parser.new(io)
tags = parser.parse()
}
Parses the underlying +IO+ and returns an +Array+ of +Tag+.
==Errors
[IOError] If a problem is encountered with the IO
[SdlParseError] If the document is malforme... | train | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L70-L96 | class Parser
# Passed to parse_error() in order to specify an error that occured on no specific position
# (column).
UNKNOWN_POSITION = -2
# Creates an SDL parser on the specified +IO+.
#
# IO.open("path/to/sdl_file") { |io|
# parser = SDL4R::Parser.new(io)
# tags = p... |
xing/beetle | lib/beetle/publisher.rb | Beetle.Publisher.rpc | ruby | def rpc(message_name, data, opts={}) #:nodoc:
opts = @client.messages[message_name].merge(opts.symbolize_keys)
exchange_name = opts.delete(:exchange)
opts.delete(:queue)
recycle_dead_servers unless @dead_servers.empty?
tries = @servers.size
logger.debug "Beetle: performing rpc with m... | :nodoc: | train | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/publisher.rb#L103-L136 | class Publisher < Base
attr_reader :dead_servers
def initialize(client, options = {}) #:nodoc:
super
@exchanges_with_bound_queues = {}
@dead_servers = {}
@bunnies = {}
at_exit { stop }
end
# list of exceptions potentially raised by bunny
# these need to be lazy, be... |
nylas/nylas-ruby | lib/nylas/collection.rb | Nylas.Collection.where | ruby | def where(filters)
raise ModelNotFilterableError, model unless model.filterable?
self.class.new(model: model, api: api, constraints: constraints.merge(where: filters))
end | Merges in additional filters when querying the collection
@return [Collection<Model>] | train | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/collection.rb#L30-L34 | class Collection
attr_accessor :model, :api, :constraints
extend Forwardable
def_delegators :each, :map, :select, :reject, :to_a, :take
def_delegators :to_a, :first, :last, :[]
def initialize(model:, api:, constraints: nil)
self.constraints = Constraints.from_constraints(constraints)
... |
wvanbergen/request-log-analyzer | lib/request_log_analyzer/file_format.rb | RequestLogAnalyzer::FileFormat.CommonRegularExpressions.add_blank_option | ruby | def add_blank_option(regexp, blank)
case blank
when String then Regexp.union(regexp, Regexp.new(Regexp.quote(blank)))
when true then Regexp.union(regexp, //)
else regexp
end
end | Allow the field to be blank if this option is given. This can be true to
allow an empty string or a string alternative for the nil value. | train | https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/file_format.rb#L184-L190 | 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',
... |
berkshelf/solve | lib/solve/ruby_solver.rb | Solve.RubySolver.resolve | ruby | def resolve(options = {})
@ui = options[:ui] if options[:ui]
solved_graph = resolve_with_error_wrapping
solution = solved_graph.map(&:payload)
unsorted_solution = solution.inject({}) do |stringified_soln, artifact|
stringified_soln[artifact.name] = artifact.version.to_s
string... | @option options [Boolean] :sorted
return the solution as a sorted list instead of a Hash
@return [Hash, List] Returns a hash like { "Artifact Name" => "Version",... }
unless the :sorted option is true, then it returns a list like [["Artifact Name", "Version],...]
@raise [Errors::NoSolutionError] when the deman... | train | https://github.com/berkshelf/solve/blob/a0e03ede13e2f66b8dd6d0d34c9c9db70fba94d2/lib/solve/ruby_solver.rb#L73-L90 | class RubySolver
class << self
# The timeout (in seconds) to use when resolving graphs. Default is 10. This can be
# configured by setting the SOLVE_TIMEOUT environment variable.
#
# @return [Integer]
def timeout
seconds = 30 unless ( seconds = ENV["SOLVE_TIMEOUT"] )
... |
bottleneckco/playoverwatch-scraper | lib/playoverwatch-scraper/scraper.rb | PlayOverwatch.Scraper.main_qp | ruby | def main_qp
hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first
hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first
end | Retrieve player's main Quick Play hero, in lowercase form. | train | https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L49-L52 | class Scraper
##
# Creates a scraper with a specified battle tag.
# The +battle_tag+ can be in the hex (#) or hyphenated (-) format. It IS case sensitive.
def initialize(battle_tag)
@player_page = Nokogiri::HTML(open("https://playoverwatch.com/en-us/career/pc/#{battle_tag.gsub(/#/, '-')}", "User... |
projectcypress/health-data-standards | lib/hqmf-parser/2.0/types.rb | HQMF2.TemporalReference.to_model | ruby | def to_model
rm = range ? range.to_model : nil
HQMF::TemporalReference.new(type, reference.to_model, rm)
end | Generates this classes hqmf-model equivalent | train | https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/types.rb#L363-L366 | class TemporalReference
include HQMF2::Utilities
attr_reader :type, :reference, :range
# Use updated mappings to HDS temporal reference types (as used in SimpleXML Parser)
# https://github.com/projecttacoma/simplexml_parser/blob/fa0f589d98059b88d77dc3cb465b62184df31671/lib/model/types.rb#L167
UP... |
sup-heliotrope/sup | lib/sup/poll.rb | Redwood.PollManager.poll_from | ruby | def poll_from source, opts={}
debug "trying to acquire poll lock for: #{source}..."
if source.try_lock
begin
source.poll do |sym, args|
case sym
when :add
m = Message.build_from_source source, args[:info]
old_m = Index.build_message m.id
m.la... | like Source#poll, but yields successive Message objects, which have their
labels and locations set correctly. The Messages are saved to or removed
from the index after being yielded. | train | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/poll.rb#L197-L265 | class PollManager
include Redwood::Singleton
HookManager.register "before-add-message", <<EOS
Executes immediately before a message is added to the index.
Variables:
message: the new message
EOS
HookManager.register "before-poll", <<EOS
Executes immediately before a poll for new messages commences.
No variabl... |
SamSaffron/message_bus | lib/message_bus/http_client.rb | MessageBus.HTTPClient.unsubscribe | ruby | def unsubscribe(channel, &callback)
if callback
@channels[channel].callbacks.delete(callback)
remove_channel(channel) if @channels[channel].callbacks.empty?
else
remove_channel(channel)
end
stop if @channels.empty?
@status
end | unsubscribes from a channel
@example Unsubscribing from a channel
client = MessageBus::HTTPClient.new('http://some.test.com')
callback = -> { |payload| puts payload }
client.subscribe("/test", &callback)
client.unsubscribe("/test")
If a callback is given, only the specific callback will be unsubscribed.... | train | https://github.com/SamSaffron/message_bus/blob/90fba639eb5d332ca8e87fd35f1d603a5743076d/lib/message_bus/http_client.rb#L201-L211 | class HTTPClient
class InvalidChannel < StandardError; end
class MissingBlock < StandardError; end
attr_reader :channels,
:stats
attr_accessor :enable_long_polling,
:status,
:enable_chunked_encoding,
:min_poll_interval,
... |
sup-heliotrope/sup | lib/sup/modes/thread_index_mode.rb | Redwood.ThreadIndexMode.actually_toggle_deleted | ruby | def actually_toggle_deleted t
if t.has_label? :deleted
t.remove_label :deleted
add_or_unhide t.first
UpdateManager.relay self, :undeleted, t.first
lambda do
t.apply_label :deleted
hide_thread t
UpdateManager.relay self, :deleted, t.first
end
else
t.app... | returns an undo lambda | train | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L377-L397 | class ThreadIndexMode < LineCursorMode
DATE_WIDTH = Time::TO_NICE_S_MAX_LEN
MIN_FROM_WIDTH = 15
LOAD_MORE_THREAD_NUM = 20
HookManager.register "index-mode-size-widget", <<EOS
Generates the per-thread size widget for each thread.
Variables:
thread: The message thread to be formatted.
EOS
HookManager.regist... |
trishume/pro | lib/pro/indexer.rb | Pro.Indexer.run_index_process | ruby | def run_index_process
readme, writeme = IO.pipe
p1 = fork {
# Stop cd function from blocking on fork
STDOUT.reopen(writeme)
readme.close
index_process unless File.exists?(INDEXER_LOCK_PATH)
}
Process.detach(p1)
end | spins off a background process to update the cache file | train | https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L37-L47 | class Indexer
CACHE_PATH = File.expand_path("~/.proCache")
INDEXER_LOCK_PATH = File.expand_path("~/.proCacheLock")
def initialize
@base_dirs = find_base_dirs
@low_cpu = false
end
def index
# most of the time the cache should exist
if res = read_cache
# index in the... |
robertwahler/repo_manager | lib/repo_manager/actions/base_action.rb | RepoManager.BaseAction.help | ruby | def help(help_options={})
comment_starting_with = help_options[:comment_starting_with] || ""
located_in_file = help_options[:located_in_file] || __FILE__
text = File.read(located_in_file)
result = text.match(/(^\s*#\s*#{comment_starting_with}.*)^\s*class .* AppAction/m)
result = $1
... | Convert method comments block to help text
@return [String] suitable for displaying on STDOUT | train | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L243-L260 | 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
... |
DigitPaint/roger | lib/roger/resolver.rb | Roger.Resolver.split_path | ruby | def split_path(path)
path = path.to_s
extension = File.extname(path)[1..-1] || ""
path_without_extension = path.sub(/\.#{Regexp.escape(extension)}\Z/, "")
[extension, path_without_extension]
end | Split path in to extension an path without extension | train | https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/resolver.rb#L191-L196 | class Resolver
# Maps output extensions to template extensions to find
# source files.
EXTENSION_MAP = {
"html" => %w(
rhtml
markdown
mkd
md
ad
adoc
asciidoc
rdoc
textile
),
"csv" => %w(
rcsv
),
#... |
NullVoxPopuli/authorizable | lib/authorizable/cache.rb | Authorizable.Cache.set_for_role | ruby | def set_for_role(name: "", role: nil, value: nil)
if role
store[role] ||= {}
store[role][name] = value
else
store[name] = value
end
end | calculating the value of a permission is costly.
there are several Database lookups and lots of merging
of hashes.
once a permission is calculated, we'll store it here, so we don't
have to re-calculate/query/merge everything all over again
for both object access and page access, check if we've
already calculated... | train | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/cache.rb#L36-L43 | class Cache
def store
@permission_cache ||= {}
end
# calculating the value of a permission is costly.
# there are several Database lookups and lots of merging
# of hashes.
# once a permission is calculated, we'll store it here, so we don't
# have to re-calculate/query/merge everyt... |
robertwahler/repo_manager | lib/repo_manager/views/base_view.rb | RepoManager.BaseView.render | ruby | def render
raise "unable to find template file: #{template}" unless File.exists?(template)
extension = File.extname(template)
extension = extension.downcase if extension
case extension
when '.erb'
contents = File.open(template, "r") {|f| f.read}
ERB.new(contents, ni... | TODO: render based on file ext | train | https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/base_view.rb#L97-L112 | class BaseView
def initialize(items, configuration={})
@configuration = configuration.deep_clone
@items = items
@template = File.expand_path('../templates/default.slim', __FILE__)
end
def configuration
@configuration
end
def items
@items
end
def template
... |
projectcypress/health-data-standards | lib/hqmf-parser/2.0/data_criteria.rb | HQMF2.DataCriteria.basic_setup | ruby | def basic_setup
@status = attr_val('./*/cda:statusCode/@code')
@id_xpath = './*/cda:id/@extension'
@id = "#{attr_val('./*/cda:id/@extension')}_#{attr_val('./*/cda:id/@root')}"
@comments = @entry.xpath("./#{CRITERIA_GLOB}/cda:text/cda:xml/cda:qdmUserComments/cda:item/text()",
... | Handles elments that can be extracted directly from the xml. Utilises the "BaseExtractions" class. | train | https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/data_criteria.rb#L184-L201 | class DataCriteria
include HQMF2::Utilities, HQMF2::DataCriteriaTypeAndDefinitionExtraction, HQMF2::DataCriteriaPostProcessing
attr_accessor :id
attr_accessor :original_id
attr_reader :property, :type, :status, :value, :effective_time, :section
attr_reader :temporal_references, :subset_operators,... |
jeremytregunna/ruby-trello | lib/trello/card.rb | Trello.Card.remove_upvote | ruby | def remove_upvote
begin
client.delete("/cards/#{id}/membersVoted/#{me.id}")
rescue Trello::Error => e
fail e unless e.message =~ /has not voted/i
end
self
end | Recind upvote. Noop if authenticated user hasn't previously voted | train | https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L392-L400 | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.