id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
19,900
basecrm/basecrm-ruby
lib/basecrm/services/deal_unqualified_reasons_service.rb
BaseCRM.DealUnqualifiedReasonsService.update
def update(deal_unqualified_reason) validate_type!(deal_unqualified_reason) params = extract_params!(deal_unqualified_reason, :id) id = params[:id] attributes = sanitize(deal_unqualified_reason) _, _, root = @client.put("/deal_unqualified_reasons/#{id}", attributes) DealUnqualifiedReason.new(root[:data]) end
ruby
def update(deal_unqualified_reason) validate_type!(deal_unqualified_reason) params = extract_params!(deal_unqualified_reason, :id) id = params[:id] attributes = sanitize(deal_unqualified_reason) _, _, root = @client.put("/deal_unqualified_reasons/#{id}", attributes) DealUnqualifiedReason.new(root[:data]) end
[ "def", "update", "(", "deal_unqualified_reason", ")", "validate_type!", "(", "deal_unqualified_reason", ")", "params", "=", "extract_params!", "(", "deal_unqualified_reason", ",", ":id", ")", "id", "=", "params", "[", ":id", "]", "attributes", "=", "sanitize", "(", "deal_unqualified_reason", ")", "_", ",", "_", ",", "root", "=", "@client", ".", "put", "(", "\"/deal_unqualified_reasons/#{id}\"", ",", "attributes", ")", "DealUnqualifiedReason", ".", "new", "(", "root", "[", ":data", "]", ")", "end" ]
Update a deal unqualified reason put '/deal_unqualified_reasons/{id}' Updates a deal unqualified reason information If the specified deal unqualified reason does not exist, the request will return an error <figure class="notice"> If you want to update deal unqualified reason you **must** make sure name of the reason is unique </figure> @param deal_unqualified_reason [DealUnqualifiedReason, Hash] Either object of the DealUnqualifiedReason type or Hash. This object's attributes describe the object to be updated. @return [DealUnqualifiedReason] The resulting object represting updated resource.
[ "Update", "a", "deal", "unqualified", "reason" ]
c39ea72477d41c3122805d49587043399ee454ea
https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/deal_unqualified_reasons_service.rb#L90-L99
19,901
arnau/ISO8601
lib/iso8601/date.rb
ISO8601.Date.+
def +(other) other = other.to_days if other.respond_to?(:to_days) ISO8601::Date.new((@date + other).iso8601) end
ruby
def +(other) other = other.to_days if other.respond_to?(:to_days) ISO8601::Date.new((@date + other).iso8601) end
[ "def", "+", "(", "other", ")", "other", "=", "other", ".", "to_days", "if", "other", ".", "respond_to?", "(", ":to_days", ")", "ISO8601", "::", "Date", ".", "new", "(", "(", "@date", "+", "other", ")", ".", "iso8601", ")", "end" ]
Forwards the date the given amount of days. @param [Numeric] other The days to add @return [ISO8601::Date] New date resulting of the addition
[ "Forwards", "the", "date", "the", "given", "amount", "of", "days", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/date.rb#L54-L57
19,902
arnau/ISO8601
lib/iso8601/date.rb
ISO8601.Date.atomize
def atomize(input) week_date = parse_weekdate(input) return atomize_week_date(input, week_date[2], week_date[1]) unless week_date.nil? _, sign, year, separator, day = parse_ordinal(input) return atomize_ordinal(year, day, separator, sign) unless year.nil? _, year, separator, month, day = parse_date(input) raise(ISO8601::Errors::UnknownPattern, @original) if year.nil? @separator = separator [year, month, day].compact.map(&:to_i) end
ruby
def atomize(input) week_date = parse_weekdate(input) return atomize_week_date(input, week_date[2], week_date[1]) unless week_date.nil? _, sign, year, separator, day = parse_ordinal(input) return atomize_ordinal(year, day, separator, sign) unless year.nil? _, year, separator, month, day = parse_date(input) raise(ISO8601::Errors::UnknownPattern, @original) if year.nil? @separator = separator [year, month, day].compact.map(&:to_i) end
[ "def", "atomize", "(", "input", ")", "week_date", "=", "parse_weekdate", "(", "input", ")", "return", "atomize_week_date", "(", "input", ",", "week_date", "[", "2", "]", ",", "week_date", "[", "1", "]", ")", "unless", "week_date", ".", "nil?", "_", ",", "sign", ",", "year", ",", "separator", ",", "day", "=", "parse_ordinal", "(", "input", ")", "return", "atomize_ordinal", "(", "year", ",", "day", ",", "separator", ",", "sign", ")", "unless", "year", ".", "nil?", "_", ",", "year", ",", "separator", ",", "month", ",", "day", "=", "parse_date", "(", "input", ")", "raise", "(", "ISO8601", "::", "Errors", "::", "UnknownPattern", ",", "@original", ")", "if", "year", ".", "nil?", "@separator", "=", "separator", "[", "year", ",", "month", ",", "day", "]", ".", "compact", ".", "map", "(", ":to_i", ")", "end" ]
Splits the date component into valid atoms. Acceptable patterns: * YYYY * YYYY-MM but not YYYYMM * YYYY-MM-DD, YYYYMMDD * YYYY-Www, YYYYWdd * YYYY-Www-D, YYYYWddD * YYYY-DDD, YYYYDDD @param [String] input @return [Array<Integer>] rubocop:disable Metrics/AbcSize
[ "Splits", "the", "date", "component", "into", "valid", "atoms", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/date.rb#L116-L130
19,903
arnau/ISO8601
lib/iso8601/duration.rb
ISO8601.Duration.months_to_seconds
def months_to_seconds(base) month_base = base.nil? ? nil : base + years.to_seconds(base) months.to_seconds(month_base) end
ruby
def months_to_seconds(base) month_base = base.nil? ? nil : base + years.to_seconds(base) months.to_seconds(month_base) end
[ "def", "months_to_seconds", "(", "base", ")", "month_base", "=", "base", ".", "nil?", "?", "nil", ":", "base", "+", "years", ".", "to_seconds", "(", "base", ")", "months", ".", "to_seconds", "(", "month_base", ")", "end" ]
Changes the base to compute the months for the right base year
[ "Changes", "the", "base", "to", "compute", "the", "months", "for", "the", "right", "base", "year" ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/duration.rb#L175-L178
19,904
arnau/ISO8601
lib/iso8601/duration.rb
ISO8601.Duration.atomize
def atomize(input) duration = parse(input) || raise(ISO8601::Errors::UnknownPattern, input) valid_pattern?(duration) @sign = sign_to_i(duration[:sign]) components = parse_tokens(duration) components.delete(:time) # clean time capture valid_fractions?(components.values) components end
ruby
def atomize(input) duration = parse(input) || raise(ISO8601::Errors::UnknownPattern, input) valid_pattern?(duration) @sign = sign_to_i(duration[:sign]) components = parse_tokens(duration) components.delete(:time) # clean time capture valid_fractions?(components.values) components end
[ "def", "atomize", "(", "input", ")", "duration", "=", "parse", "(", "input", ")", "||", "raise", "(", "ISO8601", "::", "Errors", "::", "UnknownPattern", ",", "input", ")", "valid_pattern?", "(", "duration", ")", "@sign", "=", "sign_to_i", "(", "duration", "[", ":sign", "]", ")", "components", "=", "parse_tokens", "(", "duration", ")", "components", ".", "delete", "(", ":time", ")", "# clean time capture", "valid_fractions?", "(", "components", ".", "values", ")", "components", "end" ]
Splits a duration pattern into valid atoms. Acceptable patterns: * PnYnMnD * PTnHnMnS * PnYnMnDTnHnMnS * PnW Where `n` is any number. If it contains a decimal fraction, a dot (`.`) or comma (`,`) can be used. @param [String] input @return [Hash<Float>]
[ "Splits", "a", "duration", "pattern", "into", "valid", "atoms", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/duration.rb#L196-L209
19,905
arnau/ISO8601
lib/iso8601/duration.rb
ISO8601.Duration.fetch_seconds
def fetch_seconds(other, base = nil) case other when ISO8601::Duration other.to_seconds(base) when Numeric other.to_f else raise(ISO8601::Errors::TypeError, other) end end
ruby
def fetch_seconds(other, base = nil) case other when ISO8601::Duration other.to_seconds(base) when Numeric other.to_f else raise(ISO8601::Errors::TypeError, other) end end
[ "def", "fetch_seconds", "(", "other", ",", "base", "=", "nil", ")", "case", "other", "when", "ISO8601", "::", "Duration", "other", ".", "to_seconds", "(", "base", ")", "when", "Numeric", "other", ".", "to_f", "else", "raise", "(", "ISO8601", "::", "Errors", "::", "TypeError", ",", "other", ")", "end", "end" ]
Fetch the number of seconds of another element. @param [ISO8601::Duration, Numeric] other Instance of a class to fetch seconds. @raise [ISO8601::Errors::TypeError] If other param is not an instance of ISO8601::Duration or Numeric classes @return [Float] Number of seconds of other param Object
[ "Fetch", "the", "number", "of", "seconds", "of", "another", "element", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/duration.rb#L323-L332
19,906
arnau/ISO8601
lib/iso8601/years.rb
ISO8601.Years.to_seconds
def to_seconds(base = nil) valid_base?(base) return factor(base) * atom if base.nil? target = ::Time.new(base.year + atom.to_i, base.month, base.day, base.hour, base.minute, base.second, base.zone) target - base.to_time end
ruby
def to_seconds(base = nil) valid_base?(base) return factor(base) * atom if base.nil? target = ::Time.new(base.year + atom.to_i, base.month, base.day, base.hour, base.minute, base.second, base.zone) target - base.to_time end
[ "def", "to_seconds", "(", "base", "=", "nil", ")", "valid_base?", "(", "base", ")", "return", "factor", "(", "base", ")", "*", "atom", "if", "base", ".", "nil?", "target", "=", "::", "Time", ".", "new", "(", "base", ".", "year", "+", "atom", ".", "to_i", ",", "base", ".", "month", ",", "base", ".", "day", ",", "base", ".", "hour", ",", "base", ".", "minute", ",", "base", ".", "second", ",", "base", ".", "zone", ")", "target", "-", "base", ".", "to_time", "end" ]
The amount of seconds TODO: Fractions of year will fail @param [ISO8601::DateTime, nil] base (nil) The base datetime to compute the year length. @return [Numeric] rubocop:disable Metrics/AbcSize
[ "The", "amount", "of", "seconds" ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/years.rb#L55-L61
19,907
arnau/ISO8601
lib/iso8601/time_interval.rb
ISO8601.TimeInterval.include?
def include?(other) raise(ISO8601::Errors::TypeError, "The parameter must respond_to #to_time") \ unless other.respond_to?(:to_time) (first.to_time <= other.to_time && last.to_time >= other.to_time) end
ruby
def include?(other) raise(ISO8601::Errors::TypeError, "The parameter must respond_to #to_time") \ unless other.respond_to?(:to_time) (first.to_time <= other.to_time && last.to_time >= other.to_time) end
[ "def", "include?", "(", "other", ")", "raise", "(", "ISO8601", "::", "Errors", "::", "TypeError", ",", "\"The parameter must respond_to #to_time\"", ")", "unless", "other", ".", "respond_to?", "(", ":to_time", ")", "(", "first", ".", "to_time", "<=", "other", ".", "to_time", "&&", "last", ".", "to_time", ">=", "other", ".", "to_time", ")", "end" ]
Check if a given time is inside the current TimeInterval. @param [#to_time] other DateTime to check if it's inside the current interval. @raise [ISO8601::Errors::TypeError] if time param is not a compatible Object. @return [Boolean]
[ "Check", "if", "a", "given", "time", "is", "inside", "the", "current", "TimeInterval", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/time_interval.rb#L161-L167
19,908
arnau/ISO8601
lib/iso8601/time_interval.rb
ISO8601.TimeInterval.subset?
def subset?(other) raise(ISO8601::Errors::TypeError, "The parameter must be an instance of #{self.class}") \ unless other.is_a?(self.class) other.include?(first) && other.include?(last) end
ruby
def subset?(other) raise(ISO8601::Errors::TypeError, "The parameter must be an instance of #{self.class}") \ unless other.is_a?(self.class) other.include?(first) && other.include?(last) end
[ "def", "subset?", "(", "other", ")", "raise", "(", "ISO8601", "::", "Errors", "::", "TypeError", ",", "\"The parameter must be an instance of #{self.class}\"", ")", "unless", "other", ".", "is_a?", "(", "self", ".", "class", ")", "other", ".", "include?", "(", "first", ")", "&&", "other", ".", "include?", "(", "last", ")", "end" ]
Returns true if the interval is a subset of the given interval. @param [ISO8601::TimeInterval] other a time interval. @raise [ISO8601::Errors::TypeError] if time param is not a compatible Object. @return [Boolean]
[ "Returns", "true", "if", "the", "interval", "is", "a", "subset", "of", "the", "given", "interval", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/time_interval.rb#L179-L184
19,909
arnau/ISO8601
lib/iso8601/time_interval.rb
ISO8601.TimeInterval.intersection
def intersection(other) raise(ISO8601::Errors::IntervalError, "The intervals are disjoint") \ if disjoint?(other) && other.disjoint?(self) return self if subset?(other) return other if other.subset?(self) a, b = sort_pair(self, other) self.class.from_datetimes(b.first, a.last) end
ruby
def intersection(other) raise(ISO8601::Errors::IntervalError, "The intervals are disjoint") \ if disjoint?(other) && other.disjoint?(self) return self if subset?(other) return other if other.subset?(self) a, b = sort_pair(self, other) self.class.from_datetimes(b.first, a.last) end
[ "def", "intersection", "(", "other", ")", "raise", "(", "ISO8601", "::", "Errors", "::", "IntervalError", ",", "\"The intervals are disjoint\"", ")", "if", "disjoint?", "(", "other", ")", "&&", "other", ".", "disjoint?", "(", "self", ")", "return", "self", "if", "subset?", "(", "other", ")", "return", "other", "if", "other", ".", "subset?", "(", "self", ")", "a", ",", "b", "=", "sort_pair", "(", "self", ",", "other", ")", "self", ".", "class", ".", "from_datetimes", "(", "b", ".", "first", ",", "a", ".", "last", ")", "end" ]
Return the intersection between two intervals. @param [ISO8601::TimeInterval] other time interval @raise [ISO8601::Errors::TypeError] if the param is not a TimeInterval. @return [Boolean]
[ "Return", "the", "intersection", "between", "two", "intervals", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/time_interval.rb#L226-L235
19,910
arnau/ISO8601
lib/iso8601/time_interval.rb
ISO8601.TimeInterval.parse_subpattern
def parse_subpattern(pattern) return ISO8601::Duration.new(pattern) if pattern.start_with?('P') ISO8601::DateTime.new(pattern) end
ruby
def parse_subpattern(pattern) return ISO8601::Duration.new(pattern) if pattern.start_with?('P') ISO8601::DateTime.new(pattern) end
[ "def", "parse_subpattern", "(", "pattern", ")", "return", "ISO8601", "::", "Duration", ".", "new", "(", "pattern", ")", "if", "pattern", ".", "start_with?", "(", "'P'", ")", "ISO8601", "::", "DateTime", ".", "new", "(", "pattern", ")", "end" ]
Parses a subpattern to a correct type. @param [String] pattern @return [ISO8601::Duration, ISO8601::DateTime]
[ "Parses", "a", "subpattern", "to", "a", "correct", "type", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/time_interval.rb#L330-L334
19,911
arnau/ISO8601
lib/iso8601/date_time.rb
ISO8601.DateTime.parse
def parse(date_time) raise(ISO8601::Errors::UnknownPattern, date_time) if date_time.empty? date, time = date_time.split('T') date_atoms = parse_date(date) time_atoms = Array(time && parse_time(time)) separators = [date_atoms.pop, time_atoms.pop] raise(ISO8601::Errors::UnknownPattern, @original) unless valid_representation?(date_atoms, time_atoms) raise(ISO8601::Errors::UnknownPattern, @original) unless valid_separators?(separators) ::DateTime.new(*(date_atoms + time_atoms).compact) end
ruby
def parse(date_time) raise(ISO8601::Errors::UnknownPattern, date_time) if date_time.empty? date, time = date_time.split('T') date_atoms = parse_date(date) time_atoms = Array(time && parse_time(time)) separators = [date_atoms.pop, time_atoms.pop] raise(ISO8601::Errors::UnknownPattern, @original) unless valid_representation?(date_atoms, time_atoms) raise(ISO8601::Errors::UnknownPattern, @original) unless valid_separators?(separators) ::DateTime.new(*(date_atoms + time_atoms).compact) end
[ "def", "parse", "(", "date_time", ")", "raise", "(", "ISO8601", "::", "Errors", "::", "UnknownPattern", ",", "date_time", ")", "if", "date_time", ".", "empty?", "date", ",", "time", "=", "date_time", ".", "split", "(", "'T'", ")", "date_atoms", "=", "parse_date", "(", "date", ")", "time_atoms", "=", "Array", "(", "time", "&&", "parse_time", "(", "time", ")", ")", "separators", "=", "[", "date_atoms", ".", "pop", ",", "time_atoms", ".", "pop", "]", "raise", "(", "ISO8601", "::", "Errors", "::", "UnknownPattern", ",", "@original", ")", "unless", "valid_representation?", "(", "date_atoms", ",", "time_atoms", ")", "raise", "(", "ISO8601", "::", "Errors", "::", "UnknownPattern", ",", "@original", ")", "unless", "valid_separators?", "(", "separators", ")", "::", "DateTime", ".", "new", "(", "(", "date_atoms", "+", "time_atoms", ")", ".", "compact", ")", "end" ]
Parses an ISO date time, where the date and the time components are optional. It enhances the parsing capabilities of the native DateTime. @param [String] date_time The ISO representation rubocop:disable Metrics/AbcSize
[ "Parses", "an", "ISO", "date", "time", "where", "the", "date", "and", "the", "time", "components", "are", "optional", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/date_time.rb#L100-L113
19,912
arnau/ISO8601
lib/iso8601/date_time.rb
ISO8601.DateTime.parse_date
def parse_date(input) today = ::Date.today return [today.year, today.month, today.day, :ignore] if input.empty? date = ISO8601::Date.new(input) date.atoms << date.separator end
ruby
def parse_date(input) today = ::Date.today return [today.year, today.month, today.day, :ignore] if input.empty? date = ISO8601::Date.new(input) date.atoms << date.separator end
[ "def", "parse_date", "(", "input", ")", "today", "=", "::", "Date", ".", "today", "return", "[", "today", ".", "year", ",", "today", ".", "month", ",", "today", ".", "day", ",", ":ignore", "]", "if", "input", ".", "empty?", "date", "=", "ISO8601", "::", "Date", ".", "new", "(", "input", ")", "date", ".", "atoms", "<<", "date", ".", "separator", "end" ]
Validates the date has the right pattern. Acceptable patterns: YYYY, YYYY-MM-DD, YYYYMMDD or YYYY-MM but not YYYYMM @param [String] input A date component @return [Array<String, nil>]
[ "Validates", "the", "date", "has", "the", "right", "pattern", "." ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/date_time.rb#L123-L130
19,913
arnau/ISO8601
lib/iso8601/date_time.rb
ISO8601.DateTime.valid_representation?
def valid_representation?(date, time) year, month, day = date hour = time.first date.nil? || !(!year.nil? && (month.nil? || day.nil?) && !hour.nil?) end
ruby
def valid_representation?(date, time) year, month, day = date hour = time.first date.nil? || !(!year.nil? && (month.nil? || day.nil?) && !hour.nil?) end
[ "def", "valid_representation?", "(", "date", ",", "time", ")", "year", ",", "month", ",", "day", "=", "date", "hour", "=", "time", ".", "first", "date", ".", "nil?", "||", "!", "(", "!", "year", ".", "nil?", "&&", "(", "month", ".", "nil?", "||", "day", ".", "nil?", ")", "&&", "!", "hour", ".", "nil?", ")", "end" ]
If time is provided date must use a complete representation
[ "If", "time", "is", "provided", "date", "must", "use", "a", "complete", "representation" ]
2b6e860f4052ce5b85c63814796f23b284644e0d
https://github.com/arnau/ISO8601/blob/2b6e860f4052ce5b85c63814796f23b284644e0d/lib/iso8601/date_time.rb#L154-L159
19,914
CocoaPods/cocoapods-search
spec/spec_helper/temporary_repos.rb
SpecHelper.TemporaryRepos.repo_make
def repo_make(name) path = repo_path(name) path.mkpath Dir.chdir(path) do `git init` repo_make_readme_change(name, 'Added') `git add .` `git commit -m "Initialized."` end path end
ruby
def repo_make(name) path = repo_path(name) path.mkpath Dir.chdir(path) do `git init` repo_make_readme_change(name, 'Added') `git add .` `git commit -m "Initialized."` end path end
[ "def", "repo_make", "(", "name", ")", "path", "=", "repo_path", "(", "name", ")", "path", ".", "mkpath", "Dir", ".", "chdir", "(", "path", ")", "do", "`", "`", "repo_make_readme_change", "(", "name", ",", "'Added'", ")", "`", "`", "`", "`", "end", "path", "end" ]
Makes a repo with the given name.
[ "Makes", "a", "repo", "with", "the", "given", "name", "." ]
452eee08d6497c43afd4452c28f9d7b8da8686f1
https://github.com/CocoaPods/cocoapods-search/blob/452eee08d6497c43afd4452c28f9d7b8da8686f1/spec/spec_helper/temporary_repos.rb#L18-L28
19,915
redhataccess/ascii_binder
lib/ascii_binder/engine.rb
AsciiBinder.Engine.local_branches
def local_branches @local_branches ||= begin branches = [] if not git.branches.local.empty? branches << git.branches.local.select{ |b| b.current }[0].name branches << git.branches.local.select{ |b| not b.current }.map{ |b| b.name } end branches.flatten end end
ruby
def local_branches @local_branches ||= begin branches = [] if not git.branches.local.empty? branches << git.branches.local.select{ |b| b.current }[0].name branches << git.branches.local.select{ |b| not b.current }.map{ |b| b.name } end branches.flatten end end
[ "def", "local_branches", "@local_branches", "||=", "begin", "branches", "=", "[", "]", "if", "not", "git", ".", "branches", ".", "local", ".", "empty?", "branches", "<<", "git", ".", "branches", ".", "local", ".", "select", "{", "|", "b", "|", "b", ".", "current", "}", "[", "0", "]", ".", "name", "branches", "<<", "git", ".", "branches", ".", "local", ".", "select", "{", "|", "b", "|", "not", "b", ".", "current", "}", ".", "map", "{", "|", "b", "|", "b", ".", "name", "}", "end", "branches", ".", "flatten", "end", "end" ]
Returns the local git branches; current branch is always first
[ "Returns", "the", "local", "git", "branches", ";", "current", "branch", "is", "always", "first" ]
1f89834654e2a4998f7194c05db3eba1343a11d2
https://github.com/redhataccess/ascii_binder/blob/1f89834654e2a4998f7194c05db3eba1343a11d2/lib/ascii_binder/engine.rb#L59-L68
19,916
cloudwalkio/da_funk
lib/iso8583/message.rb
ISO8583.Message.[]
def [](key) bmp_def = _get_definition key bmp = @values[bmp_def.bmp] bmp ? bmp.value : nil end
ruby
def [](key) bmp_def = _get_definition key bmp = @values[bmp_def.bmp] bmp ? bmp.value : nil end
[ "def", "[]", "(", "key", ")", "bmp_def", "=", "_get_definition", "key", "bmp", "=", "@values", "[", "bmp_def", ".", "bmp", "]", "bmp", "?", "bmp", ".", "value", ":", "nil", "end" ]
Retrieve the decoded value of the contents of a bitmap described either by the bitmap number or name. ===Example mes = BlaBlaMessage.parse someMessageBytes mes[2] # bmp 2 is generally the PAN mes["Primary Account Number"] # if thats what you called the field in Message.bmp.
[ "Retrieve", "the", "decoded", "value", "of", "the", "contents", "of", "a", "bitmap", "described", "either", "by", "the", "bitmap", "number", "or", "name", "." ]
cfa309b8165567e855ccdb80c700dbaa8133571b
https://github.com/cloudwalkio/da_funk/blob/cfa309b8165567e855ccdb80c700dbaa8133571b/lib/iso8583/message.rb#L173-L177
19,917
cloudwalkio/da_funk
lib/iso8583/message.rb
ISO8583.Message.to_s
def to_s _mti_name = _get_mti_definition(mti)[1] str = "MTI:#{mti} (#{_mti_name})\n\n" _max = @values.values.max {|a,b| a.name.length <=> b.name.length } _max_name = _max.name.length @values.keys.sort.each{|bmp_num| _bmp = @values[bmp_num] str += ("%03d %#{_max_name}s : %s\n" % [bmp_num, _bmp.name, _bmp.value]) } str end
ruby
def to_s _mti_name = _get_mti_definition(mti)[1] str = "MTI:#{mti} (#{_mti_name})\n\n" _max = @values.values.max {|a,b| a.name.length <=> b.name.length } _max_name = _max.name.length @values.keys.sort.each{|bmp_num| _bmp = @values[bmp_num] str += ("%03d %#{_max_name}s : %s\n" % [bmp_num, _bmp.name, _bmp.value]) } str end
[ "def", "to_s", "_mti_name", "=", "_get_mti_definition", "(", "mti", ")", "[", "1", "]", "str", "=", "\"MTI:#{mti} (#{_mti_name})\\n\\n\"", "_max", "=", "@values", ".", "values", ".", "max", "{", "|", "a", ",", "b", "|", "a", ".", "name", ".", "length", "<=>", "b", ".", "name", ".", "length", "}", "_max_name", "=", "_max", ".", "name", ".", "length", "@values", ".", "keys", ".", "sort", ".", "each", "{", "|", "bmp_num", "|", "_bmp", "=", "@values", "[", "bmp_num", "]", "str", "+=", "(", "\"%03d %#{_max_name}s : %s\\n\"", "%", "[", "bmp_num", ",", "_bmp", ".", "name", ",", "_bmp", ".", "value", "]", ")", "}", "str", "end" ]
Returns a nicely formatted representation of this message.
[ "Returns", "a", "nicely", "formatted", "representation", "of", "this", "message", "." ]
cfa309b8165567e855ccdb80c700dbaa8133571b
https://github.com/cloudwalkio/da_funk/blob/cfa309b8165567e855ccdb80c700dbaa8133571b/lib/iso8583/message.rb#L188-L201
19,918
cloudwalkio/da_funk
lib/iso8583/bitmap.rb
ISO8583.Bitmap.[]=
def []=(i, value) if i > 128 raise ISO8583Exception.new("Bits > 128 are not permitted.") elsif i < 2 raise ISO8583Exception.new("Bits < 2 are not permitted (continutation bit is set automatically)") end @bmp[i-1] = (value == true) end
ruby
def []=(i, value) if i > 128 raise ISO8583Exception.new("Bits > 128 are not permitted.") elsif i < 2 raise ISO8583Exception.new("Bits < 2 are not permitted (continutation bit is set automatically)") end @bmp[i-1] = (value == true) end
[ "def", "[]=", "(", "i", ",", "value", ")", "if", "i", ">", "128", "raise", "ISO8583Exception", ".", "new", "(", "\"Bits > 128 are not permitted.\"", ")", "elsif", "i", "<", "2", "raise", "ISO8583Exception", ".", "new", "(", "\"Bits < 2 are not permitted (continutation bit is set automatically)\"", ")", "end", "@bmp", "[", "i", "-", "1", "]", "=", "(", "value", "==", "true", ")", "end" ]
Set the bit to the indicated value. Only `true` sets the bit, any other value unsets it.
[ "Set", "the", "bit", "to", "the", "indicated", "value", ".", "Only", "true", "sets", "the", "bit", "any", "other", "value", "unsets", "it", "." ]
cfa309b8165567e855ccdb80c700dbaa8133571b
https://github.com/cloudwalkio/da_funk/blob/cfa309b8165567e855ccdb80c700dbaa8133571b/lib/iso8583/bitmap.rb#L41-L48
19,919
cloudwalkio/da_funk
lib/iso8583/bitmap.rb
ISO8583.Bitmap.to_bytes
def to_bytes # Convert binary to hex, by slicing the binary in 4 bytes chuncks bitmap_hex = "" str = "" self.to_s.chars.reverse.each_with_index do |ch, i| str << ch next if i == 0 if (i+1) % 4 == 0 bitmap_hex << str.reverse.to_i(2).to_s(16) str = "" end end unless str.empty? bitmap_hex << str.reverse.to_i(2).to_s(16) end bitmap_hex.reverse.upcase end
ruby
def to_bytes # Convert binary to hex, by slicing the binary in 4 bytes chuncks bitmap_hex = "" str = "" self.to_s.chars.reverse.each_with_index do |ch, i| str << ch next if i == 0 if (i+1) % 4 == 0 bitmap_hex << str.reverse.to_i(2).to_s(16) str = "" end end unless str.empty? bitmap_hex << str.reverse.to_i(2).to_s(16) end bitmap_hex.reverse.upcase end
[ "def", "to_bytes", "# Convert binary to hex, by slicing the binary in 4 bytes chuncks", "bitmap_hex", "=", "\"\"", "str", "=", "\"\"", "self", ".", "to_s", ".", "chars", ".", "reverse", ".", "each_with_index", "do", "|", "ch", ",", "i", "|", "str", "<<", "ch", "next", "if", "i", "==", "0", "if", "(", "i", "+", "1", ")", "%", "4", "==", "0", "bitmap_hex", "<<", "str", ".", "reverse", ".", "to_i", "(", "2", ")", ".", "to_s", "(", "16", ")", "str", "=", "\"\"", "end", "end", "unless", "str", ".", "empty?", "bitmap_hex", "<<", "str", ".", "reverse", ".", "to_i", "(", "2", ")", ".", "to_s", "(", "16", ")", "end", "bitmap_hex", ".", "reverse", ".", "upcase", "end" ]
Generate the bytes representing this bitmap.
[ "Generate", "the", "bytes", "representing", "this", "bitmap", "." ]
cfa309b8165567e855ccdb80c700dbaa8133571b
https://github.com/cloudwalkio/da_funk/blob/cfa309b8165567e855ccdb80c700dbaa8133571b/lib/iso8583/bitmap.rb#L61-L77
19,920
cloudwalkio/da_funk
lib/da_funk/helper.rb
DaFunk.Helper.try_user
def try_user(timeout = Device::IO.timeout, options = nil, &block) time = timeout != 0 ? Time.now + timeout / 1000 : Time.now processing = Hash.new(keep: true) interation = 0 files = options[:bmps][:attach_loop] if options && options[:bmps].is_a?(Hash) max = (files.size - 1) if files while(processing[:keep] && processing[:key] != Device::IO::CANCEL) do if files Device::Display.print_bitmap(files[interation]) interation = (max >= interation) ? interation + 1 : 0 end if processing[:keep] = block.call(processing) processing[:key] = getc(200) end break if time < Time.now end processing end
ruby
def try_user(timeout = Device::IO.timeout, options = nil, &block) time = timeout != 0 ? Time.now + timeout / 1000 : Time.now processing = Hash.new(keep: true) interation = 0 files = options[:bmps][:attach_loop] if options && options[:bmps].is_a?(Hash) max = (files.size - 1) if files while(processing[:keep] && processing[:key] != Device::IO::CANCEL) do if files Device::Display.print_bitmap(files[interation]) interation = (max >= interation) ? interation + 1 : 0 end if processing[:keep] = block.call(processing) processing[:key] = getc(200) end break if time < Time.now end processing end
[ "def", "try_user", "(", "timeout", "=", "Device", "::", "IO", ".", "timeout", ",", "options", "=", "nil", ",", "&", "block", ")", "time", "=", "timeout", "!=", "0", "?", "Time", ".", "now", "+", "timeout", "/", "1000", ":", "Time", ".", "now", "processing", "=", "Hash", ".", "new", "(", "keep", ":", "true", ")", "interation", "=", "0", "files", "=", "options", "[", ":bmps", "]", "[", ":attach_loop", "]", "if", "options", "&&", "options", "[", ":bmps", "]", ".", "is_a?", "(", "Hash", ")", "max", "=", "(", "files", ".", "size", "-", "1", ")", "if", "files", "while", "(", "processing", "[", ":keep", "]", "&&", "processing", "[", ":key", "]", "!=", "Device", "::", "IO", "::", "CANCEL", ")", "do", "if", "files", "Device", "::", "Display", ".", "print_bitmap", "(", "files", "[", "interation", "]", ")", "interation", "=", "(", "max", ">=", "interation", ")", "?", "interation", "+", "1", ":", "0", "end", "if", "processing", "[", ":keep", "]", "=", "block", ".", "call", "(", "processing", ")", "processing", "[", ":key", "]", "=", "getc", "(", "200", ")", "end", "break", "if", "time", "<", "Time", ".", "now", "end", "processing", "end" ]
must send nonblock proc
[ "must", "send", "nonblock", "proc" ]
cfa309b8165567e855ccdb80c700dbaa8133571b
https://github.com/cloudwalkio/da_funk/blob/cfa309b8165567e855ccdb80c700dbaa8133571b/lib/da_funk/helper.rb#L112-L130
19,921
cloudwalkio/da_funk
lib/da_funk/helper.rb
DaFunk.Helper.menu
def menu(title, selection, options = {}) return nil if selection.empty? options[:number] = true if options[:number].nil? options[:timeout] ||= Device::IO.timeout key, selected = pagination(title, options, selection) do |collection, line_zero| collection.each_with_index do |value,i| display = value.is_a?(Array) ? value[0] : value if options[:number] Device::Display.print("#{i+1} #{display}", i+line_zero, 0) else unless display.to_s.empty? Device::Display.print("#{display}", i+line_zero, 0) end end end end if key == Device::IO::ENTER || key == Device::IO::CANCEL options[:default] else selected end end
ruby
def menu(title, selection, options = {}) return nil if selection.empty? options[:number] = true if options[:number].nil? options[:timeout] ||= Device::IO.timeout key, selected = pagination(title, options, selection) do |collection, line_zero| collection.each_with_index do |value,i| display = value.is_a?(Array) ? value[0] : value if options[:number] Device::Display.print("#{i+1} #{display}", i+line_zero, 0) else unless display.to_s.empty? Device::Display.print("#{display}", i+line_zero, 0) end end end end if key == Device::IO::ENTER || key == Device::IO::CANCEL options[:default] else selected end end
[ "def", "menu", "(", "title", ",", "selection", ",", "options", "=", "{", "}", ")", "return", "nil", "if", "selection", ".", "empty?", "options", "[", ":number", "]", "=", "true", "if", "options", "[", ":number", "]", ".", "nil?", "options", "[", ":timeout", "]", "||=", "Device", "::", "IO", ".", "timeout", "key", ",", "selected", "=", "pagination", "(", "title", ",", "options", ",", "selection", ")", "do", "|", "collection", ",", "line_zero", "|", "collection", ".", "each_with_index", "do", "|", "value", ",", "i", "|", "display", "=", "value", ".", "is_a?", "(", "Array", ")", "?", "value", "[", "0", "]", ":", "value", "if", "options", "[", ":number", "]", "Device", "::", "Display", ".", "print", "(", "\"#{i+1} #{display}\"", ",", "i", "+", "line_zero", ",", "0", ")", "else", "unless", "display", ".", "to_s", ".", "empty?", "Device", "::", "Display", ".", "print", "(", "\"#{display}\"", ",", "i", "+", "line_zero", ",", "0", ")", "end", "end", "end", "end", "if", "key", "==", "Device", "::", "IO", "::", "ENTER", "||", "key", "==", "Device", "::", "IO", "::", "CANCEL", "options", "[", ":default", "]", "else", "selected", "end", "end" ]
Create a form menu. @param title [String] Text to display on line 0. If nil title won't be displayed and Display.clear won't be called on before the option show. @param selection [Hash] Hash (display text => value that will return) containing the list options. @param options [Hash] Hash containing options to change the menu behaviour. @example options = { # default value to return if enter, you can work with complex data. :default => 10, # Add number to label or not :number => true, # Input Timeout in miliseconds :timeout => 30_000 } selection = { "option X" => 10, "option Y" => 11 } menu("Option menu", selection, options)
[ "Create", "a", "form", "menu", "." ]
cfa309b8165567e855ccdb80c700dbaa8133571b
https://github.com/cloudwalkio/da_funk/blob/cfa309b8165567e855ccdb80c700dbaa8133571b/lib/da_funk/helper.rb#L173-L195
19,922
oggy/looksee
lib/looksee/editor.rb
Looksee.Editor.edit
def edit(object, method_name) method = LookupPath.new(object).find(method_name.to_s) or raise NoMethodError, "no method `#{method_name}' in lookup path of #{object.class} instance" file, line = method.source_location if !file raise NoSourceLocationError, "no source location for #{method.owner}##{method.name}" elsif !File.exist?(file) raise NoSourceFileError, "cannot find source file: #{file}" else run(file, line) end end
ruby
def edit(object, method_name) method = LookupPath.new(object).find(method_name.to_s) or raise NoMethodError, "no method `#{method_name}' in lookup path of #{object.class} instance" file, line = method.source_location if !file raise NoSourceLocationError, "no source location for #{method.owner}##{method.name}" elsif !File.exist?(file) raise NoSourceFileError, "cannot find source file: #{file}" else run(file, line) end end
[ "def", "edit", "(", "object", ",", "method_name", ")", "method", "=", "LookupPath", ".", "new", "(", "object", ")", ".", "find", "(", "method_name", ".", "to_s", ")", "or", "raise", "NoMethodError", ",", "\"no method `#{method_name}' in lookup path of #{object.class} instance\"", "file", ",", "line", "=", "method", ".", "source_location", "if", "!", "file", "raise", "NoSourceLocationError", ",", "\"no source location for #{method.owner}##{method.name}\"", "elsif", "!", "File", ".", "exist?", "(", "file", ")", "raise", "NoSourceFileError", ",", "\"cannot find source file: #{file}\"", "else", "run", "(", "file", ",", "line", ")", "end", "end" ]
Run the editor command for the +method_name+ of +object+.
[ "Run", "the", "editor", "command", "for", "the", "+", "method_name", "+", "of", "+", "object", "+", "." ]
d3107e4fa497d45eb70b3d4badc1d124074da964
https://github.com/oggy/looksee/blob/d3107e4fa497d45eb70b3d4badc1d124074da964/lib/looksee/editor.rb#L15-L26
19,923
oggy/looksee
lib/looksee/editor.rb
Looksee.Editor.command_for
def command_for(file, line) line = line.to_s words = Shellwords.shellwords(command) words.map! do |word| word.gsub!(/%f/, file) word.gsub!(/%l/, line) word.gsub!(/%%/, '%') word end end
ruby
def command_for(file, line) line = line.to_s words = Shellwords.shellwords(command) words.map! do |word| word.gsub!(/%f/, file) word.gsub!(/%l/, line) word.gsub!(/%%/, '%') word end end
[ "def", "command_for", "(", "file", ",", "line", ")", "line", "=", "line", ".", "to_s", "words", "=", "Shellwords", ".", "shellwords", "(", "command", ")", "words", ".", "map!", "do", "|", "word", "|", "word", ".", "gsub!", "(", "/", "/", ",", "file", ")", "word", ".", "gsub!", "(", "/", "/", ",", "line", ")", "word", ".", "gsub!", "(", "/", "/", ",", "'%'", ")", "word", "end", "end" ]
Return the editor command for the given file and line. This is an array of the command with its arguments.
[ "Return", "the", "editor", "command", "for", "the", "given", "file", "and", "line", "." ]
d3107e4fa497d45eb70b3d4badc1d124074da964
https://github.com/oggy/looksee/blob/d3107e4fa497d45eb70b3d4badc1d124074da964/lib/looksee/editor.rb#L40-L49
19,924
oggy/looksee
lib/looksee/inspector.rb
Looksee.Inspector.edit
def edit(name) Editor.new(Looksee.editor).edit(lookup_path.object, name) end
ruby
def edit(name) Editor.new(Looksee.editor).edit(lookup_path.object, name) end
[ "def", "edit", "(", "name", ")", "Editor", ".", "new", "(", "Looksee", ".", "editor", ")", ".", "edit", "(", "lookup_path", ".", "object", ",", "name", ")", "end" ]
Open an editor at the named method's definition. Uses Looksee.editor to determine the editor command to run. Only works for methods for which file and line numbers are accessible.
[ "Open", "an", "editor", "at", "the", "named", "method", "s", "definition", "." ]
d3107e4fa497d45eb70b3d4badc1d124074da964
https://github.com/oggy/looksee/blob/d3107e4fa497d45eb70b3d4badc1d124074da964/lib/looksee/inspector.rb#L31-L33
19,925
p0deje/watirsome
lib/watirsome/regions.rb
Watirsome.Regions.has_one
def has_one(region_name, **opts, &block) within = opts[:in] || opts[:within] region_class = opts[:class] || opts[:region_class] define_region_accessor(region_name, within: within, region_class: region_class, &block) end
ruby
def has_one(region_name, **opts, &block) within = opts[:in] || opts[:within] region_class = opts[:class] || opts[:region_class] define_region_accessor(region_name, within: within, region_class: region_class, &block) end
[ "def", "has_one", "(", "region_name", ",", "**", "opts", ",", "&", "block", ")", "within", "=", "opts", "[", ":in", "]", "||", "opts", "[", ":within", "]", "region_class", "=", "opts", "[", ":class", "]", "||", "opts", "[", ":region_class", "]", "define_region_accessor", "(", "region_name", ",", "within", ":", "within", ",", "region_class", ":", "region_class", ",", "block", ")", "end" ]
Defines region accessor. @param [Symbol] region_name @param [Hash|Proc] in, optional, alias: within @param [Class] class, optional, alias: region_class @param [Block] block
[ "Defines", "region", "accessor", "." ]
1c3283fced017659ec03dbaaf0bc3e82d116a08e
https://github.com/p0deje/watirsome/blob/1c3283fced017659ec03dbaaf0bc3e82d116a08e/lib/watirsome/regions.rb#L11-L15
19,926
p0deje/watirsome
lib/watirsome/regions.rb
Watirsome.Regions.has_many
def has_many(region_name, **opts, &block) region_class = opts[:class] || opts[:region_class] collection_class = opts[:through] || opts[:collection_class] each = opts[:each] || raise(ArgumentError, '"has_many" method requires "each" param') within = opts[:in] || opts[:within] define_region_accessor(region_name, within: within, each: each, region_class: region_class, collection_class: collection_class, &block) define_finder_method(region_name) end
ruby
def has_many(region_name, **opts, &block) region_class = opts[:class] || opts[:region_class] collection_class = opts[:through] || opts[:collection_class] each = opts[:each] || raise(ArgumentError, '"has_many" method requires "each" param') within = opts[:in] || opts[:within] define_region_accessor(region_name, within: within, each: each, region_class: region_class, collection_class: collection_class, &block) define_finder_method(region_name) end
[ "def", "has_many", "(", "region_name", ",", "**", "opts", ",", "&", "block", ")", "region_class", "=", "opts", "[", ":class", "]", "||", "opts", "[", ":region_class", "]", "collection_class", "=", "opts", "[", ":through", "]", "||", "opts", "[", ":collection_class", "]", "each", "=", "opts", "[", ":each", "]", "||", "raise", "(", "ArgumentError", ",", "'\"has_many\" method requires \"each\" param'", ")", "within", "=", "opts", "[", ":in", "]", "||", "opts", "[", ":within", "]", "define_region_accessor", "(", "region_name", ",", "within", ":", "within", ",", "each", ":", "each", ",", "region_class", ":", "region_class", ",", "collection_class", ":", "collection_class", ",", "block", ")", "define_finder_method", "(", "region_name", ")", "end" ]
Defines multiple regions accessor. @param [Symbol] region_name @param [Hash|Proc] in, optional, alias: within @param [Hash] each, required @param [Class] class, optional, alias: region_class @param [Class] through, optional, alias collection_class @param [Block] block, optional
[ "Defines", "multiple", "regions", "accessor", "." ]
1c3283fced017659ec03dbaaf0bc3e82d116a08e
https://github.com/p0deje/watirsome/blob/1c3283fced017659ec03dbaaf0bc3e82d116a08e/lib/watirsome/regions.rb#L27-L34
19,927
tradegecko/gecko
lib/gecko/client.rb
Gecko.Client.authorize_from_refresh_token
def authorize_from_refresh_token(refresh_token) @access_token = oauth_client.get_token({ client_id: oauth_client.id, client_secret: oauth_client.secret, refresh_token: refresh_token, grant_type: 'refresh_token' }) end
ruby
def authorize_from_refresh_token(refresh_token) @access_token = oauth_client.get_token({ client_id: oauth_client.id, client_secret: oauth_client.secret, refresh_token: refresh_token, grant_type: 'refresh_token' }) end
[ "def", "authorize_from_refresh_token", "(", "refresh_token", ")", "@access_token", "=", "oauth_client", ".", "get_token", "(", "{", "client_id", ":", "oauth_client", ".", "id", ",", "client_secret", ":", "oauth_client", ".", "secret", ",", "refresh_token", ":", "refresh_token", ",", "grant_type", ":", "'refresh_token'", "}", ")", "end" ]
Authorize client by fetching a new access_token via refresh token @example client.authorize_from_refresh_token("DEF") @param [String] refresh_token @return [OAuth2::AccessToken] @api public
[ "Authorize", "client", "by", "fetching", "a", "new", "access_token", "via", "refresh", "token" ]
1c9ed6d9c20db58e0fa9edb7c227ce16582fa3fb
https://github.com/tradegecko/gecko/blob/1c9ed6d9c20db58e0fa9edb7c227ce16582fa3fb/lib/gecko/client.rb#L93-L100
19,928
projecttacoma/cqm-models
app/models/cqm/measure.rb
CQM.Measure.as_hqmf_model
def as_hqmf_model json = { 'id' => hqmf_id, 'title' => title, 'description' => description, 'population_criteria' => population_criteria, 'data_criteria' => data_criteria, 'source_data_criteria' => source_data_criteria, 'measure_period' => measure_period, 'attributes' => measure_attributes, 'populations' => populations, 'hqmf_id' => hqmf_id, 'hqmf_set_id' => hqmf_set_id, 'hqmf_version_number' => hqmf_version_number, 'cms_id' => cms_id } HQMF::Document.from_json(json) end
ruby
def as_hqmf_model json = { 'id' => hqmf_id, 'title' => title, 'description' => description, 'population_criteria' => population_criteria, 'data_criteria' => data_criteria, 'source_data_criteria' => source_data_criteria, 'measure_period' => measure_period, 'attributes' => measure_attributes, 'populations' => populations, 'hqmf_id' => hqmf_id, 'hqmf_set_id' => hqmf_set_id, 'hqmf_version_number' => hqmf_version_number, 'cms_id' => cms_id } HQMF::Document.from_json(json) end
[ "def", "as_hqmf_model", "json", "=", "{", "'id'", "=>", "hqmf_id", ",", "'title'", "=>", "title", ",", "'description'", "=>", "description", ",", "'population_criteria'", "=>", "population_criteria", ",", "'data_criteria'", "=>", "data_criteria", ",", "'source_data_criteria'", "=>", "source_data_criteria", ",", "'measure_period'", "=>", "measure_period", ",", "'attributes'", "=>", "measure_attributes", ",", "'populations'", "=>", "populations", ",", "'hqmf_id'", "=>", "hqmf_id", ",", "'hqmf_set_id'", "=>", "hqmf_set_id", ",", "'hqmf_version_number'", "=>", "hqmf_version_number", ",", "'cms_id'", "=>", "cms_id", "}", "HQMF", "::", "Document", ".", "from_json", "(", "json", ")", "end" ]
Returns the hqmf-parser's ruby implementation of an HQMF document. Rebuild from population_criteria, data_criteria, and measure_period JSON
[ "Returns", "the", "hqmf", "-", "parser", "s", "ruby", "implementation", "of", "an", "HQMF", "document", ".", "Rebuild", "from", "population_criteria", "data_criteria", "and", "measure_period", "JSON" ]
d1ccbea6451f02fed3c5ef4e443a53bc6f29b000
https://github.com/projecttacoma/cqm-models/blob/d1ccbea6451f02fed3c5ef4e443a53bc6f29b000/app/models/cqm/measure.rb#L85-L102
19,929
projecttacoma/cqm-models
app/models/qdm/basetypes/data_element.rb
QDM.DataElement.code_system_pairs
def code_system_pairs codes.collect do |code| { code: code.code, system: code.codeSystem } end end
ruby
def code_system_pairs codes.collect do |code| { code: code.code, system: code.codeSystem } end end
[ "def", "code_system_pairs", "codes", ".", "collect", "do", "|", "code", "|", "{", "code", ":", "code", ".", "code", ",", "system", ":", "code", ".", "codeSystem", "}", "end", "end" ]
Returns all of the codes on this datatype in a way that is typical to the CQL execution engine.
[ "Returns", "all", "of", "the", "codes", "on", "this", "datatype", "in", "a", "way", "that", "is", "typical", "to", "the", "CQL", "execution", "engine", "." ]
d1ccbea6451f02fed3c5ef4e443a53bc6f29b000
https://github.com/projecttacoma/cqm-models/blob/d1ccbea6451f02fed3c5ef4e443a53bc6f29b000/app/models/qdm/basetypes/data_element.rb#L32-L36
19,930
projecttacoma/cqm-models
app/models/qdm/basetypes/data_element.rb
QDM.DataElement.shift_dates
def shift_dates(seconds) # Iterate over fields fields.keys.each do |field| # Check if field is a DateTime if send(field).is_a? DateTime send(field + '=', (send(field).to_time + seconds.seconds).to_datetime) end # Check if field is an Interval if (send(field).is_a? Interval) || (send(field).is_a? DataElement) send(field + '=', send(field).shift_dates(seconds)) end # Special case for facility locations if field == 'facilityLocations' send(field).each do |facility_location| shift_facility_location_dates(facility_location, seconds) end elsif field == 'facilityLocation' facility_location = send(field) unless facility_location.nil? shift_facility_location_dates(facility_location, seconds) send(field + '=', facility_location) end end end end
ruby
def shift_dates(seconds) # Iterate over fields fields.keys.each do |field| # Check if field is a DateTime if send(field).is_a? DateTime send(field + '=', (send(field).to_time + seconds.seconds).to_datetime) end # Check if field is an Interval if (send(field).is_a? Interval) || (send(field).is_a? DataElement) send(field + '=', send(field).shift_dates(seconds)) end # Special case for facility locations if field == 'facilityLocations' send(field).each do |facility_location| shift_facility_location_dates(facility_location, seconds) end elsif field == 'facilityLocation' facility_location = send(field) unless facility_location.nil? shift_facility_location_dates(facility_location, seconds) send(field + '=', facility_location) end end end end
[ "def", "shift_dates", "(", "seconds", ")", "# Iterate over fields", "fields", ".", "keys", ".", "each", "do", "|", "field", "|", "# Check if field is a DateTime", "if", "send", "(", "field", ")", ".", "is_a?", "DateTime", "send", "(", "field", "+", "'='", ",", "(", "send", "(", "field", ")", ".", "to_time", "+", "seconds", ".", "seconds", ")", ".", "to_datetime", ")", "end", "# Check if field is an Interval", "if", "(", "send", "(", "field", ")", ".", "is_a?", "Interval", ")", "||", "(", "send", "(", "field", ")", ".", "is_a?", "DataElement", ")", "send", "(", "field", "+", "'='", ",", "send", "(", "field", ")", ".", "shift_dates", "(", "seconds", ")", ")", "end", "# Special case for facility locations", "if", "field", "==", "'facilityLocations'", "send", "(", "field", ")", ".", "each", "do", "|", "facility_location", "|", "shift_facility_location_dates", "(", "facility_location", ",", "seconds", ")", "end", "elsif", "field", "==", "'facilityLocation'", "facility_location", "=", "send", "(", "field", ")", "unless", "facility_location", ".", "nil?", "shift_facility_location_dates", "(", "facility_location", ",", "seconds", ")", "send", "(", "field", "+", "'='", ",", "facility_location", ")", "end", "end", "end", "end" ]
Shift all fields that deal with dates by the given value. Given value should be in seconds. Positive values shift forward, negative values shift backwards.
[ "Shift", "all", "fields", "that", "deal", "with", "dates", "by", "the", "given", "value", ".", "Given", "value", "should", "be", "in", "seconds", ".", "Positive", "values", "shift", "forward", "negative", "values", "shift", "backwards", "." ]
d1ccbea6451f02fed3c5ef4e443a53bc6f29b000
https://github.com/projecttacoma/cqm-models/blob/d1ccbea6451f02fed3c5ef4e443a53bc6f29b000/app/models/qdm/basetypes/data_element.rb#L60-L85
19,931
projecttacoma/cqm-models
app/models/qdm/basetypes/interval.rb
QDM.Interval.shift_dates
def shift_dates(seconds) if (@low.is_a? DateTime) || (@low.is_a? Time) @low = (@low.utc.to_time + seconds.seconds).to_datetime.new_offset(0) end if (@high.is_a? DateTime) || (@high.is_a? Time) @high = (@high.utc.to_time + seconds.seconds).to_datetime.new_offset(0) @high = @high.year > 9999 ? @high.change(year: 9999) : @high end self end
ruby
def shift_dates(seconds) if (@low.is_a? DateTime) || (@low.is_a? Time) @low = (@low.utc.to_time + seconds.seconds).to_datetime.new_offset(0) end if (@high.is_a? DateTime) || (@high.is_a? Time) @high = (@high.utc.to_time + seconds.seconds).to_datetime.new_offset(0) @high = @high.year > 9999 ? @high.change(year: 9999) : @high end self end
[ "def", "shift_dates", "(", "seconds", ")", "if", "(", "@low", ".", "is_a?", "DateTime", ")", "||", "(", "@low", ".", "is_a?", "Time", ")", "@low", "=", "(", "@low", ".", "utc", ".", "to_time", "+", "seconds", ".", "seconds", ")", ".", "to_datetime", ".", "new_offset", "(", "0", ")", "end", "if", "(", "@high", ".", "is_a?", "DateTime", ")", "||", "(", "@high", ".", "is_a?", "Time", ")", "@high", "=", "(", "@high", ".", "utc", ".", "to_time", "+", "seconds", ".", "seconds", ")", ".", "to_datetime", ".", "new_offset", "(", "0", ")", "@high", "=", "@high", ".", "year", ">", "9999", "?", "@high", ".", "change", "(", "year", ":", "9999", ")", ":", "@high", "end", "self", "end" ]
Shift dates by the given value. Given value should be in seconds. Positive values shift forward, negative values shift backwards. NOTE: This will only shift if @high and @low are DateTimes.
[ "Shift", "dates", "by", "the", "given", "value", ".", "Given", "value", "should", "be", "in", "seconds", ".", "Positive", "values", "shift", "forward", "negative", "values", "shift", "backwards", "." ]
d1ccbea6451f02fed3c5ef4e443a53bc6f29b000
https://github.com/projecttacoma/cqm-models/blob/d1ccbea6451f02fed3c5ef4e443a53bc6f29b000/app/models/qdm/basetypes/interval.rb#L24-L33
19,932
projecttacoma/cqm-models
app/models/qdm/patient.rb
QDM.Patient.shift_dates
def shift_dates(seconds) self.birthDatetime = (birthDatetime.utc.to_time + seconds.seconds).to_datetime dataElements.each { |element| element.shift_dates(seconds) } end
ruby
def shift_dates(seconds) self.birthDatetime = (birthDatetime.utc.to_time + seconds.seconds).to_datetime dataElements.each { |element| element.shift_dates(seconds) } end
[ "def", "shift_dates", "(", "seconds", ")", "self", ".", "birthDatetime", "=", "(", "birthDatetime", ".", "utc", ".", "to_time", "+", "seconds", ".", "seconds", ")", ".", "to_datetime", "dataElements", ".", "each", "{", "|", "element", "|", "element", ".", "shift_dates", "(", "seconds", ")", "}", "end" ]
Shift all data element fields that deal with dates by the given value. Given value should be in seconds. Positive values shift forward, negative values shift backwards. Note: This will shift dates of the birthdate and dates on the data elements that exist on the patient.
[ "Shift", "all", "data", "element", "fields", "that", "deal", "with", "dates", "by", "the", "given", "value", ".", "Given", "value", "should", "be", "in", "seconds", ".", "Positive", "values", "shift", "forward", "negative", "values", "shift", "backwards", "." ]
d1ccbea6451f02fed3c5ef4e443a53bc6f29b000
https://github.com/projecttacoma/cqm-models/blob/d1ccbea6451f02fed3c5ef4e443a53bc6f29b000/app/models/qdm/patient.rb#L36-L39
19,933
ministryofjustice/govuk_elements_form_builder
lib/govuk_elements_form_builder/form_builder.rb
GovukElementsFormBuilder.FormBuilder.fields_for
def fields_for record_name, record_object = nil, fields_options = {}, &block super record_name, record_object, fields_options.merge(builder: self.class), &block end
ruby
def fields_for record_name, record_object = nil, fields_options = {}, &block super record_name, record_object, fields_options.merge(builder: self.class), &block end
[ "def", "fields_for", "record_name", ",", "record_object", "=", "nil", ",", "fields_options", "=", "{", "}", ",", "&", "block", "super", "record_name", ",", "record_object", ",", "fields_options", ".", "merge", "(", "builder", ":", "self", ".", "class", ")", ",", "block", "end" ]
Ensure fields_for yields a GovukElementsFormBuilder.
[ "Ensure", "fields_for", "yields", "a", "GovukElementsFormBuilder", "." ]
3049c945f46e61a1a2264346f3ce5f7b60a7c8f4
https://github.com/ministryofjustice/govuk_elements_form_builder/blob/3049c945f46e61a1a2264346f3ce5f7b60a7c8f4/lib/govuk_elements_form_builder/form_builder.rb#L15-L17
19,934
ministryofjustice/govuk_elements_form_builder
lib/govuk_elements_form_builder/form_builder.rb
GovukElementsFormBuilder.FormBuilder.merge_attributes
def merge_attributes attributes, default: hash = attributes || {} hash.merge(default) { |_key, oldval, newval| Array(newval) + Array(oldval) } end
ruby
def merge_attributes attributes, default: hash = attributes || {} hash.merge(default) { |_key, oldval, newval| Array(newval) + Array(oldval) } end
[ "def", "merge_attributes", "attributes", ",", "default", ":", "hash", "=", "attributes", "||", "{", "}", "hash", ".", "merge", "(", "default", ")", "{", "|", "_key", ",", "oldval", ",", "newval", "|", "Array", "(", "newval", ")", "+", "Array", "(", "oldval", ")", "}", "end" ]
Given an attributes hash that could include any number of arbitrary keys, this method ensure we merge one or more 'default' attributes into the hash, creating the keys if don't exist, or merging the defaults if the keys already exists. It supports strings or arrays as values.
[ "Given", "an", "attributes", "hash", "that", "could", "include", "any", "number", "of", "arbitrary", "keys", "this", "method", "ensure", "we", "merge", "one", "or", "more", "default", "attributes", "into", "the", "hash", "creating", "the", "keys", "if", "don", "t", "exist", "or", "merging", "the", "defaults", "if", "the", "keys", "already", "exists", ".", "It", "supports", "strings", "or", "arrays", "as", "values", "." ]
3049c945f46e61a1a2264346f3ce5f7b60a7c8f4
https://github.com/ministryofjustice/govuk_elements_form_builder/blob/3049c945f46e61a1a2264346f3ce5f7b60a7c8f4/lib/govuk_elements_form_builder/form_builder.rb#L178-L181
19,935
hashicorp/vagrant_cloud
lib/vagrant_cloud/box.rb
VagrantCloud.Box.update
def update(args = {}) # hash arguments kept for backwards compatibility return @data if args.empty? org = args[:organization] || account.username box_name = args[:name] || @name data = @client.request('put', box_path(org, box_name), box: args) # Update was called on *this* object, so update # objects data locally @data = data if !args[:organization] && !args[:name] data end
ruby
def update(args = {}) # hash arguments kept for backwards compatibility return @data if args.empty? org = args[:organization] || account.username box_name = args[:name] || @name data = @client.request('put', box_path(org, box_name), box: args) # Update was called on *this* object, so update # objects data locally @data = data if !args[:organization] && !args[:name] data end
[ "def", "update", "(", "args", "=", "{", "}", ")", "# hash arguments kept for backwards compatibility", "return", "@data", "if", "args", ".", "empty?", "org", "=", "args", "[", ":organization", "]", "||", "account", ".", "username", "box_name", "=", "args", "[", ":name", "]", "||", "@name", "data", "=", "@client", ".", "request", "(", "'put'", ",", "box_path", "(", "org", ",", "box_name", ")", ",", "box", ":", "args", ")", "# Update was called on *this* object, so update", "# objects data locally", "@data", "=", "data", "if", "!", "args", "[", ":organization", "]", "&&", "!", "args", "[", ":name", "]", "data", "end" ]
Update a box @param [Hash] args @param [String] org - organization of the box to read @param [String] box_name - name of the box to read @return [Hash] @data
[ "Update", "a", "box" ]
f3f5f96277ba93371a351acbd50d1183b611787f
https://github.com/hashicorp/vagrant_cloud/blob/f3f5f96277ba93371a351acbd50d1183b611787f/lib/vagrant_cloud/box.rb#L37-L50
19,936
hashicorp/vagrant_cloud
lib/vagrant_cloud/search.rb
VagrantCloud.Search.search
def search(query = nil, provider = nil, sort = nil, order = nil, limit = nil, page = nil) params = { q: query, provider: provider, sort: sort, order: order, limit: limit, page: page }.delete_if { |_, v| v.nil? } @client.request('get', '/search', params) end
ruby
def search(query = nil, provider = nil, sort = nil, order = nil, limit = nil, page = nil) params = { q: query, provider: provider, sort: sort, order: order, limit: limit, page: page }.delete_if { |_, v| v.nil? } @client.request('get', '/search', params) end
[ "def", "search", "(", "query", "=", "nil", ",", "provider", "=", "nil", ",", "sort", "=", "nil", ",", "order", "=", "nil", ",", "limit", "=", "nil", ",", "page", "=", "nil", ")", "params", "=", "{", "q", ":", "query", ",", "provider", ":", "provider", ",", "sort", ":", "sort", ",", "order", ":", "order", ",", "limit", ":", "limit", ",", "page", ":", "page", "}", ".", "delete_if", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "@client", ".", "request", "(", "'get'", ",", "'/search'", ",", "params", ")", "end" ]
Requests a search based on the given parameters @param [String] query @param [String] provider @param [String] sort @param [String] order @param [String] limit @param [String] page @return [Hash]
[ "Requests", "a", "search", "based", "on", "the", "given", "parameters" ]
f3f5f96277ba93371a351acbd50d1183b611787f
https://github.com/hashicorp/vagrant_cloud/blob/f3f5f96277ba93371a351acbd50d1183b611787f/lib/vagrant_cloud/search.rb#L18-L29
19,937
htdebeer/paru
lib/paru/filter.rb
Paru.Filter.filter
def filter(&block) @selectors = Hash.new @filtered_nodes = [] @document = read_document @metadata = PandocFilter::Metadata.new @document.meta nodes_to_filter = Enumerator.new do |node_list| @document.each_depth_first do |node| node_list << node end end @current_node = @document nodes_to_filter.each do |node| if @current_node.has_been_replaced? @current_node = @current_node.get_replacement @filtered_nodes.pop else @current_node = node end @filtered_nodes.push @current_node instance_eval(&block) # run the actual filter code end write_document end
ruby
def filter(&block) @selectors = Hash.new @filtered_nodes = [] @document = read_document @metadata = PandocFilter::Metadata.new @document.meta nodes_to_filter = Enumerator.new do |node_list| @document.each_depth_first do |node| node_list << node end end @current_node = @document nodes_to_filter.each do |node| if @current_node.has_been_replaced? @current_node = @current_node.get_replacement @filtered_nodes.pop else @current_node = node end @filtered_nodes.push @current_node instance_eval(&block) # run the actual filter code end write_document end
[ "def", "filter", "(", "&", "block", ")", "@selectors", "=", "Hash", ".", "new", "@filtered_nodes", "=", "[", "]", "@document", "=", "read_document", "@metadata", "=", "PandocFilter", "::", "Metadata", ".", "new", "@document", ".", "meta", "nodes_to_filter", "=", "Enumerator", ".", "new", "do", "|", "node_list", "|", "@document", ".", "each_depth_first", "do", "|", "node", "|", "node_list", "<<", "node", "end", "end", "@current_node", "=", "@document", "nodes_to_filter", ".", "each", "do", "|", "node", "|", "if", "@current_node", ".", "has_been_replaced?", "@current_node", "=", "@current_node", ".", "get_replacement", "@filtered_nodes", ".", "pop", "else", "@current_node", "=", "node", "end", "@filtered_nodes", ".", "push", "@current_node", "instance_eval", "(", "block", ")", "# run the actual filter code", "end", "write_document", "end" ]
Create a filter using +block+. In the block you specify selectors and actions to be performed on selected nodes. In the example below, the selector is "Image", which selects all image nodes. The action is to prepend the contents of the image's caption by the string "Figure. ". @param block [Proc] the filter specification @return [JSON] a JSON string with the filtered pandoc AST @example Add 'Figure' to each image's caption input = IOString.new(File.read("my_report.md") output = IOString.new Paru::Filter.new(input, output).filter do with "Image" do |image| image.inner_markdown = "Figure. #{image.inner_markdown}" end end
[ "Create", "a", "filter", "using", "+", "block", "+", ".", "In", "the", "block", "you", "specify", "selectors", "and", "actions", "to", "be", "performed", "on", "selected", "nodes", ".", "In", "the", "example", "below", "the", "selector", "is", "Image", "which", "selects", "all", "image", "nodes", ".", "The", "action", "is", "to", "prepend", "the", "contents", "of", "the", "image", "s", "caption", "by", "the", "string", "Figure", ".", "." ]
bb54c38c020f8bcaf475cb5f9d51f5ef761d6d86
https://github.com/htdebeer/paru/blob/bb54c38c020f8bcaf475cb5f9d51f5ef761d6d86/lib/paru/filter.rb#L267-L296
19,938
htdebeer/paru
lib/paru/filter.rb
Paru.Filter.with
def with(selector) @selectors[selector] = Selector.new selector unless @selectors.has_key? selector yield @current_node if @selectors[selector].matches? @current_node, @filtered_nodes end
ruby
def with(selector) @selectors[selector] = Selector.new selector unless @selectors.has_key? selector yield @current_node if @selectors[selector].matches? @current_node, @filtered_nodes end
[ "def", "with", "(", "selector", ")", "@selectors", "[", "selector", "]", "=", "Selector", ".", "new", "selector", "unless", "@selectors", ".", "has_key?", "selector", "yield", "@current_node", "if", "@selectors", "[", "selector", "]", ".", "matches?", "@current_node", ",", "@filtered_nodes", "end" ]
Specify what nodes to filter with a +selector+. If the +current_node+ matches that selector, it is passed to the block to this +with+ method. @param selector [String] a selector string @yield [Node] the current node if it matches the selector
[ "Specify", "what", "nodes", "to", "filter", "with", "a", "+", "selector", "+", ".", "If", "the", "+", "current_node", "+", "matches", "that", "selector", "it", "is", "passed", "to", "the", "block", "to", "this", "+", "with", "+", "method", "." ]
bb54c38c020f8bcaf475cb5f9d51f5ef761d6d86
https://github.com/htdebeer/paru/blob/bb54c38c020f8bcaf475cb5f9d51f5ef761d6d86/lib/paru/filter.rb#L303-L306
19,939
htdebeer/paru
lib/paru/selector.rb
Paru.Selector.matches?
def matches? node, filtered_nodes node.type == @type and @classes.all? {|c| node.has_class? c } and @relations.all? {|r| r.matches? node, filtered_nodes} end
ruby
def matches? node, filtered_nodes node.type == @type and @classes.all? {|c| node.has_class? c } and @relations.all? {|r| r.matches? node, filtered_nodes} end
[ "def", "matches?", "node", ",", "filtered_nodes", "node", ".", "type", "==", "@type", "and", "@classes", ".", "all?", "{", "|", "c", "|", "node", ".", "has_class?", "c", "}", "and", "@relations", ".", "all?", "{", "|", "r", "|", "r", ".", "matches?", "node", ",", "filtered_nodes", "}", "end" ]
Create a new Selector based on the selector string @param selector [String] the selector string Does node get selected by this Selector in the context of the already filtered nodes? @param node [Node] the node to check against this Selector @param filtered_nodes [Array<Node>] the context of filtered nodes to take into account as well @return [Boolean] True if the node in the context of the filtered_nodes is selected by this Selector
[ "Create", "a", "new", "Selector", "based", "on", "the", "selector", "string" ]
bb54c38c020f8bcaf475cb5f9d51f5ef761d6d86
https://github.com/htdebeer/paru/blob/bb54c38c020f8bcaf475cb5f9d51f5ef761d6d86/lib/paru/selector.rb#L53-L57
19,940
riemann/riemann-ruby-client
lib/riemann/event.rb
Riemann.Event.[]
def [](k) if RESERVED_FIELDS.include? k.to_sym super else r = attributes.find {|a| a.key.to_s == k.to_s }.value end end
ruby
def [](k) if RESERVED_FIELDS.include? k.to_sym super else r = attributes.find {|a| a.key.to_s == k.to_s }.value end end
[ "def", "[]", "(", "k", ")", "if", "RESERVED_FIELDS", ".", "include?", "k", ".", "to_sym", "super", "else", "r", "=", "attributes", ".", "find", "{", "|", "a", "|", "a", ".", "key", ".", "to_s", "==", "k", ".", "to_s", "}", ".", "value", "end", "end" ]
Look up attributes
[ "Look", "up", "attributes" ]
8e3972086c220fd46e274c6b314795bcbf897b83
https://github.com/riemann/riemann-ruby-client/blob/8e3972086c220fd46e274c6b314795bcbf897b83/lib/riemann/event.rb#L210-L216
19,941
riemann/riemann-ruby-client
lib/riemann/auto_state.rb
Riemann.AutoState.once
def once(opts) o = @state.merge opts o[:time] = Time.now.to_i o[:tags] = ((o[:tags] | ["once"]) rescue ["once"]) @client << o end
ruby
def once(opts) o = @state.merge opts o[:time] = Time.now.to_i o[:tags] = ((o[:tags] | ["once"]) rescue ["once"]) @client << o end
[ "def", "once", "(", "opts", ")", "o", "=", "@state", ".", "merge", "opts", "o", "[", ":time", "]", "=", "Time", ".", "now", ".", "to_i", "o", "[", ":tags", "]", "=", "(", "(", "o", "[", ":tags", "]", "|", "[", "\"once\"", "]", ")", "rescue", "[", "\"once\"", "]", ")", "@client", "<<", "o", "end" ]
Issues an immediate update of the state with tag "once" set, but does not update the local state. Useful for transient errors. Opts are merged with the state.
[ "Issues", "an", "immediate", "update", "of", "the", "state", "with", "tag", "once", "set", "but", "does", "not", "update", "the", "local", "state", ".", "Useful", "for", "transient", "errors", ".", "Opts", "are", "merged", "with", "the", "state", "." ]
8e3972086c220fd46e274c6b314795bcbf897b83
https://github.com/riemann/riemann-ruby-client/blob/8e3972086c220fd46e274c6b314795bcbf897b83/lib/riemann/auto_state.rb#L95-L100
19,942
alphagov/slimmer
lib/slimmer/headers.rb
Slimmer.Headers.set_slimmer_headers
def set_slimmer_headers(hash) raise InvalidHeader if (hash.keys - SLIMMER_HEADER_MAPPING.keys).any? SLIMMER_HEADER_MAPPING.each do |hash_key, header_suffix| value = hash[hash_key] headers["#{HEADER_PREFIX}-#{header_suffix}"] = value.to_s if value end end
ruby
def set_slimmer_headers(hash) raise InvalidHeader if (hash.keys - SLIMMER_HEADER_MAPPING.keys).any? SLIMMER_HEADER_MAPPING.each do |hash_key, header_suffix| value = hash[hash_key] headers["#{HEADER_PREFIX}-#{header_suffix}"] = value.to_s if value end end
[ "def", "set_slimmer_headers", "(", "hash", ")", "raise", "InvalidHeader", "if", "(", "hash", ".", "keys", "-", "SLIMMER_HEADER_MAPPING", ".", "keys", ")", ".", "any?", "SLIMMER_HEADER_MAPPING", ".", "each", "do", "|", "hash_key", ",", "header_suffix", "|", "value", "=", "hash", "[", "hash_key", "]", "headers", "[", "\"#{HEADER_PREFIX}-#{header_suffix}\"", "]", "=", "value", ".", "to_s", "if", "value", "end", "end" ]
Set the "slimmer headers" to configure the page @param hash [Hash] the options @option hash [String] application_name @option hash [String] format @option hash [String] organisations @option hash [String] page_owner @option hash [String] remove_search @option hash [String] result_count @option hash [String] search_parameters @option hash [String] section @option hash [String] skip @option hash [String] template @option hash [String] world_locations
[ "Set", "the", "slimmer", "headers", "to", "configure", "the", "page" ]
934aa93e6301cf792495ee24ece603932f994872
https://github.com/alphagov/slimmer/blob/934aa93e6301cf792495ee24ece603932f994872/lib/slimmer/headers.rb#L72-L78
19,943
nixme/pry-debugger
lib/pry-debugger/breakpoints.rb
PryDebugger.Breakpoints.add
def add(file, line, expression = nil) real_file = (file != Pry.eval_path) raise ArgumentError, 'Invalid file!' if real_file && !File.exist?(file) validate_expression expression Pry.processor.debugging = true path = (real_file ? File.expand_path(file) : file) Debugger.add_breakpoint(path, line, expression) end
ruby
def add(file, line, expression = nil) real_file = (file != Pry.eval_path) raise ArgumentError, 'Invalid file!' if real_file && !File.exist?(file) validate_expression expression Pry.processor.debugging = true path = (real_file ? File.expand_path(file) : file) Debugger.add_breakpoint(path, line, expression) end
[ "def", "add", "(", "file", ",", "line", ",", "expression", "=", "nil", ")", "real_file", "=", "(", "file", "!=", "Pry", ".", "eval_path", ")", "raise", "ArgumentError", ",", "'Invalid file!'", "if", "real_file", "&&", "!", "File", ".", "exist?", "(", "file", ")", "validate_expression", "expression", "Pry", ".", "processor", ".", "debugging", "=", "true", "path", "=", "(", "real_file", "?", "File", ".", "expand_path", "(", "file", ")", ":", "file", ")", "Debugger", ".", "add_breakpoint", "(", "path", ",", "line", ",", "expression", ")", "end" ]
Add a new breakpoint.
[ "Add", "a", "new", "breakpoint", "." ]
fab9c7bfc535b917a5b304cd04323a9ac8d826e7
https://github.com/nixme/pry-debugger/blob/fab9c7bfc535b917a5b304cd04323a9ac8d826e7/lib/pry-debugger/breakpoints.rb#L12-L21
19,944
nixme/pry-debugger
lib/pry-debugger/breakpoints.rb
PryDebugger.Breakpoints.change
def change(id, expression = nil) validate_expression expression breakpoint = find_by_id(id) breakpoint.expr = expression breakpoint end
ruby
def change(id, expression = nil) validate_expression expression breakpoint = find_by_id(id) breakpoint.expr = expression breakpoint end
[ "def", "change", "(", "id", ",", "expression", "=", "nil", ")", "validate_expression", "expression", "breakpoint", "=", "find_by_id", "(", "id", ")", "breakpoint", ".", "expr", "=", "expression", "breakpoint", "end" ]
Change the conditional expression for a breakpoint.
[ "Change", "the", "conditional", "expression", "for", "a", "breakpoint", "." ]
fab9c7bfc535b917a5b304cd04323a9ac8d826e7
https://github.com/nixme/pry-debugger/blob/fab9c7bfc535b917a5b304cd04323a9ac8d826e7/lib/pry-debugger/breakpoints.rb#L24-L30
19,945
nixme/pry-debugger
lib/pry-debugger/breakpoints.rb
PryDebugger.Breakpoints.delete
def delete(id) unless Debugger.started? && Debugger.remove_breakpoint(id) raise ArgumentError, "No breakpoint ##{id}" end Pry.processor.debugging = false if to_a.empty? end
ruby
def delete(id) unless Debugger.started? && Debugger.remove_breakpoint(id) raise ArgumentError, "No breakpoint ##{id}" end Pry.processor.debugging = false if to_a.empty? end
[ "def", "delete", "(", "id", ")", "unless", "Debugger", ".", "started?", "&&", "Debugger", ".", "remove_breakpoint", "(", "id", ")", "raise", "ArgumentError", ",", "\"No breakpoint ##{id}\"", "end", "Pry", ".", "processor", ".", "debugging", "=", "false", "if", "to_a", ".", "empty?", "end" ]
Delete an existing breakpoint with the given ID.
[ "Delete", "an", "existing", "breakpoint", "with", "the", "given", "ID", "." ]
fab9c7bfc535b917a5b304cd04323a9ac8d826e7
https://github.com/nixme/pry-debugger/blob/fab9c7bfc535b917a5b304cd04323a9ac8d826e7/lib/pry-debugger/breakpoints.rb#L33-L38
19,946
nixme/pry-debugger
lib/pry-debugger/breakpoints.rb
PryDebugger.Breakpoints.clear
def clear Debugger.breakpoints.clear if Debugger.started? Pry.processor.debugging = false end
ruby
def clear Debugger.breakpoints.clear if Debugger.started? Pry.processor.debugging = false end
[ "def", "clear", "Debugger", ".", "breakpoints", ".", "clear", "if", "Debugger", ".", "started?", "Pry", ".", "processor", ".", "debugging", "=", "false", "end" ]
Delete all breakpoints.
[ "Delete", "all", "breakpoints", "." ]
fab9c7bfc535b917a5b304cd04323a9ac8d826e7
https://github.com/nixme/pry-debugger/blob/fab9c7bfc535b917a5b304cd04323a9ac8d826e7/lib/pry-debugger/breakpoints.rb#L41-L44
19,947
nixme/pry-debugger
lib/pry-debugger/processor.rb
PryDebugger.Processor.stop
def stop Debugger.stop if !@always_enabled && Debugger.started? if PryDebugger.current_remote_server # Cleanup DRb remote if running PryDebugger.current_remote_server.teardown end end
ruby
def stop Debugger.stop if !@always_enabled && Debugger.started? if PryDebugger.current_remote_server # Cleanup DRb remote if running PryDebugger.current_remote_server.teardown end end
[ "def", "stop", "Debugger", ".", "stop", "if", "!", "@always_enabled", "&&", "Debugger", ".", "started?", "if", "PryDebugger", ".", "current_remote_server", "# Cleanup DRb remote if running", "PryDebugger", ".", "current_remote_server", ".", "teardown", "end", "end" ]
Cleanup when debugging is stopped and execution continues.
[ "Cleanup", "when", "debugging", "is", "stopped", "and", "execution", "continues", "." ]
fab9c7bfc535b917a5b304cd04323a9ac8d826e7
https://github.com/nixme/pry-debugger/blob/fab9c7bfc535b917a5b304cd04323a9ac8d826e7/lib/pry-debugger/processor.rb#L142-L147
19,948
Sage/fudge
lib/fudge/task_dsl.rb
Fudge.TaskDSL.task
def task(name, *args) klass = Fudge::Tasks.discover(name) task = klass.new(*args) current_scope.tasks << task with_scope(task) { yield if block_given? } end
ruby
def task(name, *args) klass = Fudge::Tasks.discover(name) task = klass.new(*args) current_scope.tasks << task with_scope(task) { yield if block_given? } end
[ "def", "task", "(", "name", ",", "*", "args", ")", "klass", "=", "Fudge", "::", "Tasks", ".", "discover", "(", "name", ")", "task", "=", "klass", ".", "new", "(", "args", ")", "current_scope", ".", "tasks", "<<", "task", "with_scope", "(", "task", ")", "{", "yield", "if", "block_given?", "}", "end" ]
Adds a task to the current scope
[ "Adds", "a", "task", "to", "the", "current", "scope" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/task_dsl.rb#L15-L22
19,949
Sage/fudge
lib/fudge/task_dsl.rb
Fudge.TaskDSL.method_missing
def method_missing(meth, *args, &block) task meth, *args, &block rescue Fudge::Exceptions::TaskNotFound super end
ruby
def method_missing(meth, *args, &block) task meth, *args, &block rescue Fudge::Exceptions::TaskNotFound super end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "task", "meth", ",", "args", ",", "block", "rescue", "Fudge", "::", "Exceptions", "::", "TaskNotFound", "super", "end" ]
Delegate to the current object scope
[ "Delegate", "to", "the", "current", "object", "scope" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/task_dsl.rb#L25-L29
19,950
Sage/fudge
lib/fudge/file_finder.rb
Fudge.FileFinder.generate_command
def generate_command(name, tty_options) cmd = [] cmd << name cmd += tty_options cmd << "`#{find_filters.join(' | ')}`" cmd.join(' ') end
ruby
def generate_command(name, tty_options) cmd = [] cmd << name cmd += tty_options cmd << "`#{find_filters.join(' | ')}`" cmd.join(' ') end
[ "def", "generate_command", "(", "name", ",", "tty_options", ")", "cmd", "=", "[", "]", "cmd", "<<", "name", "cmd", "+=", "tty_options", "cmd", "<<", "\"`#{find_filters.join(' | ')}`\"", "cmd", ".", "join", "(", "' '", ")", "end" ]
Generates a command line with command and any tty_option
[ "Generates", "a", "command", "line", "with", "command", "and", "any", "tty_option" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/file_finder.rb#L11-L17
19,951
Sage/fudge
lib/fudge/cli.rb
Fudge.Cli.init
def init generator = Fudge::Generator.new(Dir.pwd) msg = generator.write_fudgefile shell.say msg end
ruby
def init generator = Fudge::Generator.new(Dir.pwd) msg = generator.write_fudgefile shell.say msg end
[ "def", "init", "generator", "=", "Fudge", "::", "Generator", ".", "new", "(", "Dir", ".", "pwd", ")", "msg", "=", "generator", ".", "write_fudgefile", "shell", ".", "say", "msg", "end" ]
Initalizes the blank Fudgefile
[ "Initalizes", "the", "blank", "Fudgefile" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/cli.rb#L8-L12
19,952
Sage/fudge
lib/fudge/cli.rb
Fudge.Cli.build
def build(build_name='default') description = Fudge::Parser.new.parse('Fudgefile') Fudge::Runner.new(description).run_build(build_name, options) end
ruby
def build(build_name='default') description = Fudge::Parser.new.parse('Fudgefile') Fudge::Runner.new(description).run_build(build_name, options) end
[ "def", "build", "(", "build_name", "=", "'default'", ")", "description", "=", "Fudge", "::", "Parser", ".", "new", ".", "parse", "(", "'Fudgefile'", ")", "Fudge", "::", "Runner", ".", "new", "(", "description", ")", ".", "run_build", "(", "build_name", ",", "options", ")", "end" ]
Runs the parsed builds @param [String] build_name the given build to run (default 'default')
[ "Runs", "the", "parsed", "builds" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/cli.rb#L20-L23
19,953
Sage/fudge
lib/fudge/description.rb
Fudge.Description.build
def build(name, options={}) @builds[name] = build = Build.new(options) with_scope(build) { yield } end
ruby
def build(name, options={}) @builds[name] = build = Build.new(options) with_scope(build) { yield } end
[ "def", "build", "(", "name", ",", "options", "=", "{", "}", ")", "@builds", "[", "name", "]", "=", "build", "=", "Build", ".", "new", "(", "options", ")", "with_scope", "(", "build", ")", "{", "yield", "}", "end" ]
Sets builds to an initial empty array Adds a build to the current description
[ "Sets", "builds", "to", "an", "initial", "empty", "array", "Adds", "a", "build", "to", "the", "current", "description" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/description.rb#L18-L21
19,954
Sage/fudge
lib/fudge/description.rb
Fudge.Description.task_group
def task_group(name, *args, &block) if block @task_groups[name] = block else find_task_group(name).call(*args) end end
ruby
def task_group(name, *args, &block) if block @task_groups[name] = block else find_task_group(name).call(*args) end end
[ "def", "task_group", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "block", "@task_groups", "[", "name", "]", "=", "block", "else", "find_task_group", "(", "name", ")", ".", "call", "(", "args", ")", "end", "end" ]
Adds a task group to the current description or includes a task group
[ "Adds", "a", "task", "group", "to", "the", "current", "description", "or", "includes", "a", "task", "group" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/description.rb#L24-L30
19,955
Sage/fudge
lib/fudge/description.rb
Fudge.Description.find_task_group
def find_task_group(name) @task_groups[name].tap do |block| raise Exceptions::TaskGroupNotFound.new(name) unless block end end
ruby
def find_task_group(name) @task_groups[name].tap do |block| raise Exceptions::TaskGroupNotFound.new(name) unless block end end
[ "def", "find_task_group", "(", "name", ")", "@task_groups", "[", "name", "]", ".", "tap", "do", "|", "block", "|", "raise", "Exceptions", "::", "TaskGroupNotFound", ".", "new", "(", "name", ")", "unless", "block", "end", "end" ]
Gets a task group of the given name
[ "Gets", "a", "task", "group", "of", "the", "given", "name" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/description.rb#L33-L37
19,956
Sage/fudge
lib/fudge/runner.rb
Fudge.Runner.run_build
def run_build(which_build='default', options={}) formatter = options[:formatter] || Fudge::Formatters::Simple.new output_start(which_build, formatter) status = run(which_build, options) output_status(status, formatter) end
ruby
def run_build(which_build='default', options={}) formatter = options[:formatter] || Fudge::Formatters::Simple.new output_start(which_build, formatter) status = run(which_build, options) output_status(status, formatter) end
[ "def", "run_build", "(", "which_build", "=", "'default'", ",", "options", "=", "{", "}", ")", "formatter", "=", "options", "[", ":formatter", "]", "||", "Fudge", "::", "Formatters", "::", "Simple", ".", "new", "output_start", "(", "which_build", ",", "formatter", ")", "status", "=", "run", "(", "which_build", ",", "options", ")", "output_status", "(", "status", ",", "formatter", ")", "end" ]
Run the specified build @param [String] which_build Defaults to 'default'
[ "Run", "the", "specified", "build" ]
2a22b68f5ea96409b61949a503c6ee0b6d683920
https://github.com/Sage/fudge/blob/2a22b68f5ea96409b61949a503c6ee0b6d683920/lib/fudge/runner.rb#L11-L16
19,957
honeycombio/libhoney-rb
lib/libhoney/event.rb
Libhoney.Event.with_timer
def with_timer(name) start = Time.now yield duration = Time.now - start # report in ms add_field(name, duration * 1000) self end
ruby
def with_timer(name) start = Time.now yield duration = Time.now - start # report in ms add_field(name, duration * 1000) self end
[ "def", "with_timer", "(", "name", ")", "start", "=", "Time", ".", "now", "yield", "duration", "=", "Time", ".", "now", "-", "start", "# report in ms", "add_field", "(", "name", ",", "duration", "*", "1000", ")", "self", "end" ]
times the execution of a block and adds a field containing the duration in milliseconds @param name [String] the name of the field to add to the event @return [self] this event. @example event.with_timer "task_ms" do # something time consuming end
[ "times", "the", "execution", "of", "a", "block", "and", "adds", "a", "field", "containing", "the", "duration", "in", "milliseconds" ]
6ef2e402d11bf5cc0e08e5e72eb669bd81e04b67
https://github.com/honeycombio/libhoney-rb/blob/6ef2e402d11bf5cc0e08e5e72eb669bd81e04b67/lib/libhoney/event.rb#L98-L105
19,958
getyoti/yoti-ruby-sdk
lib/yoti/configuration.rb
Yoti.Configuration.validate_required_all
def validate_required_all(required_configs) required_configs.each do |config| unless config_set?(config) message = "Configuration value `#{config}` is required." raise ConfigurationError, message end end end
ruby
def validate_required_all(required_configs) required_configs.each do |config| unless config_set?(config) message = "Configuration value `#{config}` is required." raise ConfigurationError, message end end end
[ "def", "validate_required_all", "(", "required_configs", ")", "required_configs", ".", "each", "do", "|", "config", "|", "unless", "config_set?", "(", "config", ")", "message", "=", "\"Configuration value `#{config}` is required.\"", "raise", "ConfigurationError", ",", "message", "end", "end", "end" ]
Loops through the list of required configurations and raises an error if a it can't find all the configuration values set @return [nil]
[ "Loops", "through", "the", "list", "of", "required", "configurations", "and", "raises", "an", "error", "if", "a", "it", "can", "t", "find", "all", "the", "configuration", "values", "set" ]
d99abefc626828282b4a44dd44a7a10ce41bb24a
https://github.com/getyoti/yoti-ruby-sdk/blob/d99abefc626828282b4a44dd44a7a10ce41bb24a/lib/yoti/configuration.rb#L35-L42
19,959
getyoti/yoti-ruby-sdk
lib/yoti/configuration.rb
Yoti.Configuration.validate_required_any
def validate_required_any(required_configs) valid = required_configs.select { |config| config_set?(config) } return if valid.any? config_list = required_configs.map { |conf| '`' + conf + '`' }.join(', ') message = "At least one of the configuration values has to be set: #{config_list}." raise ConfigurationError, message end
ruby
def validate_required_any(required_configs) valid = required_configs.select { |config| config_set?(config) } return if valid.any? config_list = required_configs.map { |conf| '`' + conf + '`' }.join(', ') message = "At least one of the configuration values has to be set: #{config_list}." raise ConfigurationError, message end
[ "def", "validate_required_any", "(", "required_configs", ")", "valid", "=", "required_configs", ".", "select", "{", "|", "config", "|", "config_set?", "(", "config", ")", "}", "return", "if", "valid", ".", "any?", "config_list", "=", "required_configs", ".", "map", "{", "|", "conf", "|", "'`'", "+", "conf", "+", "'`'", "}", ".", "join", "(", "', '", ")", "message", "=", "\"At least one of the configuration values has to be set: #{config_list}.\"", "raise", "ConfigurationError", ",", "message", "end" ]
Loops through the list of required configurations and raises an error if a it can't find at least one configuration value set @return [nil]
[ "Loops", "through", "the", "list", "of", "required", "configurations", "and", "raises", "an", "error", "if", "a", "it", "can", "t", "find", "at", "least", "one", "configuration", "value", "set" ]
d99abefc626828282b4a44dd44a7a10ce41bb24a
https://github.com/getyoti/yoti-ruby-sdk/blob/d99abefc626828282b4a44dd44a7a10ce41bb24a/lib/yoti/configuration.rb#L47-L55
19,960
getyoti/yoti-ruby-sdk
lib/yoti/configuration.rb
Yoti.Configuration.validate_value
def validate_value(config, allowed_values) value = instance_variable_get("@#{config}") return unless invalid_value?(value, allowed_values) message = "Configuration value `#{value}` is not allowed for `#{config}`." raise ConfigurationError, message end
ruby
def validate_value(config, allowed_values) value = instance_variable_get("@#{config}") return unless invalid_value?(value, allowed_values) message = "Configuration value `#{value}` is not allowed for `#{config}`." raise ConfigurationError, message end
[ "def", "validate_value", "(", "config", ",", "allowed_values", ")", "value", "=", "instance_variable_get", "(", "\"@#{config}\"", ")", "return", "unless", "invalid_value?", "(", "value", ",", "allowed_values", ")", "message", "=", "\"Configuration value `#{value}` is not allowed for `#{config}`.\"", "raise", "ConfigurationError", ",", "message", "end" ]
Raises an error if the setting receives an invalid value @param config [String] the value to be assigned @param allowed_values [Array] an array of allowed values for the variable @return [nil]
[ "Raises", "an", "error", "if", "the", "setting", "receives", "an", "invalid", "value" ]
d99abefc626828282b4a44dd44a7a10ce41bb24a
https://github.com/getyoti/yoti-ruby-sdk/blob/d99abefc626828282b4a44dd44a7a10ce41bb24a/lib/yoti/configuration.rb#L61-L68
19,961
honeycombio/libhoney-rb
lib/libhoney/log_transmission.rb
Libhoney.LogTransmissionClient.add
def add(event) if @verbose metadata = "Honeycomb dataset '#{event.dataset}' | #{event.timestamp.iso8601}" metadata << " (sample rate: #{event.sample_rate})" if event.sample_rate != 1 @output.print("#{metadata} | ") end @output.puts(event.data.to_json) end
ruby
def add(event) if @verbose metadata = "Honeycomb dataset '#{event.dataset}' | #{event.timestamp.iso8601}" metadata << " (sample rate: #{event.sample_rate})" if event.sample_rate != 1 @output.print("#{metadata} | ") end @output.puts(event.data.to_json) end
[ "def", "add", "(", "event", ")", "if", "@verbose", "metadata", "=", "\"Honeycomb dataset '#{event.dataset}' | #{event.timestamp.iso8601}\"", "metadata", "<<", "\" (sample rate: #{event.sample_rate})\"", "if", "event", ".", "sample_rate", "!=", "1", "@output", ".", "print", "(", "\"#{metadata} | \"", ")", "end", "@output", ".", "puts", "(", "event", ".", "data", ".", "to_json", ")", "end" ]
Prints an event
[ "Prints", "an", "event" ]
6ef2e402d11bf5cc0e08e5e72eb669bd81e04b67
https://github.com/honeycombio/libhoney-rb/blob/6ef2e402d11bf5cc0e08e5e72eb669bd81e04b67/lib/libhoney/log_transmission.rb#L18-L25
19,962
honeycombio/libhoney-rb
lib/libhoney/client.rb
Libhoney.Client.send_event
def send_event(event) @lock.synchronize do transmission_client_params = { max_batch_size: @max_batch_size, send_frequency: @send_frequency, max_concurrent_batches: @max_concurrent_batches, pending_work_capacity: @pending_work_capacity, responses: @responses, block_on_send: @block_on_send, block_on_responses: @block_on_responses, user_agent_addition: @user_agent_addition } @transmission ||= TransmissionClient.new(transmission_client_params) end @transmission.add(event) end
ruby
def send_event(event) @lock.synchronize do transmission_client_params = { max_batch_size: @max_batch_size, send_frequency: @send_frequency, max_concurrent_batches: @max_concurrent_batches, pending_work_capacity: @pending_work_capacity, responses: @responses, block_on_send: @block_on_send, block_on_responses: @block_on_responses, user_agent_addition: @user_agent_addition } @transmission ||= TransmissionClient.new(transmission_client_params) end @transmission.add(event) end
[ "def", "send_event", "(", "event", ")", "@lock", ".", "synchronize", "do", "transmission_client_params", "=", "{", "max_batch_size", ":", "@max_batch_size", ",", "send_frequency", ":", "@send_frequency", ",", "max_concurrent_batches", ":", "@max_concurrent_batches", ",", "pending_work_capacity", ":", "@pending_work_capacity", ",", "responses", ":", "@responses", ",", "block_on_send", ":", "@block_on_send", ",", "block_on_responses", ":", "@block_on_responses", ",", "user_agent_addition", ":", "@user_agent_addition", "}", "@transmission", "||=", "TransmissionClient", ".", "new", "(", "transmission_client_params", ")", "end", "@transmission", ".", "add", "(", "event", ")", "end" ]
Enqueue an event to send. Sampling happens here, and we will create new threads to handle work as long as we haven't gone over max_concurrent_batches and there are still events in the queue. @param event [Event] the event to send to honeycomb @api private
[ "Enqueue", "an", "event", "to", "send", ".", "Sampling", "happens", "here", "and", "we", "will", "create", "new", "threads", "to", "handle", "work", "as", "long", "as", "we", "haven", "t", "gone", "over", "max_concurrent_batches", "and", "there", "are", "still", "events", "in", "the", "queue", "." ]
6ef2e402d11bf5cc0e08e5e72eb669bd81e04b67
https://github.com/honeycombio/libhoney-rb/blob/6ef2e402d11bf5cc0e08e5e72eb669bd81e04b67/lib/libhoney/client.rb#L214-L231
19,963
getyoti/yoti-ruby-sdk
lib/yoti/http/request.rb
Yoti.Request.body
def body raise RequestError, 'The request requires a HTTP method.' unless @http_method raise RequestError, 'The payload needs to be a hash.' unless @payload.to_s.empty? || @payload.is_a?(Hash) res = Net::HTTP.start(uri.hostname, Yoti.configuration.api_port, use_ssl: https_uri?) do |http| signed_request = SignedRequest.new(unsigned_request, path, @payload).sign http.request(signed_request) end raise RequestError, "Unsuccessful Yoti API call: #{res.message}" unless res.code == '200' res.body end
ruby
def body raise RequestError, 'The request requires a HTTP method.' unless @http_method raise RequestError, 'The payload needs to be a hash.' unless @payload.to_s.empty? || @payload.is_a?(Hash) res = Net::HTTP.start(uri.hostname, Yoti.configuration.api_port, use_ssl: https_uri?) do |http| signed_request = SignedRequest.new(unsigned_request, path, @payload).sign http.request(signed_request) end raise RequestError, "Unsuccessful Yoti API call: #{res.message}" unless res.code == '200' res.body end
[ "def", "body", "raise", "RequestError", ",", "'The request requires a HTTP method.'", "unless", "@http_method", "raise", "RequestError", ",", "'The payload needs to be a hash.'", "unless", "@payload", ".", "to_s", ".", "empty?", "||", "@payload", ".", "is_a?", "(", "Hash", ")", "res", "=", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "hostname", ",", "Yoti", ".", "configuration", ".", "api_port", ",", "use_ssl", ":", "https_uri?", ")", "do", "|", "http", "|", "signed_request", "=", "SignedRequest", ".", "new", "(", "unsigned_request", ",", "path", ",", "@payload", ")", ".", "sign", "http", ".", "request", "(", "signed_request", ")", "end", "raise", "RequestError", ",", "\"Unsuccessful Yoti API call: #{res.message}\"", "unless", "res", ".", "code", "==", "'200'", "res", ".", "body", "end" ]
Makes a HTTP request after signing the headers @return [Hash] the body from the HTTP request
[ "Makes", "a", "HTTP", "request", "after", "signing", "the", "headers" ]
d99abefc626828282b4a44dd44a7a10ce41bb24a
https://github.com/getyoti/yoti-ruby-sdk/blob/d99abefc626828282b4a44dd44a7a10ce41bb24a/lib/yoti/http/request.rb#L19-L31
19,964
BookingSync/bookingsync-api
lib/bookingsync/api/response.rb
BookingSync::API.Response.process_data
def process_data(hash) Array(hash).map do |hash| Resource.new(client, hash, resource_relations, resources_key) end end
ruby
def process_data(hash) Array(hash).map do |hash| Resource.new(client, hash, resource_relations, resources_key) end end
[ "def", "process_data", "(", "hash", ")", "Array", "(", "hash", ")", ".", "map", "do", "|", "hash", "|", "Resource", ".", "new", "(", "client", ",", "hash", ",", "resource_relations", ",", "resources_key", ")", "end", "end" ]
Build a Response after a completed request. @param client [BookingSync::API::Client] The client that is managing the API connection. @param res [Faraday::Response] Faraday response object Turn parsed contents from an API response into a Resource or collection of Resources. @param hash [Hash] A Hash of resources parsed from JSON. @return [Array] An Array of Resources.
[ "Build", "a", "Response", "after", "a", "completed", "request", "." ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/response.rb#L24-L28
19,965
BookingSync/bookingsync-api
lib/bookingsync/api/client.rb
BookingSync::API.Client.request
def request(method, path, data = nil, options = nil) instrument("request.bookingsync_api", method: method, path: path) do response = call(method, path, data, options) response.respond_to?(:resources) ? response.resources : response end end
ruby
def request(method, path, data = nil, options = nil) instrument("request.bookingsync_api", method: method, path: path) do response = call(method, path, data, options) response.respond_to?(:resources) ? response.resources : response end end
[ "def", "request", "(", "method", ",", "path", ",", "data", "=", "nil", ",", "options", "=", "nil", ")", "instrument", "(", "\"request.bookingsync_api\"", ",", "method", ":", "method", ",", "path", ":", "path", ")", "do", "response", "=", "call", "(", "method", ",", "path", ",", "data", ",", "options", ")", "response", ".", "respond_to?", "(", ":resources", ")", "?", "response", ".", "resources", ":", "response", "end", "end" ]
Make a HTTP request to a path and returns an Array of Resources @param method [Symbol] HTTP verb to use. @param path [String] The path, relative to {#api_endpoint}. @param data [Hash] Data to be send in the request's body it can include query: key with requests params for GET requests @param options [Hash] A customizable set of request options. @return [Array<BookingSync::API::Resource>] Array of resources.
[ "Make", "a", "HTTP", "request", "to", "a", "path", "and", "returns", "an", "Array", "of", "Resources" ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/client.rb#L212-L217
19,966
BookingSync/bookingsync-api
lib/bookingsync/api/client.rb
BookingSync::API.Client.paginate
def paginate(path, options = {}, &block) instrument("paginate.bookingsync_api", path: path) do request_settings = { auto_paginate: options.delete(:auto_paginate), request_method: options.delete(:request_method) || :get } if block_given? data = fetch_with_block(path, options, request_settings, &block) else data = fetch_with_paginate(path, options, request_settings) end data end end
ruby
def paginate(path, options = {}, &block) instrument("paginate.bookingsync_api", path: path) do request_settings = { auto_paginate: options.delete(:auto_paginate), request_method: options.delete(:request_method) || :get } if block_given? data = fetch_with_block(path, options, request_settings, &block) else data = fetch_with_paginate(path, options, request_settings) end data end end
[ "def", "paginate", "(", "path", ",", "options", "=", "{", "}", ",", "&", "block", ")", "instrument", "(", "\"paginate.bookingsync_api\"", ",", "path", ":", "path", ")", "do", "request_settings", "=", "{", "auto_paginate", ":", "options", ".", "delete", "(", ":auto_paginate", ")", ",", "request_method", ":", "options", ".", "delete", "(", ":request_method", ")", "||", ":get", "}", "if", "block_given?", "data", "=", "fetch_with_block", "(", "path", ",", "options", ",", "request_settings", ",", "block", ")", "else", "data", "=", "fetch_with_paginate", "(", "path", ",", "options", ",", "request_settings", ")", "end", "data", "end", "end" ]
Make a HTTP GET or POST request to a path with pagination support. @param options [Hash] @option options [Integer] per_page: Number of resources per page @option options [Integer] page: Number of page to return @option options [Boolean] auto_paginate: If true, all resources will be returned. It makes multiple requestes underneath and joins the results. @yieldreturn [Array<BookingSync::API::Resource>] Batch of resources @return [Array<BookingSync::API::Resource>] Batch of resources
[ "Make", "a", "HTTP", "GET", "or", "POST", "request", "to", "a", "path", "with", "pagination", "support", "." ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/client.rb#L229-L244
19,967
BookingSync/bookingsync-api
lib/bookingsync/api/client.rb
BookingSync::API.Client.call
def call(method, path, data = nil, options = nil) instrument("call.bookingsync_api", method: method, path: path) do if [:get, :head].include?(method) options = data data = {} end options ||= {} options[:headers] ||= {} options[:headers]["Authorization"] = "Bearer #{token}" if options.has_key?(:query) if options[:query].has_key?(:ids) ids = Array(options[:query].delete(:ids)).join(",") path = "#{path}/#{ids}" end options[:query].keys.each do |key| if options[:query][key].is_a?(Array) options[:query][key] = options[:query][key].join(",") end end end url = expand_url(path, options[:uri]) res = @conn.send(method, url) do |req| if data req.body = data.is_a?(String) ? data : encode_body(data) end if params = options[:query] req.params.update params end req.headers.update options[:headers] end handle_response(res) end end
ruby
def call(method, path, data = nil, options = nil) instrument("call.bookingsync_api", method: method, path: path) do if [:get, :head].include?(method) options = data data = {} end options ||= {} options[:headers] ||= {} options[:headers]["Authorization"] = "Bearer #{token}" if options.has_key?(:query) if options[:query].has_key?(:ids) ids = Array(options[:query].delete(:ids)).join(",") path = "#{path}/#{ids}" end options[:query].keys.each do |key| if options[:query][key].is_a?(Array) options[:query][key] = options[:query][key].join(",") end end end url = expand_url(path, options[:uri]) res = @conn.send(method, url) do |req| if data req.body = data.is_a?(String) ? data : encode_body(data) end if params = options[:query] req.params.update params end req.headers.update options[:headers] end handle_response(res) end end
[ "def", "call", "(", "method", ",", "path", ",", "data", "=", "nil", ",", "options", "=", "nil", ")", "instrument", "(", "\"call.bookingsync_api\"", ",", "method", ":", "method", ",", "path", ":", "path", ")", "do", "if", "[", ":get", ",", ":head", "]", ".", "include?", "(", "method", ")", "options", "=", "data", "data", "=", "{", "}", "end", "options", "||=", "{", "}", "options", "[", ":headers", "]", "||=", "{", "}", "options", "[", ":headers", "]", "[", "\"Authorization\"", "]", "=", "\"Bearer #{token}\"", "if", "options", ".", "has_key?", "(", ":query", ")", "if", "options", "[", ":query", "]", ".", "has_key?", "(", ":ids", ")", "ids", "=", "Array", "(", "options", "[", ":query", "]", ".", "delete", "(", ":ids", ")", ")", ".", "join", "(", "\",\"", ")", "path", "=", "\"#{path}/#{ids}\"", "end", "options", "[", ":query", "]", ".", "keys", ".", "each", "do", "|", "key", "|", "if", "options", "[", ":query", "]", "[", "key", "]", ".", "is_a?", "(", "Array", ")", "options", "[", ":query", "]", "[", "key", "]", "=", "options", "[", ":query", "]", "[", "key", "]", ".", "join", "(", "\",\"", ")", "end", "end", "end", "url", "=", "expand_url", "(", "path", ",", "options", "[", ":uri", "]", ")", "res", "=", "@conn", ".", "send", "(", "method", ",", "url", ")", "do", "|", "req", "|", "if", "data", "req", ".", "body", "=", "data", ".", "is_a?", "(", "String", ")", "?", "data", ":", "encode_body", "(", "data", ")", "end", "if", "params", "=", "options", "[", ":query", "]", "req", ".", "params", ".", "update", "params", "end", "req", ".", "headers", ".", "update", "options", "[", ":headers", "]", "end", "handle_response", "(", "res", ")", "end", "end" ]
Make a HTTP request to given path and returns Response object. @param method [Symbol] HTTP verb to use. @param path [String] The path, relative to {#api_endpoint}. @param data [Hash] Data to be send in the request's body it can include query: key with requests params for GET requests @param options [Hash] A customizable set of request options. @return [BookingSync::API::Response] A Response object.
[ "Make", "a", "HTTP", "request", "to", "given", "path", "and", "returns", "Response", "object", "." ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/client.rb#L254-L288
19,968
BookingSync/bookingsync-api
lib/bookingsync/api/client.rb
BookingSync::API.Client.with_headers
def with_headers(extra_headers = {}, &block) original_headers = @conn.headers.dup @conn.headers.merge!(extra_headers) result = yield self @conn.headers = original_headers result end
ruby
def with_headers(extra_headers = {}, &block) original_headers = @conn.headers.dup @conn.headers.merge!(extra_headers) result = yield self @conn.headers = original_headers result end
[ "def", "with_headers", "(", "extra_headers", "=", "{", "}", ",", "&", "block", ")", "original_headers", "=", "@conn", ".", "headers", ".", "dup", "@conn", ".", "headers", ".", "merge!", "(", "extra_headers", ")", "result", "=", "yield", "self", "@conn", ".", "headers", "=", "original_headers", "result", "end" ]
Yields client with temporarily modified headers. @param extra_headers [Hash] Additional headers added to next request. @yieldreturn [BookingSync::API::Client] Client with modified default headers. @return [Array<BookingSync::API::Resource>|BookingSync::API::Resource|String|Object] Client response
[ "Yields", "client", "with", "temporarily", "modified", "headers", "." ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/client.rb#L295-L301
19,969
BookingSync/bookingsync-api
lib/bookingsync/api/client.rb
BookingSync::API.Client.handle_response
def handle_response(faraday_response) @last_response = response = Response.new(self, faraday_response) case response.status when 204; nil # destroy/cancel when 200..299; response when 401; raise Unauthorized.new(response) when 403; raise Forbidden.new(response) when 404; raise NotFound.new(response) when 422; raise UnprocessableEntity.new(response) when 429; raise RateLimitExceeded.new(response) else raise UnsupportedResponse.new(response) end end
ruby
def handle_response(faraday_response) @last_response = response = Response.new(self, faraday_response) case response.status when 204; nil # destroy/cancel when 200..299; response when 401; raise Unauthorized.new(response) when 403; raise Forbidden.new(response) when 404; raise NotFound.new(response) when 422; raise UnprocessableEntity.new(response) when 429; raise RateLimitExceeded.new(response) else raise UnsupportedResponse.new(response) end end
[ "def", "handle_response", "(", "faraday_response", ")", "@last_response", "=", "response", "=", "Response", ".", "new", "(", "self", ",", "faraday_response", ")", "case", "response", ".", "status", "when", "204", ";", "nil", "# destroy/cancel", "when", "200", "..", "299", ";", "response", "when", "401", ";", "raise", "Unauthorized", ".", "new", "(", "response", ")", "when", "403", ";", "raise", "Forbidden", ".", "new", "(", "response", ")", "when", "404", ";", "raise", "NotFound", ".", "new", "(", "response", ")", "when", "422", ";", "raise", "UnprocessableEntity", ".", "new", "(", "response", ")", "when", "429", ";", "raise", "RateLimitExceeded", ".", "new", "(", "response", ")", "else", "raise", "UnsupportedResponse", ".", "new", "(", "response", ")", "end", "end" ]
Process faraday response. @param faraday_response [Faraday::Response] - A response to process @raise [BookingSync::API::Unauthorized] - On unauthorized user @raise [BookingSync::API::UnprocessableEntity] - On validations error @return [BookingSync::API::Response|NilClass]
[ "Process", "faraday", "response", "." ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/client.rb#L352-L364
19,970
BookingSync/bookingsync-api
lib/bookingsync/api/relation.rb
BookingSync::API.Relation.call
def call(data = {}, options = {}) m = options.delete(:method) client.call m || method, href_template, data, options end
ruby
def call(data = {}, options = {}) m = options.delete(:method) client.call m || method, href_template, data, options end
[ "def", "call", "(", "data", "=", "{", "}", ",", "options", "=", "{", "}", ")", "m", "=", "options", ".", "delete", "(", ":method", ")", "client", ".", "call", "m", "||", "method", ",", "href_template", ",", "data", ",", "options", "end" ]
Make an API request with the curent Relation. @param data [Hash|String] The Optional Hash or Resource body to be sent. :get or :head requests can have no body, so this can be the options Hash instead. @param options [Hash] A Hash of option to configure the API request. @option options [Hash] headers: A Hash of API headers to set. @option options [Hash] query: Hash of URL query params to set. @option options [Symbol] method: Symbol HTTP method. @return [BookingSync::API::Response]
[ "Make", "an", "API", "request", "with", "the", "curent", "Relation", "." ]
4f9ca7aec359f3b76bde5867321995b7307bd6bd
https://github.com/BookingSync/bookingsync-api/blob/4f9ca7aec359f3b76bde5867321995b7307bd6bd/lib/bookingsync/api/relation.rb#L85-L88
19,971
mavenlink/brainstem
lib/brainstem/controller_methods.rb
Brainstem.ControllerMethods.brainstem_present
def brainstem_present(name, options = {}, &block) Brainstem.presenter_collection(options[:namespace]).presenting(name, options.reverse_merge(:params => params), &block) end
ruby
def brainstem_present(name, options = {}, &block) Brainstem.presenter_collection(options[:namespace]).presenting(name, options.reverse_merge(:params => params), &block) end
[ "def", "brainstem_present", "(", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "Brainstem", ".", "presenter_collection", "(", "options", "[", ":namespace", "]", ")", ".", "presenting", "(", "name", ",", "options", ".", "reverse_merge", "(", ":params", "=>", "params", ")", ",", "block", ")", "end" ]
Return a Ruby hash that contains models requested by the user's params and allowed by the +name+ presenter's configuration. Pass the returned hash to the render method to convert it into a useful format. For example: render :json => brainstem_present("post"){ Post.where(:draft => false) } @param (see PresenterCollection#presenting) @option options [String] :namespace ("none") the namespace to be presented from @yield (see PresenterCollection#presenting) @return (see PresenterCollection#presenting)
[ "Return", "a", "Ruby", "hash", "that", "contains", "models", "requested", "by", "the", "user", "s", "params", "and", "allowed", "by", "the", "+", "name", "+", "presenter", "s", "configuration", "." ]
99558d02e911ff8836f485b0eccdb63f0460e1e2
https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/controller_methods.rb#L27-L29
19,972
mavenlink/brainstem
lib/brainstem/preloader.rb
Brainstem.Preloader.preload_method
def preload_method @preload_method ||= begin if Gem.loaded_specs['activerecord'].version >= Gem::Version.create('4.1') ActiveRecord::Associations::Preloader.new.method(:preload) else Proc.new do |models, association_names| ActiveRecord::Associations::Preloader.new(models, association_names).run end end end end
ruby
def preload_method @preload_method ||= begin if Gem.loaded_specs['activerecord'].version >= Gem::Version.create('4.1') ActiveRecord::Associations::Preloader.new.method(:preload) else Proc.new do |models, association_names| ActiveRecord::Associations::Preloader.new(models, association_names).run end end end end
[ "def", "preload_method", "@preload_method", "||=", "begin", "if", "Gem", ".", "loaded_specs", "[", "'activerecord'", "]", ".", "version", ">=", "Gem", "::", "Version", ".", "create", "(", "'4.1'", ")", "ActiveRecord", "::", "Associations", "::", "Preloader", ".", "new", ".", "method", "(", ":preload", ")", "else", "Proc", ".", "new", "do", "|", "models", ",", "association_names", "|", "ActiveRecord", "::", "Associations", "::", "Preloader", ".", "new", "(", "models", ",", "association_names", ")", ".", "run", "end", "end", "end", "end" ]
Returns a proc that takes two arguments, +models+ and +association_names+, which, when called, preloads those. @return [Proc] A callable proc
[ "Returns", "a", "proc", "that", "takes", "two", "arguments", "+", "models", "+", "and", "+", "association_names", "+", "which", "when", "called", "preloads", "those", "." ]
99558d02e911ff8836f485b0eccdb63f0460e1e2
https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/preloader.rb#L68-L78
19,973
mavenlink/brainstem
lib/brainstem/presenter.rb
Brainstem.Presenter.apply_ordering_to_scope
def apply_ordering_to_scope(scope, user_params) sort_name, direction = calculate_sort_name_and_direction(user_params) order = configuration[:sort_orders].fetch(sort_name, {})[:value] ordered_scope = case order when Proc fresh_helper_instance.instance_exec(scope, direction, &order) when nil scope else scope.reorder(order.to_s + " " + direction) end fallback_deterministic_sort = assemble_primary_key_sort(scope) # Chain on a tiebreaker sort to ensure deterministic ordering of multiple pages of data if fallback_deterministic_sort ordered_scope.order(fallback_deterministic_sort) else ordered_scope end end
ruby
def apply_ordering_to_scope(scope, user_params) sort_name, direction = calculate_sort_name_and_direction(user_params) order = configuration[:sort_orders].fetch(sort_name, {})[:value] ordered_scope = case order when Proc fresh_helper_instance.instance_exec(scope, direction, &order) when nil scope else scope.reorder(order.to_s + " " + direction) end fallback_deterministic_sort = assemble_primary_key_sort(scope) # Chain on a tiebreaker sort to ensure deterministic ordering of multiple pages of data if fallback_deterministic_sort ordered_scope.order(fallback_deterministic_sort) else ordered_scope end end
[ "def", "apply_ordering_to_scope", "(", "scope", ",", "user_params", ")", "sort_name", ",", "direction", "=", "calculate_sort_name_and_direction", "(", "user_params", ")", "order", "=", "configuration", "[", ":sort_orders", "]", ".", "fetch", "(", "sort_name", ",", "{", "}", ")", "[", ":value", "]", "ordered_scope", "=", "case", "order", "when", "Proc", "fresh_helper_instance", ".", "instance_exec", "(", "scope", ",", "direction", ",", "order", ")", "when", "nil", "scope", "else", "scope", ".", "reorder", "(", "order", ".", "to_s", "+", "\" \"", "+", "direction", ")", "end", "fallback_deterministic_sort", "=", "assemble_primary_key_sort", "(", "scope", ")", "# Chain on a tiebreaker sort to ensure deterministic ordering of multiple pages of data", "if", "fallback_deterministic_sort", "ordered_scope", ".", "order", "(", "fallback_deterministic_sort", ")", "else", "ordered_scope", "end", "end" ]
Given user params, apply a validated sort order to the given scope.
[ "Given", "user", "params", "apply", "a", "validated", "sort", "order", "to", "the", "given", "scope", "." ]
99558d02e911ff8836f485b0eccdb63f0460e1e2
https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/presenter.rb#L207-L228
19,974
mavenlink/brainstem
lib/brainstem/presenter.rb
Brainstem.Presenter.calculate_sort_name_and_direction
def calculate_sort_name_and_direction(user_params = {}) default_column, default_direction = (configuration[:default_sort_order] || "updated_at:desc").split(":") sort_name, direction = user_params['order'].to_s.split(":") unless sort_name.present? && configuration[:sort_orders][sort_name] sort_name = default_column direction = default_direction end [sort_name, direction == 'desc' ? 'desc' : 'asc'] end
ruby
def calculate_sort_name_and_direction(user_params = {}) default_column, default_direction = (configuration[:default_sort_order] || "updated_at:desc").split(":") sort_name, direction = user_params['order'].to_s.split(":") unless sort_name.present? && configuration[:sort_orders][sort_name] sort_name = default_column direction = default_direction end [sort_name, direction == 'desc' ? 'desc' : 'asc'] end
[ "def", "calculate_sort_name_and_direction", "(", "user_params", "=", "{", "}", ")", "default_column", ",", "default_direction", "=", "(", "configuration", "[", ":default_sort_order", "]", "||", "\"updated_at:desc\"", ")", ".", "split", "(", "\":\"", ")", "sort_name", ",", "direction", "=", "user_params", "[", "'order'", "]", ".", "to_s", ".", "split", "(", "\":\"", ")", "unless", "sort_name", ".", "present?", "&&", "configuration", "[", ":sort_orders", "]", "[", "sort_name", "]", "sort_name", "=", "default_column", "direction", "=", "default_direction", "end", "[", "sort_name", ",", "direction", "==", "'desc'", "?", "'desc'", ":", "'asc'", "]", "end" ]
Clean and validate a sort order and direction from user params.
[ "Clean", "and", "validate", "a", "sort", "order", "and", "direction", "from", "user", "params", "." ]
99558d02e911ff8836f485b0eccdb63f0460e1e2
https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/presenter.rb#L248-L257
19,975
mavenlink/brainstem
lib/brainstem/cli.rb
Brainstem.Cli.call
def call if requested_command && commands.has_key?(requested_command) self.command_method = commands[requested_command].method(:call) end command_method.call(_args.drop(1)) self end
ruby
def call if requested_command && commands.has_key?(requested_command) self.command_method = commands[requested_command].method(:call) end command_method.call(_args.drop(1)) self end
[ "def", "call", "if", "requested_command", "&&", "commands", ".", "has_key?", "(", "requested_command", ")", "self", ".", "command_method", "=", "commands", "[", "requested_command", "]", ".", "method", "(", ":call", ")", "end", "command_method", ".", "call", "(", "_args", ".", "drop", "(", "1", ")", ")", "self", "end" ]
Creates a new instance of the Cli to respond to user input. Input is expected to be the name of the subcommand, followed by any additional arguments. Routes to an application endpoint depending on given options. @return [Brainstem::Cli] the instance
[ "Creates", "a", "new", "instance", "of", "the", "Cli", "to", "respond", "to", "user", "input", "." ]
99558d02e911ff8836f485b0eccdb63f0460e1e2
https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/cli.rb#L41-L49
19,976
Openwsman/openwsman
bindings/ruby/openwsman/openwsman.rb
Openwsman.ClientOptions.properties=
def properties= value value.each do |k,v| self.add_property k.to_s, v end end
ruby
def properties= value value.each do |k,v| self.add_property k.to_s, v end end
[ "def", "properties", "=", "value", "value", ".", "each", "do", "|", "k", ",", "v", "|", "self", ".", "add_property", "k", ".", "to_s", ",", "v", "end", "end" ]
assign hash to properties
[ "assign", "hash", "to", "properties" ]
5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e
https://github.com/Openwsman/openwsman/blob/5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e/bindings/ruby/openwsman/openwsman.rb#L46-L50
19,977
Openwsman/openwsman
bindings/ruby/openwsman/openwsman.rb
Openwsman.ClientOptions.selectors=
def selectors= value value.each do |k,v| self.add_selector k.to_s, v end end
ruby
def selectors= value value.each do |k,v| self.add_selector k.to_s, v end end
[ "def", "selectors", "=", "value", "value", ".", "each", "do", "|", "k", ",", "v", "|", "self", ".", "add_selector", "k", ".", "to_s", ",", "v", "end", "end" ]
assign hash to selectors
[ "assign", "hash", "to", "selectors" ]
5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e
https://github.com/Openwsman/openwsman/blob/5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e/bindings/ruby/openwsman/openwsman.rb#L52-L56
19,978
Openwsman/openwsman
bindings/ruby/parse_swig.rb
RDoc.Swig_Parser.handle_class_module
def handle_class_module(class_mod, class_name, options = {}) # puts "handle_class_module(#{class_mod}, #{class_name})" progress(class_mod[0, 1]) parent = options[:parent] parent_name = @known_classes[parent] || parent if @@module_name enclosure = @top_level.find_module_named(@@module_name) else enclosure = @top_level end if class_mod == "class" cm = enclosure.add_class(NormalClass, class_name, parent_name) @stats.num_classes += 1 else cm = enclosure.add_module(NormalModule, class_name) @stats.num_modules += 1 end cm.record_location(enclosure.toplevel) cm.body = options[:content] cm.extend_name = options[:extend_name] || class_name find_class_comment(class_name, cm) @classes[class_name] = cm @known_classes[class_name] = cm.full_name cm end
ruby
def handle_class_module(class_mod, class_name, options = {}) # puts "handle_class_module(#{class_mod}, #{class_name})" progress(class_mod[0, 1]) parent = options[:parent] parent_name = @known_classes[parent] || parent if @@module_name enclosure = @top_level.find_module_named(@@module_name) else enclosure = @top_level end if class_mod == "class" cm = enclosure.add_class(NormalClass, class_name, parent_name) @stats.num_classes += 1 else cm = enclosure.add_module(NormalModule, class_name) @stats.num_modules += 1 end cm.record_location(enclosure.toplevel) cm.body = options[:content] cm.extend_name = options[:extend_name] || class_name find_class_comment(class_name, cm) @classes[class_name] = cm @known_classes[class_name] = cm.full_name cm end
[ "def", "handle_class_module", "(", "class_mod", ",", "class_name", ",", "options", "=", "{", "}", ")", "# puts \"handle_class_module(#{class_mod}, #{class_name})\"", "progress", "(", "class_mod", "[", "0", ",", "1", "]", ")", "parent", "=", "options", "[", ":parent", "]", "parent_name", "=", "@known_classes", "[", "parent", "]", "||", "parent", "if", "@@module_name", "enclosure", "=", "@top_level", ".", "find_module_named", "(", "@@module_name", ")", "else", "enclosure", "=", "@top_level", "end", "if", "class_mod", "==", "\"class\"", "cm", "=", "enclosure", ".", "add_class", "(", "NormalClass", ",", "class_name", ",", "parent_name", ")", "@stats", ".", "num_classes", "+=", "1", "else", "cm", "=", "enclosure", ".", "add_module", "(", "NormalModule", ",", "class_name", ")", "@stats", ".", "num_modules", "+=", "1", "end", "cm", ".", "record_location", "(", "enclosure", ".", "toplevel", ")", "cm", ".", "body", "=", "options", "[", ":content", "]", "cm", ".", "extend_name", "=", "options", "[", ":extend_name", "]", "||", "class_name", "find_class_comment", "(", "class_name", ",", "cm", ")", "@classes", "[", "class_name", "]", "=", "cm", "@known_classes", "[", "class_name", "]", "=", "cm", ".", "full_name", "cm", "end" ]
handle class or module return enclosure
[ "handle", "class", "or", "module" ]
5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e
https://github.com/Openwsman/openwsman/blob/5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e/bindings/ruby/parse_swig.rb#L152-L179
19,979
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/speech_recognizer.rb
Pocketsphinx.SpeechRecognizer.recognize
def recognize(max_samples = 2048, &b) unless ALGORITHMS.include?(algorithm) raise NotImplementedError, "Unknown speech recognition algorithm: #{algorithm}" end start unless recognizing? FFI::MemoryPointer.new(:int16, max_samples) do |buffer| loop do send("recognize_#{algorithm}", max_samples, buffer, &b) or break end end ensure stop end
ruby
def recognize(max_samples = 2048, &b) unless ALGORITHMS.include?(algorithm) raise NotImplementedError, "Unknown speech recognition algorithm: #{algorithm}" end start unless recognizing? FFI::MemoryPointer.new(:int16, max_samples) do |buffer| loop do send("recognize_#{algorithm}", max_samples, buffer, &b) or break end end ensure stop end
[ "def", "recognize", "(", "max_samples", "=", "2048", ",", "&", "b", ")", "unless", "ALGORITHMS", ".", "include?", "(", "algorithm", ")", "raise", "NotImplementedError", ",", "\"Unknown speech recognition algorithm: #{algorithm}\"", "end", "start", "unless", "recognizing?", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int16", ",", "max_samples", ")", "do", "|", "buffer", "|", "loop", "do", "send", "(", "\"recognize_#{algorithm}\"", ",", "max_samples", ",", "buffer", ",", "b", ")", "or", "break", "end", "end", "ensure", "stop", "end" ]
Recognize speech and yield hypotheses in infinite loop @param [Fixnum] max_samples Number of samples to process at a time
[ "Recognize", "speech", "and", "yield", "hypotheses", "in", "infinite", "loop" ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/speech_recognizer.rb#L46-L60
19,980
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/speech_recognizer.rb
Pocketsphinx.SpeechRecognizer.recognize_continuous
def recognize_continuous(max_samples, buffer) process_audio(buffer, max_samples).tap do if hypothesis = decoder.hypothesis decoder.end_utterance yield hypothesis decoder.start_utterance end end end
ruby
def recognize_continuous(max_samples, buffer) process_audio(buffer, max_samples).tap do if hypothesis = decoder.hypothesis decoder.end_utterance yield hypothesis decoder.start_utterance end end end
[ "def", "recognize_continuous", "(", "max_samples", ",", "buffer", ")", "process_audio", "(", "buffer", ",", "max_samples", ")", ".", "tap", "do", "if", "hypothesis", "=", "decoder", ".", "hypothesis", "decoder", ".", "end_utterance", "yield", "hypothesis", "decoder", ".", "start_utterance", "end", "end", "end" ]
Yields as soon as any hypothesis is available
[ "Yields", "as", "soon", "as", "any", "hypothesis", "is", "available" ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/speech_recognizer.rb#L108-L118
19,981
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/decoder.rb
Pocketsphinx.Decoder.decode
def decode(audio_path_or_file, max_samples = 2048) case audio_path_or_file when String File.open(audio_path_or_file, 'rb') { |f| decode_raw(f, max_samples) } else decode_raw(audio_path_or_file, max_samples) end end
ruby
def decode(audio_path_or_file, max_samples = 2048) case audio_path_or_file when String File.open(audio_path_or_file, 'rb') { |f| decode_raw(f, max_samples) } else decode_raw(audio_path_or_file, max_samples) end end
[ "def", "decode", "(", "audio_path_or_file", ",", "max_samples", "=", "2048", ")", "case", "audio_path_or_file", "when", "String", "File", ".", "open", "(", "audio_path_or_file", ",", "'rb'", ")", "{", "|", "f", "|", "decode_raw", "(", "f", ",", "max_samples", ")", "}", "else", "decode_raw", "(", "audio_path_or_file", ",", "max_samples", ")", "end", "end" ]
Decode a raw audio stream as a single utterance, opening a file if path given See #decode_raw @param [IO] audio_path_or_file The raw audio stream or file path to decode as a single utterance @param [Fixnum] max_samples The maximum samples to process from the stream on each iteration
[ "Decode", "a", "raw", "audio", "stream", "as", "a", "single", "utterance", "opening", "a", "file", "if", "path", "given" ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L54-L61
19,982
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/decoder.rb
Pocketsphinx.Decoder.decode_raw
def decode_raw(audio_file, max_samples = 2048) start_utterance FFI::MemoryPointer.new(:int16, max_samples) do |buffer| while data = audio_file.read(max_samples * 2) buffer.write_string(data) process_raw(buffer, data.length / 2) end end end_utterance end
ruby
def decode_raw(audio_file, max_samples = 2048) start_utterance FFI::MemoryPointer.new(:int16, max_samples) do |buffer| while data = audio_file.read(max_samples * 2) buffer.write_string(data) process_raw(buffer, data.length / 2) end end end_utterance end
[ "def", "decode_raw", "(", "audio_file", ",", "max_samples", "=", "2048", ")", "start_utterance", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int16", ",", "max_samples", ")", "do", "|", "buffer", "|", "while", "data", "=", "audio_file", ".", "read", "(", "max_samples", "*", "2", ")", "buffer", ".", "write_string", "(", "data", ")", "process_raw", "(", "buffer", ",", "data", ".", "length", "/", "2", ")", "end", "end", "end_utterance", "end" ]
Decode a raw audio stream as a single utterance. No headers are recognized in this files. The configuration parameters samprate and input_endian are used to determine the sampling rate and endianness of the stream, respectively. Audio is always assumed to be 16-bit signed PCM. @param [IO] audio_file The raw audio stream to decode as a single utterance @param [Fixnum] max_samples The maximum samples to process from the stream on each iteration
[ "Decode", "a", "raw", "audio", "stream", "as", "a", "single", "utterance", "." ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L71-L82
19,983
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/decoder.rb
Pocketsphinx.Decoder.process_raw
def process_raw(buffer, size, no_search = false, full_utt = false) api_call :ps_process_raw, ps_decoder, buffer, size, no_search ? 1 : 0, full_utt ? 1 : 0 end
ruby
def process_raw(buffer, size, no_search = false, full_utt = false) api_call :ps_process_raw, ps_decoder, buffer, size, no_search ? 1 : 0, full_utt ? 1 : 0 end
[ "def", "process_raw", "(", "buffer", ",", "size", ",", "no_search", "=", "false", ",", "full_utt", "=", "false", ")", "api_call", ":ps_process_raw", ",", "ps_decoder", ",", "buffer", ",", "size", ",", "no_search", "?", "1", ":", "0", ",", "full_utt", "?", "1", ":", "0", "end" ]
Decode raw audio data. @param [Boolean] no_search If non-zero, perform feature extraction but don't do any recognition yet. This may be necessary if your processor has trouble doing recognition in real-time. @param [Boolean] full_utt If non-zero, this block of data is a full utterance worth of data. This may allow the recognizer to produce more accurate results. @return Number of frames of data searched
[ "Decode", "raw", "audio", "data", "." ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L92-L94
19,984
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/decoder.rb
Pocketsphinx.Decoder.log_prob_to_linear
def log_prob_to_linear(log_prob) logmath = ps_api.ps_get_logmath(ps_decoder) ps_api.logmath_exp(logmath, log_prob) end
ruby
def log_prob_to_linear(log_prob) logmath = ps_api.ps_get_logmath(ps_decoder) ps_api.logmath_exp(logmath, log_prob) end
[ "def", "log_prob_to_linear", "(", "log_prob", ")", "logmath", "=", "ps_api", ".", "ps_get_logmath", "(", "ps_decoder", ")", "ps_api", ".", "logmath_exp", "(", "logmath", ",", "log_prob", ")", "end" ]
Convert logarithmic probability to linear floating point
[ "Convert", "logarithmic", "probability", "to", "linear", "floating", "point" ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L216-L219
19,985
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/microphone.rb
Pocketsphinx.Microphone.read_audio
def read_audio(buffer, max_samples = 2048) samples = ps_api.ad_read(@ps_audio_device, buffer, max_samples) samples if samples >= 0 end
ruby
def read_audio(buffer, max_samples = 2048) samples = ps_api.ad_read(@ps_audio_device, buffer, max_samples) samples if samples >= 0 end
[ "def", "read_audio", "(", "buffer", ",", "max_samples", "=", "2048", ")", "samples", "=", "ps_api", ".", "ad_read", "(", "@ps_audio_device", ",", "buffer", ",", "max_samples", ")", "samples", "if", "samples", ">=", "0", "end" ]
Read next block of audio samples while recording; read upto max samples into buf. @param [FFI::Pointer] buffer 16bit buffer of at least max_samples in size @params [Fixnum] max_samples The maximum number of samples to read from the audio device @return [Fixnum] Samples actually read (could be 0 since non-blocking); nil if not recording and no more samples remaining to be read from most recent recording.
[ "Read", "next", "block", "of", "audio", "samples", "while", "recording", ";", "read", "upto", "max", "samples", "into", "buf", "." ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/microphone.rb#L52-L55
19,986
watsonbox/pocketsphinx-ruby
lib/pocketsphinx/audio_file.rb
Pocketsphinx.AudioFile.read_audio
def read_audio(buffer, max_samples = 2048) if file.nil? raise "Can't read audio: use AudioFile#start_recording to open the file first" end if data = file.read(max_samples * 2) buffer.write_string(data) data.length / 2 end end
ruby
def read_audio(buffer, max_samples = 2048) if file.nil? raise "Can't read audio: use AudioFile#start_recording to open the file first" end if data = file.read(max_samples * 2) buffer.write_string(data) data.length / 2 end end
[ "def", "read_audio", "(", "buffer", ",", "max_samples", "=", "2048", ")", "if", "file", ".", "nil?", "raise", "\"Can't read audio: use AudioFile#start_recording to open the file first\"", "end", "if", "data", "=", "file", ".", "read", "(", "max_samples", "*", "2", ")", "buffer", ".", "write_string", "(", "data", ")", "data", ".", "length", "/", "2", "end", "end" ]
Read next block of audio samples from file; up to max samples into buffer. @param [FFI::Pointer] buffer 16bit buffer of at least max_samples in size @params [Fixnum] max_samples The maximum number of samples to read from the audio file @return [Fixnum] Samples actually read; nil if EOF
[ "Read", "next", "block", "of", "audio", "samples", "from", "file", ";", "up", "to", "max", "samples", "into", "buffer", "." ]
12c71c35285c38b42bd7779c8246923bd5be150f
https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/audio_file.rb#L9-L18
19,987
zk-ruby/zk
lib/zk/threadpool.rb
ZK.Threadpool.on_threadpool?
def on_threadpool? tp = nil @mutex.synchronize do return false unless @threadpool # you can't dup nil tp = @threadpool.dup end tp.respond_to?(:include?) and tp.include?(Thread.current) end
ruby
def on_threadpool? tp = nil @mutex.synchronize do return false unless @threadpool # you can't dup nil tp = @threadpool.dup end tp.respond_to?(:include?) and tp.include?(Thread.current) end
[ "def", "on_threadpool?", "tp", "=", "nil", "@mutex", ".", "synchronize", "do", "return", "false", "unless", "@threadpool", "# you can't dup nil", "tp", "=", "@threadpool", ".", "dup", "end", "tp", ".", "respond_to?", "(", ":include?", ")", "and", "tp", ".", "include?", "(", "Thread", ".", "current", ")", "end" ]
returns true if the current thread is one of the threadpool threads
[ "returns", "true", "if", "the", "current", "thread", "is", "one", "of", "the", "threadpool", "threads" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/threadpool.rb#L76-L85
19,988
zk-ruby/zk
lib/zk/event_handler.rb
ZK.EventHandler.process
def process(event, watch_type = nil) @zk.raw_event_handler(event) logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1 event.zk = @zk cb_keys = if event.node_event? [event.path, ALL_NODE_EVENTS_KEY] elsif event.session_event? [state_key(event.state), ALL_STATE_EVENTS_KEY] else raise ZKError, "don't know how to process event: #{event.inspect}" end cb_ary = synchronize do clear_watch_restrictions(event, watch_type) @callbacks.values_at(*cb_keys) end cb_ary.flatten! # takes care of not modifying original arrays cb_ary.compact! # we only filter for node events if event.node_event? interest_key = event.interest_key cb_ary.select! { |sub| sub.interests.include?(interest_key) } end safe_call(cb_ary, event) end
ruby
def process(event, watch_type = nil) @zk.raw_event_handler(event) logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1 event.zk = @zk cb_keys = if event.node_event? [event.path, ALL_NODE_EVENTS_KEY] elsif event.session_event? [state_key(event.state), ALL_STATE_EVENTS_KEY] else raise ZKError, "don't know how to process event: #{event.inspect}" end cb_ary = synchronize do clear_watch_restrictions(event, watch_type) @callbacks.values_at(*cb_keys) end cb_ary.flatten! # takes care of not modifying original arrays cb_ary.compact! # we only filter for node events if event.node_event? interest_key = event.interest_key cb_ary.select! { |sub| sub.interests.include?(interest_key) } end safe_call(cb_ary, event) end
[ "def", "process", "(", "event", ",", "watch_type", "=", "nil", ")", "@zk", ".", "raw_event_handler", "(", "event", ")", "logger", ".", "debug", "{", "\"EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}\"", "}", "# unless event.type == -1", "event", ".", "zk", "=", "@zk", "cb_keys", "=", "if", "event", ".", "node_event?", "[", "event", ".", "path", ",", "ALL_NODE_EVENTS_KEY", "]", "elsif", "event", ".", "session_event?", "[", "state_key", "(", "event", ".", "state", ")", ",", "ALL_STATE_EVENTS_KEY", "]", "else", "raise", "ZKError", ",", "\"don't know how to process event: #{event.inspect}\"", "end", "cb_ary", "=", "synchronize", "do", "clear_watch_restrictions", "(", "event", ",", "watch_type", ")", "@callbacks", ".", "values_at", "(", "cb_keys", ")", "end", "cb_ary", ".", "flatten!", "# takes care of not modifying original arrays", "cb_ary", ".", "compact!", "# we only filter for node events", "if", "event", ".", "node_event?", "interest_key", "=", "event", ".", "interest_key", "cb_ary", ".", "select!", "{", "|", "sub", "|", "sub", ".", "interests", ".", "include?", "(", "interest_key", ")", "}", "end", "safe_call", "(", "cb_ary", ",", "event", ")", "end" ]
called from the Client registered callback when an event fires @note this is *ONLY* dealing with asynchronous callbacks! watchers and session events go through here, NOT anything else!! @private
[ "called", "from", "the", "Client", "registered", "callback", "when", "an", "event", "fires" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/event_handler.rb#L163-L194
19,989
zk-ruby/zk
lib/zk/event_handler.rb
ZK.EventHandler.restricting_new_watches_for?
def restricting_new_watches_for?(watch_type, path) synchronize do if set = @outstanding_watches[watch_type] return set.include?(path) end end false end
ruby
def restricting_new_watches_for?(watch_type, path) synchronize do if set = @outstanding_watches[watch_type] return set.include?(path) end end false end
[ "def", "restricting_new_watches_for?", "(", "watch_type", ",", "path", ")", "synchronize", "do", "if", "set", "=", "@outstanding_watches", "[", "watch_type", "]", "return", "set", ".", "include?", "(", "path", ")", "end", "end", "false", "end" ]
returns true if there's a pending watch of type for path @private
[ "returns", "true", "if", "there", "s", "a", "pending", "watch", "of", "type", "for", "path" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/event_handler.rb#L270-L278
19,990
zk-ruby/zk
lib/zk/message_queue.rb
ZK.MessageQueue.delete_message
def delete_message(message_title) full_path = "#{full_queue_path}/#{message_title}" locker = @zk.locker("#{full_queue_path}/#{message_title}") if locker.lock! begin @zk.delete(full_path) return true ensure locker.unlock! end else return false end end
ruby
def delete_message(message_title) full_path = "#{full_queue_path}/#{message_title}" locker = @zk.locker("#{full_queue_path}/#{message_title}") if locker.lock! begin @zk.delete(full_path) return true ensure locker.unlock! end else return false end end
[ "def", "delete_message", "(", "message_title", ")", "full_path", "=", "\"#{full_queue_path}/#{message_title}\"", "locker", "=", "@zk", ".", "locker", "(", "\"#{full_queue_path}/#{message_title}\"", ")", "if", "locker", ".", "lock!", "begin", "@zk", ".", "delete", "(", "full_path", ")", "return", "true", "ensure", "locker", ".", "unlock!", "end", "else", "return", "false", "end", "end" ]
you barely ever need to actually use this method but lets you remove a message from the queue by specifying its title @param [String] message_title the title of the message to remove
[ "you", "barely", "ever", "need", "to", "actually", "use", "this", "method", "but", "lets", "you", "remove", "a", "message", "from", "the", "queue", "by", "specifying", "its", "title" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/message_queue.rb#L58-L71
19,991
zk-ruby/zk
lib/zk/message_queue.rb
ZK.MessageQueue.destroy!
def destroy! unsubscribe # first thing, make sure we don't get any callbacks related to this children = @zk.children(full_queue_path) locks = [] children.each do |path| lock = @zk.locker("#{full_queue_path}/#{path}") lock.lock! # XXX(slyphon): should this be a blocking lock? locks << lock end children.each do |path| begin @zk.delete("#{full_queue_path}/#{path}") rescue ZK::Exceptions::NoNode end end begin @zk.delete(full_queue_path) rescue ZK::Exceptions::NoNode end locks.each do |lock| lock.unlock! end end
ruby
def destroy! unsubscribe # first thing, make sure we don't get any callbacks related to this children = @zk.children(full_queue_path) locks = [] children.each do |path| lock = @zk.locker("#{full_queue_path}/#{path}") lock.lock! # XXX(slyphon): should this be a blocking lock? locks << lock end children.each do |path| begin @zk.delete("#{full_queue_path}/#{path}") rescue ZK::Exceptions::NoNode end end begin @zk.delete(full_queue_path) rescue ZK::Exceptions::NoNode end locks.each do |lock| lock.unlock! end end
[ "def", "destroy!", "unsubscribe", "# first thing, make sure we don't get any callbacks related to this", "children", "=", "@zk", ".", "children", "(", "full_queue_path", ")", "locks", "=", "[", "]", "children", ".", "each", "do", "|", "path", "|", "lock", "=", "@zk", ".", "locker", "(", "\"#{full_queue_path}/#{path}\"", ")", "lock", ".", "lock!", "# XXX(slyphon): should this be a blocking lock?", "locks", "<<", "lock", "end", "children", ".", "each", "do", "|", "path", "|", "begin", "@zk", ".", "delete", "(", "\"#{full_queue_path}/#{path}\"", ")", "rescue", "ZK", "::", "Exceptions", "::", "NoNode", "end", "end", "begin", "@zk", ".", "delete", "(", "full_queue_path", ")", "rescue", "ZK", "::", "Exceptions", "::", "NoNode", "end", "locks", ".", "each", "do", "|", "lock", "|", "lock", ".", "unlock!", "end", "end" ]
highly destructive method! WARNING! Will delete the queue and all messages in it
[ "highly", "destructive", "method!", "WARNING!", "Will", "delete", "the", "queue", "and", "all", "messages", "in", "it" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/message_queue.rb#L113-L137
19,992
zk-ruby/zk
lib/zk/threaded_callback.rb
ZK.ThreadedCallback.shutdown
def shutdown(timeout=5) # logger.debug { "#{self.class}##{__method__}" } @mutex.lock begin return true if @state == :shutdown @state = :shutdown @cond.broadcast ensure @mutex.unlock rescue nil end return true unless @thread unless @thread.join(timeout) == @thread logger.error { "#{self.class} timed out waiting for dispatch thread, callback: #{callback.inspect}" } return false end true end
ruby
def shutdown(timeout=5) # logger.debug { "#{self.class}##{__method__}" } @mutex.lock begin return true if @state == :shutdown @state = :shutdown @cond.broadcast ensure @mutex.unlock rescue nil end return true unless @thread unless @thread.join(timeout) == @thread logger.error { "#{self.class} timed out waiting for dispatch thread, callback: #{callback.inspect}" } return false end true end
[ "def", "shutdown", "(", "timeout", "=", "5", ")", "# logger.debug { \"#{self.class}##{__method__}\" }", "@mutex", ".", "lock", "begin", "return", "true", "if", "@state", "==", ":shutdown", "@state", "=", ":shutdown", "@cond", ".", "broadcast", "ensure", "@mutex", ".", "unlock", "rescue", "nil", "end", "return", "true", "unless", "@thread", "unless", "@thread", ".", "join", "(", "timeout", ")", "==", "@thread", "logger", ".", "error", "{", "\"#{self.class} timed out waiting for dispatch thread, callback: #{callback.inspect}\"", "}", "return", "false", "end", "true", "end" ]
how long to wait on thread shutdown before we return
[ "how", "long", "to", "wait", "on", "thread", "shutdown", "before", "we", "return" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/threaded_callback.rb#L29-L50
19,993
zk-ruby/zk
lib/zk/node_deletion_watcher.rb
ZK.NodeDeletionWatcher.wait_until_blocked
def wait_until_blocked(timeout=nil) @mutex.synchronize do return true unless @blocked == NOT_YET start = Time.now time_to_stop = timeout ? (start + timeout) : nil logger.debug { "#{__method__} @blocked: #{@blocked.inspect} about to wait" } @cond.wait(timeout) if (time_to_stop and (Time.now > time_to_stop)) and (@blocked == NOT_YET) return nil end (@blocked == NOT_YET) ? nil : true end end
ruby
def wait_until_blocked(timeout=nil) @mutex.synchronize do return true unless @blocked == NOT_YET start = Time.now time_to_stop = timeout ? (start + timeout) : nil logger.debug { "#{__method__} @blocked: #{@blocked.inspect} about to wait" } @cond.wait(timeout) if (time_to_stop and (Time.now > time_to_stop)) and (@blocked == NOT_YET) return nil end (@blocked == NOT_YET) ? nil : true end end
[ "def", "wait_until_blocked", "(", "timeout", "=", "nil", ")", "@mutex", ".", "synchronize", "do", "return", "true", "unless", "@blocked", "==", "NOT_YET", "start", "=", "Time", ".", "now", "time_to_stop", "=", "timeout", "?", "(", "start", "+", "timeout", ")", ":", "nil", "logger", ".", "debug", "{", "\"#{__method__} @blocked: #{@blocked.inspect} about to wait\"", "}", "@cond", ".", "wait", "(", "timeout", ")", "if", "(", "time_to_stop", "and", "(", "Time", ".", "now", ">", "time_to_stop", ")", ")", "and", "(", "@blocked", "==", "NOT_YET", ")", "return", "nil", "end", "(", "@blocked", "==", "NOT_YET", ")", "?", "nil", ":", "true", "end", "end" ]
this is for testing, allows us to wait until this object has gone into blocking state. avoids the race where if we have already been blocked and released this will not block the caller pass optional timeout to return after that amount of time or nil to block forever @return [true] if we have been blocked previously or are currently blocked, @return [nil] if we timeout
[ "this", "is", "for", "testing", "allows", "us", "to", "wait", "until", "this", "object", "has", "gone", "into", "blocking", "state", "." ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/node_deletion_watcher.rb#L84-L100
19,994
zk-ruby/zk
lib/zk/node_deletion_watcher.rb
ZK.NodeDeletionWatcher.wait_for_result
def wait_for_result(timeout) # do the deadline maths time_to_stop = timeout ? (Time.now + timeout) : nil # slight time slippage between here # until @result # if timeout # and here now = Time.now if @result return elsif (now >= time_to_stop) @result = TIMED_OUT return end @cond.wait(time_to_stop.to_f - now.to_f) else @cond.wait_until { @result } end end end
ruby
def wait_for_result(timeout) # do the deadline maths time_to_stop = timeout ? (Time.now + timeout) : nil # slight time slippage between here # until @result # if timeout # and here now = Time.now if @result return elsif (now >= time_to_stop) @result = TIMED_OUT return end @cond.wait(time_to_stop.to_f - now.to_f) else @cond.wait_until { @result } end end end
[ "def", "wait_for_result", "(", "timeout", ")", "# do the deadline maths", "time_to_stop", "=", "timeout", "?", "(", "Time", ".", "now", "+", "timeout", ")", ":", "nil", "# slight time slippage between here", "#", "until", "@result", "#", "if", "timeout", "# and here", "now", "=", "Time", ".", "now", "if", "@result", "return", "elsif", "(", "now", ">=", "time_to_stop", ")", "@result", "=", "TIMED_OUT", "return", "end", "@cond", ".", "wait", "(", "time_to_stop", ".", "to_f", "-", "now", ".", "to_f", ")", "else", "@cond", ".", "wait_until", "{", "@result", "}", "end", "end", "end" ]
this method must be synchronized on @mutex, obviously
[ "this", "method", "must", "be", "synchronized", "on" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/node_deletion_watcher.rb#L177-L197
19,995
zk-ruby/zk
lib/zk/node_deletion_watcher.rb
ZK.NodeDeletionWatcher.watch_appropriate_nodes
def watch_appropriate_nodes remaining_paths.last( threshold + 1 ).reverse_each do |path| next if watched_paths.include? path watched_paths << path finish_node(path) unless zk.exists?(path, :watch => true) end end
ruby
def watch_appropriate_nodes remaining_paths.last( threshold + 1 ).reverse_each do |path| next if watched_paths.include? path watched_paths << path finish_node(path) unless zk.exists?(path, :watch => true) end end
[ "def", "watch_appropriate_nodes", "remaining_paths", ".", "last", "(", "threshold", "+", "1", ")", ".", "reverse_each", "do", "|", "path", "|", "next", "if", "watched_paths", ".", "include?", "path", "watched_paths", "<<", "path", "finish_node", "(", "path", ")", "unless", "zk", ".", "exists?", "(", "path", ",", ":watch", "=>", "true", ")", "end", "end" ]
ensures that threshold + 1 nodes are being watched
[ "ensures", "that", "threshold", "+", "1", "nodes", "are", "being", "watched" ]
155db85653c3831cc005140b5fd58adc80a54d8e
https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/node_deletion_watcher.rb#L237-L243
19,996
fog/fog-core
lib/fog/core/services_mixin.rb
Fog.ServicesMixin.require_service_provider_library
def require_service_provider_library(service, provider) require "fog/#{provider}/#{service}" rescue LoadError # Try to require the service provider in an alternate location Fog::Logger.deprecation("Unable to require fog/#{provider}/#{service}") Fog::Logger.deprecation( format(E_SERVICE_PROVIDER_PATH, service: service, provider: provider) ) require "fog/#{service}/#{provider}" end
ruby
def require_service_provider_library(service, provider) require "fog/#{provider}/#{service}" rescue LoadError # Try to require the service provider in an alternate location Fog::Logger.deprecation("Unable to require fog/#{provider}/#{service}") Fog::Logger.deprecation( format(E_SERVICE_PROVIDER_PATH, service: service, provider: provider) ) require "fog/#{service}/#{provider}" end
[ "def", "require_service_provider_library", "(", "service", ",", "provider", ")", "require", "\"fog/#{provider}/#{service}\"", "rescue", "LoadError", "# Try to require the service provider in an alternate location", "Fog", "::", "Logger", ".", "deprecation", "(", "\"Unable to require fog/#{provider}/#{service}\"", ")", "Fog", "::", "Logger", ".", "deprecation", "(", "format", "(", "E_SERVICE_PROVIDER_PATH", ",", "service", ":", "service", ",", "provider", ":", "provider", ")", ")", "require", "\"fog/#{service}/#{provider}\"", "end" ]
This method should be removed once all providers are extracted. Bundler will correctly require all dependencies automatically and thus fog-core wont need to know any specifics providers. Each provider will have to load its dependencies.
[ "This", "method", "should", "be", "removed", "once", "all", "providers", "are", "extracted", ".", "Bundler", "will", "correctly", "require", "all", "dependencies", "automatically", "and", "thus", "fog", "-", "core", "wont", "need", "to", "know", "any", "specifics", "providers", ".", "Each", "provider", "will", "have", "to", "load", "its", "dependencies", "." ]
a60d4001981b8d4ca9a803ae9cac07f3a99fad23
https://github.com/fog/fog-core/blob/a60d4001981b8d4ca9a803ae9cac07f3a99fad23/lib/fog/core/services_mixin.rb#L46-L54
19,997
boxen/boxen
lib/boxen/flags.rb
Boxen.Flags.apply
def apply(config) config.debug = debug? config.fde = fde? if config.fde? config.homedir = homedir if homedir config.logfile = logfile if logfile config.login = login if login config.token = token if token config.pretend = pretend? config.profile = profile? config.future_parser = future_parser? config.report = report? config.graph = graph? config.srcdir = srcdir if srcdir config.stealth = stealth? config.user = user if user config.color = color? config end
ruby
def apply(config) config.debug = debug? config.fde = fde? if config.fde? config.homedir = homedir if homedir config.logfile = logfile if logfile config.login = login if login config.token = token if token config.pretend = pretend? config.profile = profile? config.future_parser = future_parser? config.report = report? config.graph = graph? config.srcdir = srcdir if srcdir config.stealth = stealth? config.user = user if user config.color = color? config end
[ "def", "apply", "(", "config", ")", "config", ".", "debug", "=", "debug?", "config", ".", "fde", "=", "fde?", "if", "config", ".", "fde?", "config", ".", "homedir", "=", "homedir", "if", "homedir", "config", ".", "logfile", "=", "logfile", "if", "logfile", "config", ".", "login", "=", "login", "if", "login", "config", ".", "token", "=", "token", "if", "token", "config", ".", "pretend", "=", "pretend?", "config", ".", "profile", "=", "profile?", "config", ".", "future_parser", "=", "future_parser?", "config", ".", "report", "=", "report?", "config", ".", "graph", "=", "graph?", "config", ".", "srcdir", "=", "srcdir", "if", "srcdir", "config", ".", "stealth", "=", "stealth?", "config", ".", "user", "=", "user", "if", "user", "config", ".", "color", "=", "color?", "config", "end" ]
Create a new instance, optionally providing CLI `args` to parse immediately. Apply these flags to `config`. Returns `config`.
[ "Create", "a", "new", "instance", "optionally", "providing", "CLI", "args", "to", "parse", "immediately", ".", "Apply", "these", "flags", "to", "config", ".", "Returns", "config", "." ]
a11fcba2ee9fe9ad60109e36e4ec481c476c98e9
https://github.com/boxen/boxen/blob/a11fcba2ee9fe9ad60109e36e4ec481c476c98e9/lib/boxen/flags.rb#L160-L178
19,998
AnkurGel/Instamojo-rb
lib/common_object.rb
Instamojo.CommonObject.construct_hash
def construct_hash vars = instance_variables.reject { |x| [:@client, :@original].include? x } Hash[vars.map { |key| [key.to_s[1..key.length], instance_variable_get(key)] }] end
ruby
def construct_hash vars = instance_variables.reject { |x| [:@client, :@original].include? x } Hash[vars.map { |key| [key.to_s[1..key.length], instance_variable_get(key)] }] end
[ "def", "construct_hash", "vars", "=", "instance_variables", ".", "reject", "{", "|", "x", "|", "[", ":@client", ",", ":@original", "]", ".", "include?", "x", "}", "Hash", "[", "vars", ".", "map", "{", "|", "key", "|", "[", "key", ".", "to_s", "[", "1", "..", "key", ".", "length", "]", ",", "instance_variable_get", "(", "key", ")", "]", "}", "]", "end" ]
Construct hash from mutated parameters
[ "Construct", "hash", "from", "mutated", "parameters" ]
39972c695bcb460673bf29de01cb6b47b57baa58
https://github.com/AnkurGel/Instamojo-rb/blob/39972c695bcb460673bf29de01cb6b47b57baa58/lib/common_object.rb#L35-L38
19,999
whazzmaster/fitgem
lib/fitgem/notifications.rb
Fitgem.Client.create_subscription
def create_subscription(opts) resp = raw_post make_subscription_url(opts.merge({:use_subscription_id => true})), EMPTY_BODY, make_headers(opts) [resp.status, extract_response_body(resp)] end
ruby
def create_subscription(opts) resp = raw_post make_subscription_url(opts.merge({:use_subscription_id => true})), EMPTY_BODY, make_headers(opts) [resp.status, extract_response_body(resp)] end
[ "def", "create_subscription", "(", "opts", ")", "resp", "=", "raw_post", "make_subscription_url", "(", "opts", ".", "merge", "(", "{", ":use_subscription_id", "=>", "true", "}", ")", ")", ",", "EMPTY_BODY", ",", "make_headers", "(", "opts", ")", "[", "resp", ".", "status", ",", "extract_response_body", "(", "resp", ")", "]", "end" ]
Creates a notification subscription @note You must check the HTTP response code to check the status of the request to add a subscription. See {https://wiki.fitbit.com/display/API/Fitbit+Subscriptions+API} for information about what the codes mean. @param [Hash] opts The notification subscription data @option opts [Symbol] :type The type of subscription (valid values are :activities, :foods, :sleep, :body, and :all). REQUIRED @option opts [Integer, String] :subscriptionId The subscription id @return [Integer, Hash] An array containing the HTTP response code and a hash containing confirmation information for the subscription. @since v0.4.0
[ "Creates", "a", "notification", "subscription" ]
c8c4fc908feee91bb138e518f6882507b3067ae1
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/notifications.rb#L29-L32