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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.tag
def tag(name) tags.find {|tag| tag.tag_name.to_s == name.to_s } end
ruby
def tag(name) tags.find {|tag| tag.tag_name.to_s == name.to_s } end
[ "def", "tag", "(", "name", ")", "tags", ".", "find", "{", "|", "tag", "|", "tag", ".", "tag_name", ".", "to_s", "==", "name", ".", "to_s", "}", "end" ]
Convenience method to return the first tag object in the list of tag objects of that name @example doc = Docstring.new("@return zero when nil") doc.tag(:return).text # => "zero when nil" @param [#to_s] name the tag name to return data for @return [Tags::Tag] the first tag in the list of {#tags}
[ "Convenience", "method", "to", "return", "the", "first", "tag", "object", "in", "the", "list", "of", "tag", "objects", "of", "that", "name" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L265-L267
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.tags
def tags(name = nil) list = stable_sort_by(@tags + convert_ref_tags, &:tag_name) return list unless name list.select {|tag| tag.tag_name.to_s == name.to_s } end
ruby
def tags(name = nil) list = stable_sort_by(@tags + convert_ref_tags, &:tag_name) return list unless name list.select {|tag| tag.tag_name.to_s == name.to_s } end
[ "def", "tags", "(", "name", "=", "nil", ")", "list", "=", "stable_sort_by", "(", "@tags", "+", "convert_ref_tags", ",", ":tag_name", ")", "return", "list", "unless", "name", "list", ".", "select", "{", "|", "tag", "|", "tag", ".", "tag_name", ".", "to_s", "==", "name", ".", "to_s", "}", "end" ]
Returns a list of tags specified by +name+ or all tags if +name+ is not specified. @param [#to_s] name the tag name to return data for, or nil for all tags @return [Array<Tags::Tag>] the list of tags by the specified tag name
[ "Returns", "a", "list", "of", "tags", "specified", "by", "+", "name", "+", "or", "all", "tags", "if", "+", "name", "+", "is", "not", "specified", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L273-L277
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.has_tag?
def has_tag?(name) tags.any? {|tag| tag.tag_name.to_s == name.to_s } end
ruby
def has_tag?(name) tags.any? {|tag| tag.tag_name.to_s == name.to_s } end
[ "def", "has_tag?", "(", "name", ")", "tags", ".", "any?", "{", "|", "tag", "|", "tag", ".", "tag_name", ".", "to_s", "==", "name", ".", "to_s", "}", "end" ]
Returns true if at least one tag by the name +name+ was declared @param [String] name the tag name to search for @return [Boolean] whether or not the tag +name+ was declared
[ "Returns", "true", "if", "at", "least", "one", "tag", "by", "the", "name", "+", "name", "+", "was", "declared" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L283-L285
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.blank?
def blank?(only_visible_tags = true) if only_visible_tags empty? && !tags.any? {|tag| Tags::Library.visible_tags.include?(tag.tag_name.to_sym) } else empty? && @tags.empty? && @ref_tags.empty? end end
ruby
def blank?(only_visible_tags = true) if only_visible_tags empty? && !tags.any? {|tag| Tags::Library.visible_tags.include?(tag.tag_name.to_sym) } else empty? && @tags.empty? && @ref_tags.empty? end end
[ "def", "blank?", "(", "only_visible_tags", "=", "true", ")", "if", "only_visible_tags", "empty?", "&&", "!", "tags", ".", "any?", "{", "|", "tag", "|", "Tags", "::", "Library", ".", "visible_tags", ".", "include?", "(", "tag", ".", "tag_name", ".", "to_sym", ")", "}", "else", "empty?", "&&", "@tags", ".", "empty?", "&&", "@ref_tags", ".", "empty?", "end", "end" ]
Returns true if the docstring has no content that is visible to a template. @param [Boolean] only_visible_tags whether only {Tags::Library.visible_tags} should be checked, or if all tags should be considered. @return [Boolean] whether or not the docstring has content
[ "Returns", "true", "if", "the", "docstring", "has", "no", "content", "that", "is", "visible", "to", "a", "template", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L310-L316
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.convert_ref_tags
def convert_ref_tags list = @ref_tags.reject {|t| CodeObjects::Proxy === t.owner } @ref_tag_recurse_count ||= 0 @ref_tag_recurse_count += 1 if @ref_tag_recurse_count > 2 log.error "#{@object.file}:#{@object.line}: Detected circular reference tag in " \ "`#{@object}', ignoring all reference tags for this object " \ "(#{@ref_tags.map {|t| "@#{t.tag_name}" }.join(", ")})." @ref_tags = [] return @ref_tags end list = list.map(&:tags).flatten @ref_tag_recurse_count -= 1 list end
ruby
def convert_ref_tags list = @ref_tags.reject {|t| CodeObjects::Proxy === t.owner } @ref_tag_recurse_count ||= 0 @ref_tag_recurse_count += 1 if @ref_tag_recurse_count > 2 log.error "#{@object.file}:#{@object.line}: Detected circular reference tag in " \ "`#{@object}', ignoring all reference tags for this object " \ "(#{@ref_tags.map {|t| "@#{t.tag_name}" }.join(", ")})." @ref_tags = [] return @ref_tags end list = list.map(&:tags).flatten @ref_tag_recurse_count -= 1 list end
[ "def", "convert_ref_tags", "list", "=", "@ref_tags", ".", "reject", "{", "|", "t", "|", "CodeObjects", "::", "Proxy", "===", "t", ".", "owner", "}", "@ref_tag_recurse_count", "||=", "0", "@ref_tag_recurse_count", "+=", "1", "if", "@ref_tag_recurse_count", ">", "2", "log", ".", "error", "\"#{@object.file}:#{@object.line}: Detected circular reference tag in \"", "\"`#{@object}', ignoring all reference tags for this object \"", "\"(#{@ref_tags.map {|t| \"@#{t.tag_name}\" }.join(\", \")}).\"", "@ref_tags", "=", "[", "]", "return", "@ref_tags", "end", "list", "=", "list", ".", "map", "(", ":tags", ")", ".", "flatten", "@ref_tag_recurse_count", "-=", "1", "list", "end" ]
Maps valid reference tags @return [Array<Tags::RefTag>] the list of valid reference tags
[ "Maps", "valid", "reference", "tags" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L344-L359
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.parse_comments
def parse_comments(comments) parser = self.class.parser parser.parse(comments, object) @all = parser.raw_text @unresolved_reference = parser.reference add_tag(*parser.tags) parser.text end
ruby
def parse_comments(comments) parser = self.class.parser parser.parse(comments, object) @all = parser.raw_text @unresolved_reference = parser.reference add_tag(*parser.tags) parser.text end
[ "def", "parse_comments", "(", "comments", ")", "parser", "=", "self", ".", "class", ".", "parser", "parser", ".", "parse", "(", "comments", ",", "object", ")", "@all", "=", "parser", ".", "raw_text", "@unresolved_reference", "=", "parser", ".", "reference", "add_tag", "(", "parser", ".", "tags", ")", "parser", ".", "text", "end" ]
Parses out comments split by newlines into a new code object @param [String] comments the newline delimited array of comments. If the comments are passed as a String, they will be split by newlines. @return [String] the non-metadata portion of the comments to be used as a docstring
[ "Parses", "out", "comments", "split", "by", "newlines", "into", "a", "new", "code", "object" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L369-L376
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.stable_sort_by
def stable_sort_by(list) list.each_with_index.sort_by {|tag, i| [yield(tag), i] }.map(&:first) end
ruby
def stable_sort_by(list) list.each_with_index.sort_by {|tag, i| [yield(tag), i] }.map(&:first) end
[ "def", "stable_sort_by", "(", "list", ")", "list", ".", "each_with_index", ".", "sort_by", "{", "|", "tag", ",", "i", "|", "[", "yield", "(", "tag", ")", ",", "i", "]", "}", ".", "map", "(", ":first", ")", "end" ]
A stable sort_by method. @param list [Enumerable] the list to sort. @return [Array] a stable sorted list.
[ "A", "stable", "sort_by", "method", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L382-L384
train
lsegal/yard
lib/yard/code_objects/module_object.rb
YARD::CodeObjects.ModuleObject.inheritance_tree
def inheritance_tree(include_mods = false) return [self] unless include_mods [self] + mixins(:instance, :class).map do |m| next if m == self next m unless m.respond_to?(:inheritance_tree) m.inheritance_tree(true) end.compact.flatten.uniq end
ruby
def inheritance_tree(include_mods = false) return [self] unless include_mods [self] + mixins(:instance, :class).map do |m| next if m == self next m unless m.respond_to?(:inheritance_tree) m.inheritance_tree(true) end.compact.flatten.uniq end
[ "def", "inheritance_tree", "(", "include_mods", "=", "false", ")", "return", "[", "self", "]", "unless", "include_mods", "[", "self", "]", "+", "mixins", "(", ":instance", ",", ":class", ")", ".", "map", "do", "|", "m", "|", "next", "if", "m", "==", "self", "next", "m", "unless", "m", ".", "respond_to?", "(", ":inheritance_tree", ")", "m", ".", "inheritance_tree", "(", "true", ")", "end", ".", "compact", ".", "flatten", ".", "uniq", "end" ]
Returns the inheritance tree of mixins. @param [Boolean] include_mods if true, will include mixed in modules (which is likely what is wanted). @return [Array<NamespaceObject>] a list of namespace objects
[ "Returns", "the", "inheritance", "tree", "of", "mixins", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/module_object.rb#L12-L19
train
lsegal/yard
lib/yard/code_objects/namespace_object.rb
YARD::CodeObjects.NamespaceObject.child
def child(opts = {}) if !opts.is_a?(Hash) children.find {|o| o.name == opts.to_sym } else opts = SymbolHash[opts] children.find do |obj| opts.each do |meth, value| break false unless value.is_a?(Array) ? value.include?(obj[meth]) : obj[meth] == value end end end end
ruby
def child(opts = {}) if !opts.is_a?(Hash) children.find {|o| o.name == opts.to_sym } else opts = SymbolHash[opts] children.find do |obj| opts.each do |meth, value| break false unless value.is_a?(Array) ? value.include?(obj[meth]) : obj[meth] == value end end end end
[ "def", "child", "(", "opts", "=", "{", "}", ")", "if", "!", "opts", ".", "is_a?", "(", "Hash", ")", "children", ".", "find", "{", "|", "o", "|", "o", ".", "name", "==", "opts", ".", "to_sym", "}", "else", "opts", "=", "SymbolHash", "[", "opts", "]", "children", ".", "find", "do", "|", "obj", "|", "opts", ".", "each", "do", "|", "meth", ",", "value", "|", "break", "false", "unless", "value", ".", "is_a?", "(", "Array", ")", "?", "value", ".", "include?", "(", "obj", "[", "meth", "]", ")", ":", "obj", "[", "meth", "]", "==", "value", "end", "end", "end", "end" ]
Looks for a child that matches the attributes specified by +opts+. @example Finds a child by name and scope namespace.child(:name => :to_s, :scope => :instance) # => #<yardoc method MyClass#to_s> @return [Base, nil] the first matched child object, or nil
[ "Looks", "for", "a", "child", "that", "matches", "the", "attributes", "specified", "by", "+", "opts", "+", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L86-L97
train
lsegal/yard
lib/yard/code_objects/namespace_object.rb
YARD::CodeObjects.NamespaceObject.meths
def meths(opts = {}) opts = SymbolHash[ :visibility => [:public, :private, :protected], :scope => [:class, :instance], :included => true ].update(opts) opts[:visibility] = [opts[:visibility]].flatten opts[:scope] = [opts[:scope]].flatten ourmeths = children.select do |o| o.is_a?(MethodObject) && opts[:visibility].include?(o.visibility) && opts[:scope].include?(o.scope) end ourmeths + (opts[:included] ? included_meths(opts) : []) end
ruby
def meths(opts = {}) opts = SymbolHash[ :visibility => [:public, :private, :protected], :scope => [:class, :instance], :included => true ].update(opts) opts[:visibility] = [opts[:visibility]].flatten opts[:scope] = [opts[:scope]].flatten ourmeths = children.select do |o| o.is_a?(MethodObject) && opts[:visibility].include?(o.visibility) && opts[:scope].include?(o.scope) end ourmeths + (opts[:included] ? included_meths(opts) : []) end
[ "def", "meths", "(", "opts", "=", "{", "}", ")", "opts", "=", "SymbolHash", "[", ":visibility", "=>", "[", ":public", ",", ":private", ",", ":protected", "]", ",", ":scope", "=>", "[", ":class", ",", ":instance", "]", ",", ":included", "=>", "true", "]", ".", "update", "(", "opts", ")", "opts", "[", ":visibility", "]", "=", "[", "opts", "[", ":visibility", "]", "]", ".", "flatten", "opts", "[", ":scope", "]", "=", "[", "opts", "[", ":scope", "]", "]", ".", "flatten", "ourmeths", "=", "children", ".", "select", "do", "|", "o", "|", "o", ".", "is_a?", "(", "MethodObject", ")", "&&", "opts", "[", ":visibility", "]", ".", "include?", "(", "o", ".", "visibility", ")", "&&", "opts", "[", ":scope", "]", ".", "include?", "(", "o", ".", "scope", ")", "end", "ourmeths", "+", "(", "opts", "[", ":included", "]", "?", "included_meths", "(", "opts", ")", ":", "[", "]", ")", "end" ]
Returns all methods that match the attributes specified by +opts+. If no options are provided, returns all methods. @example Finds all private and protected class methods namespace.meths(:visibility => [:private, :protected], :scope => :class) # => [#<yardoc method MyClass.privmeth>, #<yardoc method MyClass.protmeth>] @option opts [Array<Symbol>, Symbol] :visibility ([:public, :private, :protected]) the visibility of the methods to list. Can be an array or single value. @option opts [Array<Symbol>, Symbol] :scope ([:class, :instance]) the scope of the methods to list. Can be an array or single value. @option opts [Boolean] :included (true) whether to include mixed in methods in the list. @return [Array<MethodObject>] a list of method objects
[ "Returns", "all", "methods", "that", "match", "the", "attributes", "specified", "by", "+", "opts", "+", ".", "If", "no", "options", "are", "provided", "returns", "all", "methods", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L113-L130
train
lsegal/yard
lib/yard/code_objects/namespace_object.rb
YARD::CodeObjects.NamespaceObject.included_meths
def included_meths(opts = {}) opts = SymbolHash[:scope => [:instance, :class]].update(opts) [opts[:scope]].flatten.map do |scope| mixins(scope).inject([]) do |list, mixin| next list if mixin.is_a?(Proxy) arr = mixin.meths(opts.merge(:scope => :instance)).reject do |o| next false if opts[:all] child(:name => o.name, :scope => scope) || list.find {|o2| o2.name == o.name } end arr.map! {|o| ExtendedMethodObject.new(o) } if scope == :class list + arr end end.flatten end
ruby
def included_meths(opts = {}) opts = SymbolHash[:scope => [:instance, :class]].update(opts) [opts[:scope]].flatten.map do |scope| mixins(scope).inject([]) do |list, mixin| next list if mixin.is_a?(Proxy) arr = mixin.meths(opts.merge(:scope => :instance)).reject do |o| next false if opts[:all] child(:name => o.name, :scope => scope) || list.find {|o2| o2.name == o.name } end arr.map! {|o| ExtendedMethodObject.new(o) } if scope == :class list + arr end end.flatten end
[ "def", "included_meths", "(", "opts", "=", "{", "}", ")", "opts", "=", "SymbolHash", "[", ":scope", "=>", "[", ":instance", ",", ":class", "]", "]", ".", "update", "(", "opts", ")", "[", "opts", "[", ":scope", "]", "]", ".", "flatten", ".", "map", "do", "|", "scope", "|", "mixins", "(", "scope", ")", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "mixin", "|", "next", "list", "if", "mixin", ".", "is_a?", "(", "Proxy", ")", "arr", "=", "mixin", ".", "meths", "(", "opts", ".", "merge", "(", ":scope", "=>", ":instance", ")", ")", ".", "reject", "do", "|", "o", "|", "next", "false", "if", "opts", "[", ":all", "]", "child", "(", ":name", "=>", "o", ".", "name", ",", ":scope", "=>", "scope", ")", "||", "list", ".", "find", "{", "|", "o2", "|", "o2", ".", "name", "==", "o", ".", "name", "}", "end", "arr", ".", "map!", "{", "|", "o", "|", "ExtendedMethodObject", ".", "new", "(", "o", ")", "}", "if", "scope", "==", ":class", "list", "+", "arr", "end", "end", ".", "flatten", "end" ]
Returns methods included from any mixins that match the attributes specified by +opts+. If no options are specified, returns all included methods. @option opts [Array<Symbol>, Symbol] :visibility ([:public, :private, :protected]) the visibility of the methods to list. Can be an array or single value. @option opts [Array<Symbol>, Symbol] :scope ([:class, :instance]) the scope of the methods to list. Can be an array or single value. @option opts [Boolean] :included (true) whether to include mixed in methods in the list. @see #meths
[ "Returns", "methods", "included", "from", "any", "mixins", "that", "match", "the", "attributes", "specified", "by", "+", "opts", "+", ".", "If", "no", "options", "are", "specified", "returns", "all", "included", "methods", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L144-L157
train
lsegal/yard
lib/yard/code_objects/namespace_object.rb
YARD::CodeObjects.NamespaceObject.constants
def constants(opts = {}) opts = SymbolHash[:included => true].update(opts) consts = children.select {|o| o.is_a? ConstantObject } consts + (opts[:included] ? included_constants : []) end
ruby
def constants(opts = {}) opts = SymbolHash[:included => true].update(opts) consts = children.select {|o| o.is_a? ConstantObject } consts + (opts[:included] ? included_constants : []) end
[ "def", "constants", "(", "opts", "=", "{", "}", ")", "opts", "=", "SymbolHash", "[", ":included", "=>", "true", "]", ".", "update", "(", "opts", ")", "consts", "=", "children", ".", "select", "{", "|", "o", "|", "o", ".", "is_a?", "ConstantObject", "}", "consts", "+", "(", "opts", "[", ":included", "]", "?", "included_constants", ":", "[", "]", ")", "end" ]
Returns all constants in the namespace @option opts [Boolean] :included (true) whether or not to include mixed in constants in list @return [Array<ConstantObject>] a list of constant objects
[ "Returns", "all", "constants", "in", "the", "namespace" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L164-L168
train
lsegal/yard
lib/yard/code_objects/namespace_object.rb
YARD::CodeObjects.NamespaceObject.included_constants
def included_constants instance_mixins.inject([]) do |list, mixin| if mixin.respond_to? :constants list += mixin.constants.reject do |o| child(:name => o.name) || list.find {|o2| o2.name == o.name } end else list end end end
ruby
def included_constants instance_mixins.inject([]) do |list, mixin| if mixin.respond_to? :constants list += mixin.constants.reject do |o| child(:name => o.name) || list.find {|o2| o2.name == o.name } end else list end end end
[ "def", "included_constants", "instance_mixins", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "mixin", "|", "if", "mixin", ".", "respond_to?", ":constants", "list", "+=", "mixin", ".", "constants", ".", "reject", "do", "|", "o", "|", "child", "(", ":name", "=>", "o", ".", "name", ")", "||", "list", ".", "find", "{", "|", "o2", "|", "o2", ".", "name", "==", "o", ".", "name", "}", "end", "else", "list", "end", "end", "end" ]
Returns constants included from any mixins @return [Array<ConstantObject>] a list of constant objects
[ "Returns", "constants", "included", "from", "any", "mixins" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L172-L182
train
dmayer/idb
lib/lib/ca_interface.rb
Idb.CAInterface.remove_cert
def remove_cert(cert) der = cert.to_der query = %(DELETE FROM "tsettings" WHERE sha1 = #{blobify(sha1_from_der(der))};) begin db = SQLite3::Database.new(@db_path) db.execute(query) db.close rescue StandardError => e raise "[*] Error writing to SQLite database at #{@db_path}: #{e.message}" end end
ruby
def remove_cert(cert) der = cert.to_der query = %(DELETE FROM "tsettings" WHERE sha1 = #{blobify(sha1_from_der(der))};) begin db = SQLite3::Database.new(@db_path) db.execute(query) db.close rescue StandardError => e raise "[*] Error writing to SQLite database at #{@db_path}: #{e.message}" end end
[ "def", "remove_cert", "(", "cert", ")", "der", "=", "cert", ".", "to_der", "query", "=", "%(DELETE FROM \"tsettings\" WHERE sha1 = #{blobify(sha1_from_der(der))};)", "begin", "db", "=", "SQLite3", "::", "Database", ".", "new", "(", "@db_path", ")", "db", ".", "execute", "(", "query", ")", "db", ".", "close", "rescue", "StandardError", "=>", "e", "raise", "\"[*] Error writing to SQLite database at #{@db_path}: #{e.message}\"", "end", "end" ]
performs uninstall based on sha1 hash provided in certfile
[ "performs", "uninstall", "based", "on", "sha1", "hash", "provided", "in", "certfile" ]
038355497091b24c53596817b8818d2b2bc18e4b
https://github.com/dmayer/idb/blob/038355497091b24c53596817b8818d2b2bc18e4b/lib/lib/ca_interface.rb#L9-L20
train
charlotte-ruby/impressionist
app/models/impressionist/impressionable.rb
Impressionist.Impressionable.impressionist_count
def impressionist_count(options={}) # Uses these options as defaults unless overridden in options hash options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now) # If a start_date is provided, finds impressions between then and the end_date. Otherwise returns all impressions imps = options[:start_date].blank? ? impressions : impressions.where("created_at >= ? and created_at <= ?", options[:start_date], options[:end_date]) if options[:message] imps = imps.where("impressions.message = ?", options[:message]) end # Count all distinct impressions unless the :all filter is provided. distinct = options[:filter] != :all if Rails::VERSION::MAJOR >= 4 distinct ? imps.select(options[:filter]).distinct.count : imps.count else distinct ? imps.count(options[:filter], :distinct => true) : imps.count end end
ruby
def impressionist_count(options={}) # Uses these options as defaults unless overridden in options hash options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now) # If a start_date is provided, finds impressions between then and the end_date. Otherwise returns all impressions imps = options[:start_date].blank? ? impressions : impressions.where("created_at >= ? and created_at <= ?", options[:start_date], options[:end_date]) if options[:message] imps = imps.where("impressions.message = ?", options[:message]) end # Count all distinct impressions unless the :all filter is provided. distinct = options[:filter] != :all if Rails::VERSION::MAJOR >= 4 distinct ? imps.select(options[:filter]).distinct.count : imps.count else distinct ? imps.count(options[:filter], :distinct => true) : imps.count end end
[ "def", "impressionist_count", "(", "options", "=", "{", "}", ")", "# Uses these options as defaults unless overridden in options hash", "options", ".", "reverse_merge!", "(", ":filter", "=>", ":request_hash", ",", ":start_date", "=>", "nil", ",", ":end_date", "=>", "Time", ".", "now", ")", "# If a start_date is provided, finds impressions between then and the end_date. Otherwise returns all impressions", "imps", "=", "options", "[", ":start_date", "]", ".", "blank?", "?", "impressions", ":", "impressions", ".", "where", "(", "\"created_at >= ? and created_at <= ?\"", ",", "options", "[", ":start_date", "]", ",", "options", "[", ":end_date", "]", ")", "if", "options", "[", ":message", "]", "imps", "=", "imps", ".", "where", "(", "\"impressions.message = ?\"", ",", "options", "[", ":message", "]", ")", "end", "# Count all distinct impressions unless the :all filter is provided.", "distinct", "=", "options", "[", ":filter", "]", "!=", ":all", "if", "Rails", "::", "VERSION", "::", "MAJOR", ">=", "4", "distinct", "?", "imps", ".", "select", "(", "options", "[", ":filter", "]", ")", ".", "distinct", ".", "count", ":", "imps", ".", "count", "else", "distinct", "?", "imps", ".", "count", "(", "options", "[", ":filter", "]", ",", ":distinct", "=>", "true", ")", ":", "imps", ".", "count", "end", "end" ]
end of ClassMethods
[ "end", "of", "ClassMethods" ]
79c8dc02864e9b998009396d7c80dcbe78bed104
https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/models/impressionist/impressionable.rb#L31-L49
train
charlotte-ruby/impressionist
lib/impressionist/models/mongoid/impressionist/impressionable.rb
Impressionist.Impressionable.impressionist_count
def impressionist_count(options={}) # Uses these options as defaults unless overridden in options hash options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now) # If a start_date is provided, finds impressions between then and the end_date. # Otherwise returns all impressions imps = options[:start_date].blank? ? impressions : impressions.between(created_at: options[:start_date]..options[:end_date]) # Count all distinct impressions unless the :all filter is provided distinct = options[:filter] != :all distinct ? imps.where(options[:filter].ne => nil).distinct(options[:filter]).count : imps.count end
ruby
def impressionist_count(options={}) # Uses these options as defaults unless overridden in options hash options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now) # If a start_date is provided, finds impressions between then and the end_date. # Otherwise returns all impressions imps = options[:start_date].blank? ? impressions : impressions.between(created_at: options[:start_date]..options[:end_date]) # Count all distinct impressions unless the :all filter is provided distinct = options[:filter] != :all distinct ? imps.where(options[:filter].ne => nil).distinct(options[:filter]).count : imps.count end
[ "def", "impressionist_count", "(", "options", "=", "{", "}", ")", "# Uses these options as defaults unless overridden in options hash", "options", ".", "reverse_merge!", "(", ":filter", "=>", ":request_hash", ",", ":start_date", "=>", "nil", ",", ":end_date", "=>", "Time", ".", "now", ")", "# If a start_date is provided, finds impressions between then and the end_date.", "# Otherwise returns all impressions", "imps", "=", "options", "[", ":start_date", "]", ".", "blank?", "?", "impressions", ":", "impressions", ".", "between", "(", "created_at", ":", "options", "[", ":start_date", "]", "..", "options", "[", ":end_date", "]", ")", "# Count all distinct impressions unless the :all filter is provided", "distinct", "=", "options", "[", ":filter", "]", "!=", ":all", "distinct", "?", "imps", ".", "where", "(", "options", "[", ":filter", "]", ".", "ne", "=>", "nil", ")", ".", "distinct", "(", "options", "[", ":filter", "]", ")", ".", "count", ":", "imps", ".", "count", "end" ]
Overides impressionist_count in order to provide mongoid compability
[ "Overides", "impressionist_count", "in", "order", "to", "provide", "mongoid", "compability" ]
79c8dc02864e9b998009396d7c80dcbe78bed104
https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/lib/impressionist/models/mongoid/impressionist/impressionable.rb#L8-L22
train
charlotte-ruby/impressionist
app/controllers/impressionist_controller.rb
ImpressionistController.InstanceMethods.associative_create_statement
def associative_create_statement(query_params={}) filter = ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters) query_params.reverse_merge!( :controller_name => controller_name, :action_name => action_name, :user_id => user_id, :request_hash => @impressionist_hash, :session_hash => session_hash, :ip_address => request.remote_ip, :referrer => request.referer, :params => filter.filter(params_hash) ) end
ruby
def associative_create_statement(query_params={}) filter = ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters) query_params.reverse_merge!( :controller_name => controller_name, :action_name => action_name, :user_id => user_id, :request_hash => @impressionist_hash, :session_hash => session_hash, :ip_address => request.remote_ip, :referrer => request.referer, :params => filter.filter(params_hash) ) end
[ "def", "associative_create_statement", "(", "query_params", "=", "{", "}", ")", "filter", "=", "ActionDispatch", "::", "Http", "::", "ParameterFilter", ".", "new", "(", "Rails", ".", "application", ".", "config", ".", "filter_parameters", ")", "query_params", ".", "reverse_merge!", "(", ":controller_name", "=>", "controller_name", ",", ":action_name", "=>", "action_name", ",", ":user_id", "=>", "user_id", ",", ":request_hash", "=>", "@impressionist_hash", ",", ":session_hash", "=>", "session_hash", ",", ":ip_address", "=>", "request", ".", "remote_ip", ",", ":referrer", "=>", "request", ".", "referer", ",", ":params", "=>", "filter", ".", "filter", "(", "params_hash", ")", ")", "end" ]
creates a statment hash that contains default values for creating an impression via an AR relation.
[ "creates", "a", "statment", "hash", "that", "contains", "default", "values", "for", "creating", "an", "impression", "via", "an", "AR", "relation", "." ]
79c8dc02864e9b998009396d7c80dcbe78bed104
https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/controllers/impressionist_controller.rb#L53-L65
train
charlotte-ruby/impressionist
app/controllers/impressionist_controller.rb
ImpressionistController.InstanceMethods.unique_query
def unique_query(unique_opts,impressionable=nil) full_statement = direct_create_statement({},impressionable) # reduce the full statement to the params we need for the specified unique options unique_opts.reduce({}) do |query, param| query[param] = full_statement[param] query end end
ruby
def unique_query(unique_opts,impressionable=nil) full_statement = direct_create_statement({},impressionable) # reduce the full statement to the params we need for the specified unique options unique_opts.reduce({}) do |query, param| query[param] = full_statement[param] query end end
[ "def", "unique_query", "(", "unique_opts", ",", "impressionable", "=", "nil", ")", "full_statement", "=", "direct_create_statement", "(", "{", "}", ",", "impressionable", ")", "# reduce the full statement to the params we need for the specified unique options", "unique_opts", ".", "reduce", "(", "{", "}", ")", "do", "|", "query", ",", "param", "|", "query", "[", "param", "]", "=", "full_statement", "[", "param", "]", "query", "end", "end" ]
creates the query to check for uniqueness
[ "creates", "the", "query", "to", "check", "for", "uniqueness" ]
79c8dc02864e9b998009396d7c80dcbe78bed104
https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/controllers/impressionist_controller.rb#L117-L124
train
charlotte-ruby/impressionist
app/controllers/impressionist_controller.rb
ImpressionistController.InstanceMethods.direct_create_statement
def direct_create_statement(query_params={},impressionable=nil) query_params.reverse_merge!( :impressionable_type => controller_name.singularize.camelize, :impressionable_id => impressionable.present? ? impressionable.id : params[:id] ) associative_create_statement(query_params) end
ruby
def direct_create_statement(query_params={},impressionable=nil) query_params.reverse_merge!( :impressionable_type => controller_name.singularize.camelize, :impressionable_id => impressionable.present? ? impressionable.id : params[:id] ) associative_create_statement(query_params) end
[ "def", "direct_create_statement", "(", "query_params", "=", "{", "}", ",", "impressionable", "=", "nil", ")", "query_params", ".", "reverse_merge!", "(", ":impressionable_type", "=>", "controller_name", ".", "singularize", ".", "camelize", ",", ":impressionable_id", "=>", "impressionable", ".", "present?", "?", "impressionable", ".", "id", ":", "params", "[", ":id", "]", ")", "associative_create_statement", "(", "query_params", ")", "end" ]
creates a statment hash that contains default values for creating an impression.
[ "creates", "a", "statment", "hash", "that", "contains", "default", "values", "for", "creating", "an", "impression", "." ]
79c8dc02864e9b998009396d7c80dcbe78bed104
https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/controllers/impressionist_controller.rb#L127-L133
train
mgomes/api_auth
lib/api_auth/helpers.rb
ApiAuth.Helpers.capitalize_keys
def capitalize_keys(hsh) capitalized_hash = {} hsh.each_pair { |k, v| capitalized_hash[k.to_s.upcase] = v } capitalized_hash end
ruby
def capitalize_keys(hsh) capitalized_hash = {} hsh.each_pair { |k, v| capitalized_hash[k.to_s.upcase] = v } capitalized_hash end
[ "def", "capitalize_keys", "(", "hsh", ")", "capitalized_hash", "=", "{", "}", "hsh", ".", "each_pair", "{", "|", "k", ",", "v", "|", "capitalized_hash", "[", "k", ".", "to_s", ".", "upcase", "]", "=", "v", "}", "capitalized_hash", "end" ]
Capitalizes the keys of a hash
[ "Capitalizes", "the", "keys", "of", "a", "hash" ]
05270e24a8189958da5b6f2247320540a6c570bc
https://github.com/mgomes/api_auth/blob/05270e24a8189958da5b6f2247320540a6c570bc/lib/api_auth/helpers.rb#L12-L16
train
bigcommerce/gruf
lib/gruf/client.rb
Gruf.Client.execute
def execute(call_sig, req, metadata, opts = {}, &block) operation = nil result = Gruf::Timer.time do opts[:return_op] = true opts[:metadata] = metadata operation = send(call_sig, req, opts, &block) operation.execute end [result, operation] end
ruby
def execute(call_sig, req, metadata, opts = {}, &block) operation = nil result = Gruf::Timer.time do opts[:return_op] = true opts[:metadata] = metadata operation = send(call_sig, req, opts, &block) operation.execute end [result, operation] end
[ "def", "execute", "(", "call_sig", ",", "req", ",", "metadata", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "operation", "=", "nil", "result", "=", "Gruf", "::", "Timer", ".", "time", "do", "opts", "[", ":return_op", "]", "=", "true", "opts", "[", ":metadata", "]", "=", "metadata", "operation", "=", "send", "(", "call_sig", ",", "req", ",", "opts", ",", "block", ")", "operation", ".", "execute", "end", "[", "result", ",", "operation", "]", "end" ]
Execute the given request to the service @param [Symbol] call_sig The call signature being executed @param [Object] req (Optional) The protobuf request message to send @param [Hash] metadata (Optional) A hash of metadata key/values that are transported with the client request @param [Hash] opts (Optional) A hash of options to send to the gRPC request_response method @return [Array<Gruf::Timer::Result, GRPC::ActiveCall::Operation>]
[ "Execute", "the", "given", "request", "to", "the", "service" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/client.rb#L127-L136
train
bigcommerce/gruf
lib/gruf/client.rb
Gruf.Client.request_object
def request_object(request_method, params = {}) desc = rpc_desc(request_method) desc&.input ? desc.input.new(params) : nil end
ruby
def request_object(request_method, params = {}) desc = rpc_desc(request_method) desc&.input ? desc.input.new(params) : nil end
[ "def", "request_object", "(", "request_method", ",", "params", "=", "{", "}", ")", "desc", "=", "rpc_desc", "(", "request_method", ")", "desc", "&.", "input", "?", "desc", ".", "input", ".", "new", "(", "params", ")", ":", "nil", "end" ]
Get the appropriate protobuf request message for the given request method on the service being called @param [Symbol] request_method The method name being called on the remote service @param [Hash] params (Optional) A hash of parameters that will populate the request object @return [Class] The request object that corresponds to the method being called
[ "Get", "the", "appropriate", "protobuf", "request", "message", "for", "the", "given", "request", "method", "on", "the", "service", "being", "called" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/client.rb#L155-L158
train
bigcommerce/gruf
lib/gruf/client.rb
Gruf.Client.build_metadata
def build_metadata(metadata = {}) unless opts[:password].empty? username = opts.fetch(:username, 'grpc').to_s username = username.empty? ? '' : "#{username}:" auth_string = Base64.encode64("#{username}#{opts[:password]}") metadata[:authorization] = "Basic #{auth_string}".tr("\n", '') end metadata end
ruby
def build_metadata(metadata = {}) unless opts[:password].empty? username = opts.fetch(:username, 'grpc').to_s username = username.empty? ? '' : "#{username}:" auth_string = Base64.encode64("#{username}#{opts[:password]}") metadata[:authorization] = "Basic #{auth_string}".tr("\n", '') end metadata end
[ "def", "build_metadata", "(", "metadata", "=", "{", "}", ")", "unless", "opts", "[", ":password", "]", ".", "empty?", "username", "=", "opts", ".", "fetch", "(", ":username", ",", "'grpc'", ")", ".", "to_s", "username", "=", "username", ".", "empty?", "?", "''", ":", "\"#{username}:\"", "auth_string", "=", "Base64", ".", "encode64", "(", "\"#{username}#{opts[:password]}\"", ")", "metadata", "[", ":authorization", "]", "=", "\"Basic #{auth_string}\"", ".", "tr", "(", "\"\\n\"", ",", "''", ")", "end", "metadata", "end" ]
Build a sanitized, authenticated metadata hash for the given request @param [Hash] metadata A base metadata hash to build from @return [Hash] The compiled metadata hash that is ready to be transported over the wire
[ "Build", "a", "sanitized", "authenticated", "metadata", "hash", "for", "the", "given", "request" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/client.rb#L176-L184
train
bigcommerce/gruf
spec/support/helpers.rb
Gruf.Helpers.build_operation
def build_operation(options = {}) double(:operation, { execute: true, metadata: {}, trailing_metadata: {}, deadline: Time.now.to_i + 600, cancelled?: false, execution_time: rand(1_000..10_000) }.merge(options)) end
ruby
def build_operation(options = {}) double(:operation, { execute: true, metadata: {}, trailing_metadata: {}, deadline: Time.now.to_i + 600, cancelled?: false, execution_time: rand(1_000..10_000) }.merge(options)) end
[ "def", "build_operation", "(", "options", "=", "{", "}", ")", "double", "(", ":operation", ",", "{", "execute", ":", "true", ",", "metadata", ":", "{", "}", ",", "trailing_metadata", ":", "{", "}", ",", "deadline", ":", "Time", ".", "now", ".", "to_i", "+", "600", ",", "cancelled?", ":", "false", ",", "execution_time", ":", "rand", "(", "1_000", "..", "10_000", ")", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Build a gRPC operation stub for testing
[ "Build", "a", "gRPC", "operation", "stub", "for", "testing" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/spec/support/helpers.rb#L27-L36
train
bigcommerce/gruf
spec/support/helpers.rb
Gruf.Helpers.run_server
def run_server(server) grpc_server = server.server t = Thread.new { grpc_server.run } grpc_server.wait_till_running begin yield ensure grpc_server.stop sleep(0.1) until grpc_server.stopped? t.join end end
ruby
def run_server(server) grpc_server = server.server t = Thread.new { grpc_server.run } grpc_server.wait_till_running begin yield ensure grpc_server.stop sleep(0.1) until grpc_server.stopped? t.join end end
[ "def", "run_server", "(", "server", ")", "grpc_server", "=", "server", ".", "server", "t", "=", "Thread", ".", "new", "{", "grpc_server", ".", "run", "}", "grpc_server", ".", "wait_till_running", "begin", "yield", "ensure", "grpc_server", ".", "stop", "sleep", "(", "0.1", ")", "until", "grpc_server", ".", "stopped?", "t", ".", "join", "end", "end" ]
Runs a server @param [Gruf::Server] server
[ "Runs", "a", "server" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/spec/support/helpers.rb#L65-L78
train
bigcommerce/gruf
lib/gruf/error.rb
Gruf.Error.add_field_error
def add_field_error(field_name, error_code, message = '') @field_errors << Errors::Field.new(field_name, error_code, message) end
ruby
def add_field_error(field_name, error_code, message = '') @field_errors << Errors::Field.new(field_name, error_code, message) end
[ "def", "add_field_error", "(", "field_name", ",", "error_code", ",", "message", "=", "''", ")", "@field_errors", "<<", "Errors", "::", "Field", ".", "new", "(", "field_name", ",", "error_code", ",", "message", ")", "end" ]
Initialize the error, setting default values @param [Hash] args (Optional) An optional hash of arguments that will set fields on the error object Add a field error to this error package @param [Symbol] field_name The field name for the error @param [Symbol] error_code The application error code for the error; e.g. :job_not_found @param [String] message The application error message for the error; e.g. "Job not found with ID 123"
[ "Initialize", "the", "error", "setting", "default", "values" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L98-L100
train
bigcommerce/gruf
lib/gruf/error.rb
Gruf.Error.attach_to_call
def attach_to_call(active_call) metadata[Gruf.error_metadata_key.to_sym] = serialize if Gruf.append_server_errors_to_trailing_metadata return self if metadata.empty? || !active_call || !active_call.respond_to?(:output_metadata) # Check if we've overflown the maximum size of output metadata. If so, # log a warning and replace the metadata with something smaller to avoid # resource exhausted errors. if metadata.inspect.size > MAX_METADATA_SIZE code = METADATA_SIZE_EXCEEDED_CODE msg = METADATA_SIZE_EXCEEDED_MSG logger.warn "#{code}: #{msg} Original error: #{to_h.inspect}" err = Gruf::Error.new(code: :internal, app_code: code, message: msg) return err.attach_to_call(active_call) end active_call.output_metadata.update(metadata) self end
ruby
def attach_to_call(active_call) metadata[Gruf.error_metadata_key.to_sym] = serialize if Gruf.append_server_errors_to_trailing_metadata return self if metadata.empty? || !active_call || !active_call.respond_to?(:output_metadata) # Check if we've overflown the maximum size of output metadata. If so, # log a warning and replace the metadata with something smaller to avoid # resource exhausted errors. if metadata.inspect.size > MAX_METADATA_SIZE code = METADATA_SIZE_EXCEEDED_CODE msg = METADATA_SIZE_EXCEEDED_MSG logger.warn "#{code}: #{msg} Original error: #{to_h.inspect}" err = Gruf::Error.new(code: :internal, app_code: code, message: msg) return err.attach_to_call(active_call) end active_call.output_metadata.update(metadata) self end
[ "def", "attach_to_call", "(", "active_call", ")", "metadata", "[", "Gruf", ".", "error_metadata_key", ".", "to_sym", "]", "=", "serialize", "if", "Gruf", ".", "append_server_errors_to_trailing_metadata", "return", "self", "if", "metadata", ".", "empty?", "||", "!", "active_call", "||", "!", "active_call", ".", "respond_to?", "(", ":output_metadata", ")", "# Check if we've overflown the maximum size of output metadata. If so,", "# log a warning and replace the metadata with something smaller to avoid", "# resource exhausted errors.", "if", "metadata", ".", "inspect", ".", "size", ">", "MAX_METADATA_SIZE", "code", "=", "METADATA_SIZE_EXCEEDED_CODE", "msg", "=", "METADATA_SIZE_EXCEEDED_MSG", "logger", ".", "warn", "\"#{code}: #{msg} Original error: #{to_h.inspect}\"", "err", "=", "Gruf", "::", "Error", ".", "new", "(", "code", ":", ":internal", ",", "app_code", ":", "code", ",", "message", ":", "msg", ")", "return", "err", ".", "attach_to_call", "(", "active_call", ")", "end", "active_call", ".", "output_metadata", ".", "update", "(", "metadata", ")", "self", "end" ]
Update the trailing metadata on the given gRPC call, including the error payload if configured to do so. @param [GRPC::ActiveCall] active_call The marshalled gRPC call @return [Error] Return the error itself after updating metadata on the given gRPC call. In the case of a metadata overflow error, we replace the current error with a new one that won't cause a low-level http2 error.
[ "Update", "the", "trailing", "metadata", "on", "the", "given", "gRPC", "call", "including", "the", "error", "payload", "if", "configured", "to", "do", "so", "." ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L151-L168
train
bigcommerce/gruf
lib/gruf/error.rb
Gruf.Error.to_h
def to_h { code: code, app_code: app_code, message: message, field_errors: field_errors.map(&:to_h), debug_info: debug_info.to_h } end
ruby
def to_h { code: code, app_code: app_code, message: message, field_errors: field_errors.map(&:to_h), debug_info: debug_info.to_h } end
[ "def", "to_h", "{", "code", ":", "code", ",", "app_code", ":", "app_code", ",", "message", ":", "message", ",", "field_errors", ":", "field_errors", ".", "map", "(", ":to_h", ")", ",", "debug_info", ":", "debug_info", ".", "to_h", "}", "end" ]
Return the error represented in Hash form @return [Hash] The error as a hash
[ "Return", "the", "error", "represented", "in", "Hash", "form" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L186-L194
train
bigcommerce/gruf
lib/gruf/error.rb
Gruf.Error.serializer_class
def serializer_class if Gruf.error_serializer Gruf.error_serializer.is_a?(Class) ? Gruf.error_serializer : Gruf.error_serializer.to_s.constantize else Gruf::Serializers::Errors::Json end end
ruby
def serializer_class if Gruf.error_serializer Gruf.error_serializer.is_a?(Class) ? Gruf.error_serializer : Gruf.error_serializer.to_s.constantize else Gruf::Serializers::Errors::Json end end
[ "def", "serializer_class", "if", "Gruf", ".", "error_serializer", "Gruf", ".", "error_serializer", ".", "is_a?", "(", "Class", ")", "?", "Gruf", ".", "error_serializer", ":", "Gruf", ".", "error_serializer", ".", "to_s", ".", "constantize", "else", "Gruf", "::", "Serializers", "::", "Errors", "::", "Json", "end", "end" ]
Return the error serializer being used for gruf @return [Gruf::Serializers::Errors::Base]
[ "Return", "the", "error", "serializer", "being", "used", "for", "gruf" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L213-L219
train
bigcommerce/gruf
lib/gruf/server.rb
Gruf.Server.server
def server @server_mu.synchronize do @server ||= begin # For backward compatibility, we allow these options to be passed directly # in the Gruf::Server options, or via Gruf.rpc_server_options. server_options = { pool_size: options.fetch(:pool_size, Gruf.rpc_server_options[:pool_size]), max_waiting_requests: options.fetch(:max_waiting_requests, Gruf.rpc_server_options[:max_waiting_requests]), poll_period: options.fetch(:poll_period, Gruf.rpc_server_options[:poll_period]), pool_keep_alive: options.fetch(:pool_keep_alive, Gruf.rpc_server_options[:pool_keep_alive]), connect_md_proc: options.fetch(:connect_md_proc, Gruf.rpc_server_options[:connect_md_proc]), server_args: options.fetch(:server_args, Gruf.rpc_server_options[:server_args]) } server = if @event_listener_proc server_options[:event_listener_proc] = @event_listener_proc Gruf::InstrumentableGrpcServer.new(server_options) else GRPC::RpcServer.new(server_options) end @port = server.add_http2_port(@hostname, ssl_credentials) @services.each { |s| server.handle(s) } server end end end
ruby
def server @server_mu.synchronize do @server ||= begin # For backward compatibility, we allow these options to be passed directly # in the Gruf::Server options, or via Gruf.rpc_server_options. server_options = { pool_size: options.fetch(:pool_size, Gruf.rpc_server_options[:pool_size]), max_waiting_requests: options.fetch(:max_waiting_requests, Gruf.rpc_server_options[:max_waiting_requests]), poll_period: options.fetch(:poll_period, Gruf.rpc_server_options[:poll_period]), pool_keep_alive: options.fetch(:pool_keep_alive, Gruf.rpc_server_options[:pool_keep_alive]), connect_md_proc: options.fetch(:connect_md_proc, Gruf.rpc_server_options[:connect_md_proc]), server_args: options.fetch(:server_args, Gruf.rpc_server_options[:server_args]) } server = if @event_listener_proc server_options[:event_listener_proc] = @event_listener_proc Gruf::InstrumentableGrpcServer.new(server_options) else GRPC::RpcServer.new(server_options) end @port = server.add_http2_port(@hostname, ssl_credentials) @services.each { |s| server.handle(s) } server end end end
[ "def", "server", "@server_mu", ".", "synchronize", "do", "@server", "||=", "begin", "# For backward compatibility, we allow these options to be passed directly", "# in the Gruf::Server options, or via Gruf.rpc_server_options.", "server_options", "=", "{", "pool_size", ":", "options", ".", "fetch", "(", ":pool_size", ",", "Gruf", ".", "rpc_server_options", "[", ":pool_size", "]", ")", ",", "max_waiting_requests", ":", "options", ".", "fetch", "(", ":max_waiting_requests", ",", "Gruf", ".", "rpc_server_options", "[", ":max_waiting_requests", "]", ")", ",", "poll_period", ":", "options", ".", "fetch", "(", ":poll_period", ",", "Gruf", ".", "rpc_server_options", "[", ":poll_period", "]", ")", ",", "pool_keep_alive", ":", "options", ".", "fetch", "(", ":pool_keep_alive", ",", "Gruf", ".", "rpc_server_options", "[", ":pool_keep_alive", "]", ")", ",", "connect_md_proc", ":", "options", ".", "fetch", "(", ":connect_md_proc", ",", "Gruf", ".", "rpc_server_options", "[", ":connect_md_proc", "]", ")", ",", "server_args", ":", "options", ".", "fetch", "(", ":server_args", ",", "Gruf", ".", "rpc_server_options", "[", ":server_args", "]", ")", "}", "server", "=", "if", "@event_listener_proc", "server_options", "[", ":event_listener_proc", "]", "=", "@event_listener_proc", "Gruf", "::", "InstrumentableGrpcServer", ".", "new", "(", "server_options", ")", "else", "GRPC", "::", "RpcServer", ".", "new", "(", "server_options", ")", "end", "@port", "=", "server", ".", "add_http2_port", "(", "@hostname", ",", "ssl_credentials", ")", "@services", ".", "each", "{", "|", "s", "|", "server", ".", "handle", "(", "s", ")", "}", "server", "end", "end", "end" ]
Initialize the server and load and setup the services @param [Hash] opts @return [GRPC::RpcServer] The GRPC server running
[ "Initialize", "the", "server", "and", "load", "and", "setup", "the", "services" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L56-L82
train
bigcommerce/gruf
lib/gruf/server.rb
Gruf.Server.start!
def start! update_proc_title(:starting) server_thread = Thread.new do logger.info { "Starting gruf server at #{@hostname}..." } server.run end stop_server_thread = Thread.new do loop do break if @stop_server @stop_server_mu.synchronize { @stop_server_cv.wait(@stop_server_mu, 10) } end logger.info { 'Shutting down...' } server.stop end server.wait_till_running @started = true update_proc_title(:serving) stop_server_thread.join server_thread.join @started = false update_proc_title(:stopped) logger.info { 'Goodbye!' } end
ruby
def start! update_proc_title(:starting) server_thread = Thread.new do logger.info { "Starting gruf server at #{@hostname}..." } server.run end stop_server_thread = Thread.new do loop do break if @stop_server @stop_server_mu.synchronize { @stop_server_cv.wait(@stop_server_mu, 10) } end logger.info { 'Shutting down...' } server.stop end server.wait_till_running @started = true update_proc_title(:serving) stop_server_thread.join server_thread.join @started = false update_proc_title(:stopped) logger.info { 'Goodbye!' } end
[ "def", "start!", "update_proc_title", "(", ":starting", ")", "server_thread", "=", "Thread", ".", "new", "do", "logger", ".", "info", "{", "\"Starting gruf server at #{@hostname}...\"", "}", "server", ".", "run", "end", "stop_server_thread", "=", "Thread", ".", "new", "do", "loop", "do", "break", "if", "@stop_server", "@stop_server_mu", ".", "synchronize", "{", "@stop_server_cv", ".", "wait", "(", "@stop_server_mu", ",", "10", ")", "}", "end", "logger", ".", "info", "{", "'Shutting down...'", "}", "server", ".", "stop", "end", "server", ".", "wait_till_running", "@started", "=", "true", "update_proc_title", "(", ":serving", ")", "stop_server_thread", ".", "join", "server_thread", ".", "join", "@started", "=", "false", "update_proc_title", "(", ":stopped", ")", "logger", ".", "info", "{", "'Goodbye!'", "}", "end" ]
Start the gRPC server :nocov:
[ "Start", "the", "gRPC", "server" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L88-L115
train
bigcommerce/gruf
lib/gruf/server.rb
Gruf.Server.insert_interceptor_before
def insert_interceptor_before(before_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_before(before_class, interceptor_class, opts) end
ruby
def insert_interceptor_before(before_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_before(before_class, interceptor_class, opts) end
[ "def", "insert_interceptor_before", "(", "before_class", ",", "interceptor_class", ",", "opts", "=", "{", "}", ")", "raise", "ServerAlreadyStartedError", "if", "@started", "@interceptors", ".", "insert_before", "(", "before_class", ",", "interceptor_class", ",", "opts", ")", "end" ]
Insert an interceptor before another in the currently registered order of execution @param [Class] before_class The interceptor that you want to add the new interceptor before @param [Class] interceptor_class The Interceptor to add to the registry @param [Hash] opts A hash of options for the interceptor
[ "Insert", "an", "interceptor", "before", "another", "in", "the", "currently", "registered", "order", "of", "execution" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L150-L154
train
bigcommerce/gruf
lib/gruf/server.rb
Gruf.Server.insert_interceptor_after
def insert_interceptor_after(after_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_after(after_class, interceptor_class, opts) end
ruby
def insert_interceptor_after(after_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_after(after_class, interceptor_class, opts) end
[ "def", "insert_interceptor_after", "(", "after_class", ",", "interceptor_class", ",", "opts", "=", "{", "}", ")", "raise", "ServerAlreadyStartedError", "if", "@started", "@interceptors", ".", "insert_after", "(", "after_class", ",", "interceptor_class", ",", "opts", ")", "end" ]
Insert an interceptor after another in the currently registered order of execution @param [Class] after_class The interceptor that you want to add the new interceptor after @param [Class] interceptor_class The Interceptor to add to the registry @param [Hash] opts A hash of options for the interceptor
[ "Insert", "an", "interceptor", "after", "another", "in", "the", "currently", "registered", "order", "of", "execution" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L163-L167
train
bigcommerce/gruf
lib/gruf/configuration.rb
Gruf.Configuration.options
def options opts = {} VALID_CONFIG_KEYS.each_key do |k| opts.merge!(k => send(k)) end opts end
ruby
def options opts = {} VALID_CONFIG_KEYS.each_key do |k| opts.merge!(k => send(k)) end opts end
[ "def", "options", "opts", "=", "{", "}", "VALID_CONFIG_KEYS", ".", "each_key", "do", "|", "k", "|", "opts", ".", "merge!", "(", "k", "=>", "send", "(", "k", ")", ")", "end", "opts", "end" ]
Return the current configuration options as a Hash @return [Hash] The configuration for gruf, represented as a Hash
[ "Return", "the", "current", "configuration", "options", "as", "a", "Hash" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/configuration.rb#L84-L90
train
bigcommerce/gruf
lib/gruf/configuration.rb
Gruf.Configuration.reset
def reset VALID_CONFIG_KEYS.each do |k, v| send((k.to_s + '='), v) end self.interceptors = Gruf::Interceptors::Registry.new self.root_path = Rails.root.to_s.chomp('/') if defined?(Rails) if defined?(Rails) && Rails.logger self.logger = Rails.logger else require 'logger' self.logger = ::Logger.new(STDOUT) end self.grpc_logger = logger if grpc_logger.nil? self.ssl_crt_file = "#{root_path}config/ssl/#{environment}.crt" self.ssl_key_file = "#{root_path}config/ssl/#{environment}.key" self.controllers_path = root_path.to_s.empty? ? 'app/rpc' : "#{root_path}/app/rpc" if use_default_interceptors interceptors.use(Gruf::Interceptors::ActiveRecord::ConnectionReset) interceptors.use(Gruf::Interceptors::Instrumentation::OutputMetadataTimer) end options end
ruby
def reset VALID_CONFIG_KEYS.each do |k, v| send((k.to_s + '='), v) end self.interceptors = Gruf::Interceptors::Registry.new self.root_path = Rails.root.to_s.chomp('/') if defined?(Rails) if defined?(Rails) && Rails.logger self.logger = Rails.logger else require 'logger' self.logger = ::Logger.new(STDOUT) end self.grpc_logger = logger if grpc_logger.nil? self.ssl_crt_file = "#{root_path}config/ssl/#{environment}.crt" self.ssl_key_file = "#{root_path}config/ssl/#{environment}.key" self.controllers_path = root_path.to_s.empty? ? 'app/rpc' : "#{root_path}/app/rpc" if use_default_interceptors interceptors.use(Gruf::Interceptors::ActiveRecord::ConnectionReset) interceptors.use(Gruf::Interceptors::Instrumentation::OutputMetadataTimer) end options end
[ "def", "reset", "VALID_CONFIG_KEYS", ".", "each", "do", "|", "k", ",", "v", "|", "send", "(", "(", "k", ".", "to_s", "+", "'='", ")", ",", "v", ")", "end", "self", ".", "interceptors", "=", "Gruf", "::", "Interceptors", "::", "Registry", ".", "new", "self", ".", "root_path", "=", "Rails", ".", "root", ".", "to_s", ".", "chomp", "(", "'/'", ")", "if", "defined?", "(", "Rails", ")", "if", "defined?", "(", "Rails", ")", "&&", "Rails", ".", "logger", "self", ".", "logger", "=", "Rails", ".", "logger", "else", "require", "'logger'", "self", ".", "logger", "=", "::", "Logger", ".", "new", "(", "STDOUT", ")", "end", "self", ".", "grpc_logger", "=", "logger", "if", "grpc_logger", ".", "nil?", "self", ".", "ssl_crt_file", "=", "\"#{root_path}config/ssl/#{environment}.crt\"", "self", ".", "ssl_key_file", "=", "\"#{root_path}config/ssl/#{environment}.key\"", "self", ".", "controllers_path", "=", "root_path", ".", "to_s", ".", "empty?", "?", "'app/rpc'", ":", "\"#{root_path}/app/rpc\"", "if", "use_default_interceptors", "interceptors", ".", "use", "(", "Gruf", "::", "Interceptors", "::", "ActiveRecord", "::", "ConnectionReset", ")", "interceptors", ".", "use", "(", "Gruf", "::", "Interceptors", "::", "Instrumentation", "::", "OutputMetadataTimer", ")", "end", "options", "end" ]
Set the default configuration onto the extended class @return [Hash] options The reset options hash
[ "Set", "the", "default", "configuration", "onto", "the", "extended", "class" ]
9e438b174df81845c8100302da671721d5a112c5
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/configuration.rb#L97-L118
train
gonzalo-bulnes/simple_token_authentication
lib/simple_token_authentication/exception_fallback_handler.rb
SimpleTokenAuthentication.ExceptionFallbackHandler.fallback!
def fallback!(controller, entity) throw(:warden, scope: entity.name_underscore.to_sym) if controller.send("current_#{entity.name_underscore}").nil? end
ruby
def fallback!(controller, entity) throw(:warden, scope: entity.name_underscore.to_sym) if controller.send("current_#{entity.name_underscore}").nil? end
[ "def", "fallback!", "(", "controller", ",", "entity", ")", "throw", "(", ":warden", ",", "scope", ":", "entity", ".", "name_underscore", ".", "to_sym", ")", "if", "controller", ".", "send", "(", "\"current_#{entity.name_underscore}\"", ")", ".", "nil?", "end" ]
Notifies the failure of authentication to Warden in the same Devise does. Does result in an HTTP 401 response in a Devise context.
[ "Notifies", "the", "failure", "of", "authentication", "to", "Warden", "in", "the", "same", "Devise", "does", ".", "Does", "result", "in", "an", "HTTP", "401", "response", "in", "a", "Devise", "context", "." ]
2ea7d13e155bf7d7da22a69e3e884e94d05a8dae
https://github.com/gonzalo-bulnes/simple_token_authentication/blob/2ea7d13e155bf7d7da22a69e3e884e94d05a8dae/lib/simple_token_authentication/exception_fallback_handler.rb#L7-L9
train
inspec/train
lib/train/transports/ssh.rb
Train::Transports.SSH.verify_host_key_option
def verify_host_key_option current_net_ssh = Net::SSH::Version::CURRENT new_option_version = Net::SSH::Version[4, 2, 0] current_net_ssh >= new_option_version ? :verify_host_key : :paranoid end
ruby
def verify_host_key_option current_net_ssh = Net::SSH::Version::CURRENT new_option_version = Net::SSH::Version[4, 2, 0] current_net_ssh >= new_option_version ? :verify_host_key : :paranoid end
[ "def", "verify_host_key_option", "current_net_ssh", "=", "Net", "::", "SSH", "::", "Version", "::", "CURRENT", "new_option_version", "=", "Net", "::", "SSH", "::", "Version", "[", "4", ",", "2", ",", "0", "]", "current_net_ssh", ">=", "new_option_version", "?", ":verify_host_key", ":", ":paranoid", "end" ]
Returns the correct host-key-verification option key to use depending on what version of net-ssh is in use. In net-ssh <= 4.1, the supported parameter is `paranoid` but in 4.2, it became `verify_host_key` `verify_host_key` does not work in <= 4.1, and `paranoid` throws deprecation warnings in >= 4.2. While the "right thing" to do would be to pin train's dependency on net-ssh to ~> 4.2, this will prevent InSpec from being used in Chef v12 because of it pinning to a v3 of net-ssh.
[ "Returns", "the", "correct", "host", "-", "key", "-", "verification", "option", "key", "to", "use", "depending", "on", "what", "version", "of", "net", "-", "ssh", "is", "in", "use", ".", "In", "net", "-", "ssh", "<", "=", "4", ".", "1", "the", "supported", "parameter", "is", "paranoid", "but", "in", "4", ".", "2", "it", "became", "verify_host_key" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/transports/ssh.rb#L189-L194
train
inspec/train
lib/train/transports/ssh.rb
Train::Transports.SSH.create_new_connection
def create_new_connection(options, &block) if defined?(@connection) logger.debug("[SSH] shutting previous connection #{@connection}") @connection.close end @connection_options = options conn = Connection.new(options, &block) # Cisco IOS requires a special implementation of `Net:SSH`. This uses the # SSH transport to identify the platform, but then replaces SSHConnection # with a CiscoIOSConnection in order to behave as expected for the user. if defined?(conn.platform.cisco_ios?) && conn.platform.cisco_ios? ios_options = {} ios_options[:host] = @options[:host] ios_options[:user] = @options[:user] # The enable password is used to elevate privileges on Cisco devices # We will also support the sudo password field for the same purpose # for the interim. # TODO ios_options[:enable_password] = @options[:enable_password] || @options[:sudo_password] ios_options[:logger] = @options[:logger] ios_options.merge!(@connection_options) conn = CiscoIOSConnection.new(ios_options) end @connection = conn unless conn.nil? end
ruby
def create_new_connection(options, &block) if defined?(@connection) logger.debug("[SSH] shutting previous connection #{@connection}") @connection.close end @connection_options = options conn = Connection.new(options, &block) # Cisco IOS requires a special implementation of `Net:SSH`. This uses the # SSH transport to identify the platform, but then replaces SSHConnection # with a CiscoIOSConnection in order to behave as expected for the user. if defined?(conn.platform.cisco_ios?) && conn.platform.cisco_ios? ios_options = {} ios_options[:host] = @options[:host] ios_options[:user] = @options[:user] # The enable password is used to elevate privileges on Cisco devices # We will also support the sudo password field for the same purpose # for the interim. # TODO ios_options[:enable_password] = @options[:enable_password] || @options[:sudo_password] ios_options[:logger] = @options[:logger] ios_options.merge!(@connection_options) conn = CiscoIOSConnection.new(ios_options) end @connection = conn unless conn.nil? end
[ "def", "create_new_connection", "(", "options", ",", "&", "block", ")", "if", "defined?", "(", "@connection", ")", "logger", ".", "debug", "(", "\"[SSH] shutting previous connection #{@connection}\"", ")", "@connection", ".", "close", "end", "@connection_options", "=", "options", "conn", "=", "Connection", ".", "new", "(", "options", ",", "block", ")", "# Cisco IOS requires a special implementation of `Net:SSH`. This uses the", "# SSH transport to identify the platform, but then replaces SSHConnection", "# with a CiscoIOSConnection in order to behave as expected for the user.", "if", "defined?", "(", "conn", ".", "platform", ".", "cisco_ios?", ")", "&&", "conn", ".", "platform", ".", "cisco_ios?", "ios_options", "=", "{", "}", "ios_options", "[", ":host", "]", "=", "@options", "[", ":host", "]", "ios_options", "[", ":user", "]", "=", "@options", "[", ":user", "]", "# The enable password is used to elevate privileges on Cisco devices", "# We will also support the sudo password field for the same purpose", "# for the interim. # TODO", "ios_options", "[", ":enable_password", "]", "=", "@options", "[", ":enable_password", "]", "||", "@options", "[", ":sudo_password", "]", "ios_options", "[", ":logger", "]", "=", "@options", "[", ":logger", "]", "ios_options", ".", "merge!", "(", "@connection_options", ")", "conn", "=", "CiscoIOSConnection", ".", "new", "(", "ios_options", ")", "end", "@connection", "=", "conn", "unless", "conn", ".", "nil?", "end" ]
Creates a new SSH Connection instance and save it for potential future reuse. @param options [Hash] conneciton options @return [Ssh::Connection] an SSH Connection instance @api private
[ "Creates", "a", "new", "SSH", "Connection", "instance", "and", "save", "it", "for", "potential", "future", "reuse", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/transports/ssh.rb#L231-L257
train
inspec/train
lib/train/file.rb
Train.File.perform_checksum_ruby
def perform_checksum_ruby(method) # This is used to skip attempting other checksum methods. If this is set # then we know all other methods have failed. @ruby_checksum_fallback = true case method when :md5 res = Digest::MD5.new when :sha256 res = Digest::SHA256.new end res.update(content) res.hexdigest rescue TypeError => _ nil end
ruby
def perform_checksum_ruby(method) # This is used to skip attempting other checksum methods. If this is set # then we know all other methods have failed. @ruby_checksum_fallback = true case method when :md5 res = Digest::MD5.new when :sha256 res = Digest::SHA256.new end res.update(content) res.hexdigest rescue TypeError => _ nil end
[ "def", "perform_checksum_ruby", "(", "method", ")", "# This is used to skip attempting other checksum methods. If this is set", "# then we know all other methods have failed.", "@ruby_checksum_fallback", "=", "true", "case", "method", "when", ":md5", "res", "=", "Digest", "::", "MD5", ".", "new", "when", ":sha256", "res", "=", "Digest", "::", "SHA256", ".", "new", "end", "res", ".", "update", "(", "content", ")", "res", ".", "hexdigest", "rescue", "TypeError", "=>", "_", "nil", "end" ]
This pulls the content of the file to the machine running Train and uses Digest to perform the checksum. This is less efficient than using remote system binaries and can lead to incorrect results due to encoding.
[ "This", "pulls", "the", "content", "of", "the", "file", "to", "the", "machine", "running", "Train", "and", "uses", "Digest", "to", "perform", "the", "checksum", ".", "This", "is", "less", "efficient", "than", "using", "remote", "system", "binaries", "and", "can", "lead", "to", "incorrect", "results", "due", "to", "encoding", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/file.rb#L193-L208
train
inspec/train
lib/train/transports/winrm.rb
Train::Transports.WinRM.create_new_connection
def create_new_connection(options, &block) if @connection logger.debug("[WinRM] shutting previous connection #{@connection}") @connection.close end @connection_options = options @connection = Connection.new(options, &block) end
ruby
def create_new_connection(options, &block) if @connection logger.debug("[WinRM] shutting previous connection #{@connection}") @connection.close end @connection_options = options @connection = Connection.new(options, &block) end
[ "def", "create_new_connection", "(", "options", ",", "&", "block", ")", "if", "@connection", "logger", ".", "debug", "(", "\"[WinRM] shutting previous connection #{@connection}\"", ")", "@connection", ".", "close", "end", "@connection_options", "=", "options", "@connection", "=", "Connection", ".", "new", "(", "options", ",", "block", ")", "end" ]
Creates a new WinRM Connection instance and save it for potential future reuse. @param options [Hash] conneciton options @return [WinRM::Connection] a WinRM Connection instance @api private
[ "Creates", "a", "new", "WinRM", "Connection", "instance", "and", "save", "it", "for", "potential", "future", "reuse", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/transports/winrm.rb#L146-L154
train
inspec/train
lib/train/platforms/common.rb
Train::Platforms.Common.in_family
def in_family(family) if self.class == Train::Platforms::Family && @name == family fail "Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'" end # add family to the family list family = Train::Platforms.family(family) family.children[self] = @condition @families[family] = @condition @condition = nil self end
ruby
def in_family(family) if self.class == Train::Platforms::Family && @name == family fail "Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'" end # add family to the family list family = Train::Platforms.family(family) family.children[self] = @condition @families[family] = @condition @condition = nil self end
[ "def", "in_family", "(", "family", ")", "if", "self", ".", "class", "==", "Train", "::", "Platforms", "::", "Family", "&&", "@name", "==", "family", "fail", "\"Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'\"", "end", "# add family to the family list", "family", "=", "Train", "::", "Platforms", ".", "family", "(", "family", ")", "family", ".", "children", "[", "self", "]", "=", "@condition", "@families", "[", "family", "]", "=", "@condition", "@condition", "=", "nil", "self", "end" ]
Add a family connection. This will create a family if it does not exist and add a child relationship.
[ "Add", "a", "family", "connection", ".", "This", "will", "create", "a", "family", "if", "it", "does", "not", "exist", "and", "add", "a", "child", "relationship", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/common.rb#L7-L19
train
inspec/train
lib/train/extras/command_wrapper.rb
Train::Extras.LinuxCommand.sudo_wrap
def sudo_wrap(cmd) return cmd unless @sudo return cmd if @user == 'root' res = (@sudo_command || 'sudo') + ' ' res = "#{safe_string(@sudo_password + "\n")} | #{res}-S " unless @sudo_password.nil? res << @sudo_options.to_s + ' ' unless @sudo_options.nil? res + cmd end
ruby
def sudo_wrap(cmd) return cmd unless @sudo return cmd if @user == 'root' res = (@sudo_command || 'sudo') + ' ' res = "#{safe_string(@sudo_password + "\n")} | #{res}-S " unless @sudo_password.nil? res << @sudo_options.to_s + ' ' unless @sudo_options.nil? res + cmd end
[ "def", "sudo_wrap", "(", "cmd", ")", "return", "cmd", "unless", "@sudo", "return", "cmd", "if", "@user", "==", "'root'", "res", "=", "(", "@sudo_command", "||", "'sudo'", ")", "+", "' '", "res", "=", "\"#{safe_string(@sudo_password + \"\\n\")} | #{res}-S \"", "unless", "@sudo_password", ".", "nil?", "res", "<<", "@sudo_options", ".", "to_s", "+", "' '", "unless", "@sudo_options", ".", "nil?", "res", "+", "cmd", "end" ]
wrap the cmd in a sudo command
[ "wrap", "the", "cmd", "in", "a", "sudo", "command" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/extras/command_wrapper.rb#L92-L103
train
inspec/train
lib/train/extras/command_wrapper.rb
Train::Extras.WindowsCommand.powershell_wrap
def powershell_wrap(cmd) shell = @shell_command || 'powershell' # Prevent progress stream from leaking into stderr script = "$ProgressPreference='SilentlyContinue';" + cmd # Encode script so PowerShell can use it script = script.encode('UTF-16LE', 'UTF-8') base64_script = Base64.strict_encode64(script) cmd = "#{shell} -NoProfile -EncodedCommand #{base64_script}" cmd end
ruby
def powershell_wrap(cmd) shell = @shell_command || 'powershell' # Prevent progress stream from leaking into stderr script = "$ProgressPreference='SilentlyContinue';" + cmd # Encode script so PowerShell can use it script = script.encode('UTF-16LE', 'UTF-8') base64_script = Base64.strict_encode64(script) cmd = "#{shell} -NoProfile -EncodedCommand #{base64_script}" cmd end
[ "def", "powershell_wrap", "(", "cmd", ")", "shell", "=", "@shell_command", "||", "'powershell'", "# Prevent progress stream from leaking into stderr", "script", "=", "\"$ProgressPreference='SilentlyContinue';\"", "+", "cmd", "# Encode script so PowerShell can use it", "script", "=", "script", ".", "encode", "(", "'UTF-16LE'", ",", "'UTF-8'", ")", "base64_script", "=", "Base64", ".", "strict_encode64", "(", "script", ")", "cmd", "=", "\"#{shell} -NoProfile -EncodedCommand #{base64_script}\"", "cmd", "end" ]
Wrap the cmd in an encoded command to allow pipes and quotes
[ "Wrap", "the", "cmd", "in", "an", "encoded", "command", "to", "allow", "pipes", "and", "quotes" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/extras/command_wrapper.rb#L145-L157
train
inspec/train
lib/train/platforms/detect/scanner.rb
Train::Platforms::Detect.Scanner.scan
def scan # start with the platform/families who have no families (the top levels) top = Train::Platforms.top_platforms top.each do |_name, plat| # we are doing a instance_eval here to make sure we have the proper # context with all the detect helper methods next unless instance_eval(&plat.detect) == true # if we have a match start looking at the children plat_result = scan_children(plat) next if plat_result.nil? # return platform to backend @family_hierarchy << plat.name return get_platform(plat_result) end fail Train::PlatformDetectionFailed, 'Sorry, we are unable to detect your platform' end
ruby
def scan # start with the platform/families who have no families (the top levels) top = Train::Platforms.top_platforms top.each do |_name, plat| # we are doing a instance_eval here to make sure we have the proper # context with all the detect helper methods next unless instance_eval(&plat.detect) == true # if we have a match start looking at the children plat_result = scan_children(plat) next if plat_result.nil? # return platform to backend @family_hierarchy << plat.name return get_platform(plat_result) end fail Train::PlatformDetectionFailed, 'Sorry, we are unable to detect your platform' end
[ "def", "scan", "# start with the platform/families who have no families (the top levels)", "top", "=", "Train", "::", "Platforms", ".", "top_platforms", "top", ".", "each", "do", "|", "_name", ",", "plat", "|", "# we are doing a instance_eval here to make sure we have the proper", "# context with all the detect helper methods", "next", "unless", "instance_eval", "(", "plat", ".", "detect", ")", "==", "true", "# if we have a match start looking at the children", "plat_result", "=", "scan_children", "(", "plat", ")", "next", "if", "plat_result", ".", "nil?", "# return platform to backend", "@family_hierarchy", "<<", "plat", ".", "name", "return", "get_platform", "(", "plat_result", ")", "end", "fail", "Train", "::", "PlatformDetectionFailed", ",", "'Sorry, we are unable to detect your platform'", "end" ]
Main detect method to scan all platforms for a match @return Train::Platform instance or error if none found
[ "Main", "detect", "method", "to", "scan", "all", "platforms", "for", "a", "match" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/scanner.rb#L24-L42
train
inspec/train
lib/train/platforms/platform.rb
Train::Platforms.Platform.add_platform_methods
def add_platform_methods # Redo clean name if there is a detect override clean_name(force: true) unless @platform[:name].nil? # Add in family methods family_list = Train::Platforms.families family_list.each_value do |k| next if respond_to?(k.name + '?') define_singleton_method(k.name + '?') do family_hierarchy.include?(k.name) end end # Helper methods for direct platform info @platform.each_key do |m| next if respond_to?(m) define_singleton_method(m) do @platform[m] end end # Create method for name if its not already true m = name + '?' return if respond_to?(m) define_singleton_method(m) do true end end
ruby
def add_platform_methods # Redo clean name if there is a detect override clean_name(force: true) unless @platform[:name].nil? # Add in family methods family_list = Train::Platforms.families family_list.each_value do |k| next if respond_to?(k.name + '?') define_singleton_method(k.name + '?') do family_hierarchy.include?(k.name) end end # Helper methods for direct platform info @platform.each_key do |m| next if respond_to?(m) define_singleton_method(m) do @platform[m] end end # Create method for name if its not already true m = name + '?' return if respond_to?(m) define_singleton_method(m) do true end end
[ "def", "add_platform_methods", "# Redo clean name if there is a detect override", "clean_name", "(", "force", ":", "true", ")", "unless", "@platform", "[", ":name", "]", ".", "nil?", "# Add in family methods", "family_list", "=", "Train", "::", "Platforms", ".", "families", "family_list", ".", "each_value", "do", "|", "k", "|", "next", "if", "respond_to?", "(", "k", ".", "name", "+", "'?'", ")", "define_singleton_method", "(", "k", ".", "name", "+", "'?'", ")", "do", "family_hierarchy", ".", "include?", "(", "k", ".", "name", ")", "end", "end", "# Helper methods for direct platform info", "@platform", ".", "each_key", "do", "|", "m", "|", "next", "if", "respond_to?", "(", "m", ")", "define_singleton_method", "(", "m", ")", "do", "@platform", "[", "m", "]", "end", "end", "# Create method for name if its not already true", "m", "=", "name", "+", "'?'", "return", "if", "respond_to?", "(", "m", ")", "define_singleton_method", "(", "m", ")", "do", "true", "end", "end" ]
Add generic family? and platform methods to an existing platform This is done later to add any custom families/properties that were created
[ "Add", "generic", "family?", "and", "platform", "methods", "to", "an", "existing", "platform" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/platform.rb#L80-L107
train
inspec/train
lib/train/platforms/detect/helpers/os_windows.rb
Train::Platforms::Detect::Helpers.Windows.read_wmic
def read_wmic res = @backend.run_command('wmic os get * /format:list') if res.exit_status == 0 sys_info = {} res.stdout.lines.each { |line| m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line) sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil? } @platform[:release] = sys_info[:Version] # additional info on windows @platform[:build] = sys_info[:BuildNumber] @platform[:name] = sys_info[:Caption] @platform[:name] = @platform[:name].gsub('Microsoft', '').strip unless @platform[:name].empty? @platform[:arch] = read_wmic_cpu end end
ruby
def read_wmic res = @backend.run_command('wmic os get * /format:list') if res.exit_status == 0 sys_info = {} res.stdout.lines.each { |line| m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line) sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil? } @platform[:release] = sys_info[:Version] # additional info on windows @platform[:build] = sys_info[:BuildNumber] @platform[:name] = sys_info[:Caption] @platform[:name] = @platform[:name].gsub('Microsoft', '').strip unless @platform[:name].empty? @platform[:arch] = read_wmic_cpu end end
[ "def", "read_wmic", "res", "=", "@backend", ".", "run_command", "(", "'wmic os get * /format:list'", ")", "if", "res", ".", "exit_status", "==", "0", "sys_info", "=", "{", "}", "res", ".", "stdout", ".", "lines", ".", "each", "{", "|", "line", "|", "m", "=", "/", "\\s", "\\s", "\\s", "\\s", "/", ".", "match", "(", "line", ")", "sys_info", "[", "m", "[", "1", "]", ".", "to_sym", "]", "=", "m", "[", "2", "]", "unless", "m", ".", "nil?", "||", "m", "[", "1", "]", ".", "nil?", "}", "@platform", "[", ":release", "]", "=", "sys_info", "[", ":Version", "]", "# additional info on windows", "@platform", "[", ":build", "]", "=", "sys_info", "[", ":BuildNumber", "]", "@platform", "[", ":name", "]", "=", "sys_info", "[", ":Caption", "]", "@platform", "[", ":name", "]", "=", "@platform", "[", ":name", "]", ".", "gsub", "(", "'Microsoft'", ",", "''", ")", ".", "strip", "unless", "@platform", "[", ":name", "]", ".", "empty?", "@platform", "[", ":arch", "]", "=", "read_wmic_cpu", "end", "end" ]
reads os name and version from wmic @see https://msdn.microsoft.com/en-us/library/bb742610.aspx#EEAA Thanks to Matt Wrock (https://github.com/mwrock) for this hint
[ "reads", "os", "name", "and", "version", "from", "wmic" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_windows.rb#L33-L49
train
inspec/train
lib/train/platforms/detect/helpers/os_windows.rb
Train::Platforms::Detect::Helpers.Windows.read_wmic_cpu
def read_wmic_cpu res = @backend.run_command('wmic cpu get architecture /format:list') if res.exit_status == 0 sys_info = {} res.stdout.lines.each { |line| m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line) sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil? } end # This converts `wmic os get architecture` output to a normal standard # https://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx arch_map = { 0 => 'i386', 1 => 'mips', 2 => 'alpha', 3 => 'powerpc', 5 => 'arm', 6 => 'ia64', 9 => 'x86_64', } # The value of `wmic cpu get architecture` is always a number between 0-9 arch_number = sys_info[:Architecture].to_i arch_map[arch_number] end
ruby
def read_wmic_cpu res = @backend.run_command('wmic cpu get architecture /format:list') if res.exit_status == 0 sys_info = {} res.stdout.lines.each { |line| m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line) sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil? } end # This converts `wmic os get architecture` output to a normal standard # https://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx arch_map = { 0 => 'i386', 1 => 'mips', 2 => 'alpha', 3 => 'powerpc', 5 => 'arm', 6 => 'ia64', 9 => 'x86_64', } # The value of `wmic cpu get architecture` is always a number between 0-9 arch_number = sys_info[:Architecture].to_i arch_map[arch_number] end
[ "def", "read_wmic_cpu", "res", "=", "@backend", ".", "run_command", "(", "'wmic cpu get architecture /format:list'", ")", "if", "res", ".", "exit_status", "==", "0", "sys_info", "=", "{", "}", "res", ".", "stdout", ".", "lines", ".", "each", "{", "|", "line", "|", "m", "=", "/", "\\s", "\\s", "\\s", "\\s", "/", ".", "match", "(", "line", ")", "sys_info", "[", "m", "[", "1", "]", ".", "to_sym", "]", "=", "m", "[", "2", "]", "unless", "m", ".", "nil?", "||", "m", "[", "1", "]", ".", "nil?", "}", "end", "# This converts `wmic os get architecture` output to a normal standard", "# https://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx", "arch_map", "=", "{", "0", "=>", "'i386'", ",", "1", "=>", "'mips'", ",", "2", "=>", "'alpha'", ",", "3", "=>", "'powerpc'", ",", "5", "=>", "'arm'", ",", "6", "=>", "'ia64'", ",", "9", "=>", "'x86_64'", ",", "}", "# The value of `wmic cpu get architecture` is always a number between 0-9", "arch_number", "=", "sys_info", "[", ":Architecture", "]", ".", "to_i", "arch_map", "[", "arch_number", "]", "end" ]
`OSArchitecture` from `read_wmic` does not match a normal standard For example, `x86_64` shows as `64-bit`
[ "OSArchitecture", "from", "read_wmic", "does", "not", "match", "a", "normal", "standard", "For", "example", "x86_64", "shows", "as", "64", "-", "bit" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_windows.rb#L53-L78
train
inspec/train
lib/train/platforms/detect/helpers/os_windows.rb
Train::Platforms::Detect::Helpers.Windows.windows_uuid
def windows_uuid uuid = windows_uuid_from_chef uuid = windows_uuid_from_machine_file if uuid.nil? uuid = windows_uuid_from_wmic if uuid.nil? uuid = windows_uuid_from_registry if uuid.nil? raise Train::TransportError, 'Cannot find a UUID for your node.' if uuid.nil? uuid end
ruby
def windows_uuid uuid = windows_uuid_from_chef uuid = windows_uuid_from_machine_file if uuid.nil? uuid = windows_uuid_from_wmic if uuid.nil? uuid = windows_uuid_from_registry if uuid.nil? raise Train::TransportError, 'Cannot find a UUID for your node.' if uuid.nil? uuid end
[ "def", "windows_uuid", "uuid", "=", "windows_uuid_from_chef", "uuid", "=", "windows_uuid_from_machine_file", "if", "uuid", ".", "nil?", "uuid", "=", "windows_uuid_from_wmic", "if", "uuid", ".", "nil?", "uuid", "=", "windows_uuid_from_registry", "if", "uuid", ".", "nil?", "raise", "Train", "::", "TransportError", ",", "'Cannot find a UUID for your node.'", "if", "uuid", ".", "nil?", "uuid", "end" ]
This method scans the target os for a unique uuid to use
[ "This", "method", "scans", "the", "target", "os", "for", "a", "unique", "uuid", "to", "use" ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_windows.rb#L81-L88
train
inspec/train
examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb
TrainPlugins::LocalRot13.Platform.platform
def platform # If you are declaring a new platform, you will need to tell # Train a bit about it. # If you were defining a cloud API, you should say you are a member # of the cloud family. # This plugin makes up a new platform. Train (or rather InSpec) only # know how to read files on Windows and Un*x (MacOS is a kind of Un*x), # so we'll say we're part of those families. Train::Platforms.name('local-rot13').in_family('unix') Train::Platforms.name('local-rot13').in_family('windows') # When you know you will only ever run on your dedicated platform # (for example, a plugin named train-aws would only run on the AWS # API, which we report as the 'aws' platform). # force_platform! lets you bypass platform detection. # The options to this are not currently documented completely. # Use release to report a version number. You might use the version # of the plugin, or a version of an important underlying SDK, or a # version of a remote API. force_platform!('local-rot13', release: TrainPlugins::LocalRot13::VERSION) end
ruby
def platform # If you are declaring a new platform, you will need to tell # Train a bit about it. # If you were defining a cloud API, you should say you are a member # of the cloud family. # This plugin makes up a new platform. Train (or rather InSpec) only # know how to read files on Windows and Un*x (MacOS is a kind of Un*x), # so we'll say we're part of those families. Train::Platforms.name('local-rot13').in_family('unix') Train::Platforms.name('local-rot13').in_family('windows') # When you know you will only ever run on your dedicated platform # (for example, a plugin named train-aws would only run on the AWS # API, which we report as the 'aws' platform). # force_platform! lets you bypass platform detection. # The options to this are not currently documented completely. # Use release to report a version number. You might use the version # of the plugin, or a version of an important underlying SDK, or a # version of a remote API. force_platform!('local-rot13', release: TrainPlugins::LocalRot13::VERSION) end
[ "def", "platform", "# If you are declaring a new platform, you will need to tell", "# Train a bit about it.", "# If you were defining a cloud API, you should say you are a member", "# of the cloud family.", "# This plugin makes up a new platform. Train (or rather InSpec) only", "# know how to read files on Windows and Un*x (MacOS is a kind of Un*x),", "# so we'll say we're part of those families.", "Train", "::", "Platforms", ".", "name", "(", "'local-rot13'", ")", ".", "in_family", "(", "'unix'", ")", "Train", "::", "Platforms", ".", "name", "(", "'local-rot13'", ")", ".", "in_family", "(", "'windows'", ")", "# When you know you will only ever run on your dedicated platform", "# (for example, a plugin named train-aws would only run on the AWS", "# API, which we report as the 'aws' platform).", "# force_platform! lets you bypass platform detection.", "# The options to this are not currently documented completely.", "# Use release to report a version number. You might use the version", "# of the plugin, or a version of an important underlying SDK, or a", "# version of a remote API.", "force_platform!", "(", "'local-rot13'", ",", "release", ":", "TrainPlugins", "::", "LocalRot13", "::", "VERSION", ")", "end" ]
The method `platform` is called when platform detection is about to be performed. Train core defines a sophisticated system for platform detection, but for most plugins, you'll only ever run on the special platform for which you are targeting.
[ "The", "method", "platform", "is", "called", "when", "platform", "detection", "is", "about", "to", "be", "performed", ".", "Train", "core", "defines", "a", "sophisticated", "system", "for", "platform", "detection", "but", "for", "most", "plugins", "you", "ll", "only", "ever", "run", "on", "the", "special", "platform", "for", "which", "you", "are", "targeting", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb#L14-L36
train
inspec/train
lib/train/platforms/detect/helpers/os_common.rb
Train::Platforms::Detect::Helpers.OSCommon.uuid_from_command
def uuid_from_command return unless @platform[:uuid_command] result = @backend.run_command(@platform[:uuid_command]) uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty? end
ruby
def uuid_from_command return unless @platform[:uuid_command] result = @backend.run_command(@platform[:uuid_command]) uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty? end
[ "def", "uuid_from_command", "return", "unless", "@platform", "[", ":uuid_command", "]", "result", "=", "@backend", ".", "run_command", "(", "@platform", "[", ":uuid_command", "]", ")", "uuid_from_string", "(", "result", ".", "stdout", ".", "chomp", ")", "if", "result", ".", "exit_status", ".", "zero?", "&&", "!", "result", ".", "stdout", ".", "empty?", "end" ]
This takes a command from the platform detect block to run. We expect the command to return a unique identifier which we turn into a UUID.
[ "This", "takes", "a", "command", "from", "the", "platform", "detect", "block", "to", "run", ".", "We", "expect", "the", "command", "to", "return", "a", "unique", "identifier", "which", "we", "turn", "into", "a", "UUID", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_common.rb#L125-L129
train
inspec/train
lib/train/platforms/detect/helpers/os_common.rb
Train::Platforms::Detect::Helpers.OSCommon.uuid_from_string
def uuid_from_string(string) hash = Digest::SHA1.new hash.update(string) ary = hash.digest.unpack('NnnnnN') ary[2] = (ary[2] & 0x0FFF) | (5 << 12) ary[3] = (ary[3] & 0x3FFF) | 0x8000 # rubocop:disable Style/FormatString '%08x-%04x-%04x-%04x-%04x%08x' % ary end
ruby
def uuid_from_string(string) hash = Digest::SHA1.new hash.update(string) ary = hash.digest.unpack('NnnnnN') ary[2] = (ary[2] & 0x0FFF) | (5 << 12) ary[3] = (ary[3] & 0x3FFF) | 0x8000 # rubocop:disable Style/FormatString '%08x-%04x-%04x-%04x-%04x%08x' % ary end
[ "def", "uuid_from_string", "(", "string", ")", "hash", "=", "Digest", "::", "SHA1", ".", "new", "hash", ".", "update", "(", "string", ")", "ary", "=", "hash", ".", "digest", ".", "unpack", "(", "'NnnnnN'", ")", "ary", "[", "2", "]", "=", "(", "ary", "[", "2", "]", "&", "0x0FFF", ")", "|", "(", "5", "<<", "12", ")", "ary", "[", "3", "]", "=", "(", "ary", "[", "3", "]", "&", "0x3FFF", ")", "|", "0x8000", "# rubocop:disable Style/FormatString", "'%08x-%04x-%04x-%04x-%04x%08x'", "%", "ary", "end" ]
This hashes the passed string into SHA1. Then it downgrades the 160bit SHA1 to a 128bit then we format it as a valid UUIDv5.
[ "This", "hashes", "the", "passed", "string", "into", "SHA1", ".", "Then", "it", "downgrades", "the", "160bit", "SHA1", "to", "a", "128bit", "then", "we", "format", "it", "as", "a", "valid", "UUIDv5", "." ]
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_common.rb#L134-L142
train
guilhermesad/rspotify
lib/rspotify/category.rb
RSpotify.Category.playlists
def playlists(limit: 20, offset: 0, **options) url = "browse/categories/#{@id}/playlists"\ "?limit=#{limit}&offset=#{offset}" options.each do |option, value| url << "&#{option}=#{value}" end response = RSpotify.get(url) return response if RSpotify.raw_response response['playlists']['items'].map { |i| Playlist.new i } end
ruby
def playlists(limit: 20, offset: 0, **options) url = "browse/categories/#{@id}/playlists"\ "?limit=#{limit}&offset=#{offset}" options.each do |option, value| url << "&#{option}=#{value}" end response = RSpotify.get(url) return response if RSpotify.raw_response response['playlists']['items'].map { |i| Playlist.new i } end
[ "def", "playlists", "(", "limit", ":", "20", ",", "offset", ":", "0", ",", "**", "options", ")", "url", "=", "\"browse/categories/#{@id}/playlists\"", "\"?limit=#{limit}&offset=#{offset}\"", "options", ".", "each", "do", "|", "option", ",", "value", "|", "url", "<<", "\"&#{option}=#{value}\"", "end", "response", "=", "RSpotify", ".", "get", "(", "url", ")", "return", "response", "if", "RSpotify", ".", "raw_response", "response", "[", "'playlists'", "]", "[", "'items'", "]", ".", "map", "{", "|", "i", "|", "Playlist", ".", "new", "i", "}", "end" ]
Get a list of Spotify playlists tagged with a particular category. @param limit [Integer] Maximum number of playlists to return. Maximum: 50. Default: 20. @param offset [Integer] The index of the first playlist to return. Use with limit to get the next set of playlists. Default: 0. @param country [String] Optional. A country: an {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Provide this parameter if you want to narrow the list of returned playlists to those relevant to a particular country. If omitted, the returned playlists will be globally relevant. @return [Array<Playlist>] @example playlists = category.playlists playlists = category.playlists(country: 'BR') playlists = category.playlists(limit: 10, offset: 20)
[ "Get", "a", "list", "of", "Spotify", "playlists", "tagged", "with", "a", "particular", "category", "." ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/category.rb#L89-L100
train
guilhermesad/rspotify
lib/rspotify/player.rb
RSpotify.Player.play
def play(device_id = nil, params = {}) url = "me/player/play" url = device_id.nil? ? url : "#{url}?device_id=#{device_id}" User.oauth_put(@user.id, url, params.to_json) end
ruby
def play(device_id = nil, params = {}) url = "me/player/play" url = device_id.nil? ? url : "#{url}?device_id=#{device_id}" User.oauth_put(@user.id, url, params.to_json) end
[ "def", "play", "(", "device_id", "=", "nil", ",", "params", "=", "{", "}", ")", "url", "=", "\"me/player/play\"", "url", "=", "device_id", ".", "nil?", "?", "url", ":", "\"#{url}?device_id=#{device_id}\"", "User", ".", "oauth_put", "(", "@user", ".", "id", ",", "url", ",", "params", ".", "to_json", ")", "end" ]
Play the user's currently active player or specific device If `device_id` is not passed, the currently active spotify app will be triggered @example player = user.player player.play
[ "Play", "the", "user", "s", "currently", "active", "player", "or", "specific", "device", "If", "device_id", "is", "not", "passed", "the", "currently", "active", "spotify", "app", "will", "be", "triggered" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/player.rb#L66-L71
train
guilhermesad/rspotify
lib/rspotify/player.rb
RSpotify.Player.repeat
def repeat(device_id: nil, state: "context") url = "me/player/repeat" url += "?state=#{state}" url += "&device_id=#{device_id}" if device_id User.oauth_put(@user.id, url, {}) end
ruby
def repeat(device_id: nil, state: "context") url = "me/player/repeat" url += "?state=#{state}" url += "&device_id=#{device_id}" if device_id User.oauth_put(@user.id, url, {}) end
[ "def", "repeat", "(", "device_id", ":", "nil", ",", "state", ":", "\"context\"", ")", "url", "=", "\"me/player/repeat\"", "url", "+=", "\"?state=#{state}\"", "url", "+=", "\"&device_id=#{device_id}\"", "if", "device_id", "User", ".", "oauth_put", "(", "@user", ".", "id", ",", "url", ",", "{", "}", ")", "end" ]
Toggle the current user's player repeat status. If `device_id` is not passed, the currently active spotify app will be triggered. If `state` is not passed, the currently active context will be set to repeat. @see https://developer.spotify.com/documentation/web-api/reference/player/set-repeat-mode-on-users-playback/ @param [String] device_id the ID of the device to set the repeat state on. @param [String] state the repeat state. Defaults to the current play context. @example player = user.player player.repeat(state: 'track')
[ "Toggle", "the", "current", "user", "s", "player", "repeat", "status", ".", "If", "device_id", "is", "not", "passed", "the", "currently", "active", "spotify", "app", "will", "be", "triggered", ".", "If", "state", "is", "not", "passed", "the", "currently", "active", "context", "will", "be", "set", "to", "repeat", "." ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/player.rb#L85-L91
train
guilhermesad/rspotify
lib/rspotify/player.rb
RSpotify.Player.shuffle
def shuffle(device_id: nil, state: true) url = "me/player/shuffle" url += "?state=#{state}" url += "&device_id=#{device_id}" if device_id User.oauth_put(@user.id, url, {}) end
ruby
def shuffle(device_id: nil, state: true) url = "me/player/shuffle" url += "?state=#{state}" url += "&device_id=#{device_id}" if device_id User.oauth_put(@user.id, url, {}) end
[ "def", "shuffle", "(", "device_id", ":", "nil", ",", "state", ":", "true", ")", "url", "=", "\"me/player/shuffle\"", "url", "+=", "\"?state=#{state}\"", "url", "+=", "\"&device_id=#{device_id}\"", "if", "device_id", "User", ".", "oauth_put", "(", "@user", ".", "id", ",", "url", ",", "{", "}", ")", "end" ]
Toggle the current user's shuffle status. If `device_id` is not passed, the currently active spotify app will be triggered. If `state` is not passed, shuffle mode will be turned on. @see https://developer.spotify.com/documentation/web-api/reference/player/toggle-shuffle-for-users-playback/ @param [String] device_id the ID of the device to set the shuffle state on. @param [String] state the shuffle state. Defaults to turning the shuffle behavior on. @example player = user.player player.shuffle(state: false)
[ "Toggle", "the", "current", "user", "s", "shuffle", "status", ".", "If", "device_id", "is", "not", "passed", "the", "currently", "active", "spotify", "app", "will", "be", "triggered", ".", "If", "state", "is", "not", "passed", "shuffle", "mode", "will", "be", "turned", "on", "." ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/player.rb#L115-L121
train
guilhermesad/rspotify
lib/rspotify/album.rb
RSpotify.Album.tracks
def tracks(limit: 50, offset: 0, market: nil) last_track = offset + limit - 1 if @tracks_cache && last_track < 50 && !RSpotify.raw_response return @tracks_cache[offset..last_track] end url = "albums/#{@id}/tracks?limit=#{limit}&offset=#{offset}" url << "&market=#{market}" if market response = RSpotify.get(url) json = RSpotify.raw_response ? JSON.parse(response) : response tracks = json['items'].map { |i| Track.new i } @tracks_cache = tracks if limit == 50 && offset == 0 return response if RSpotify.raw_response tracks end
ruby
def tracks(limit: 50, offset: 0, market: nil) last_track = offset + limit - 1 if @tracks_cache && last_track < 50 && !RSpotify.raw_response return @tracks_cache[offset..last_track] end url = "albums/#{@id}/tracks?limit=#{limit}&offset=#{offset}" url << "&market=#{market}" if market response = RSpotify.get(url) json = RSpotify.raw_response ? JSON.parse(response) : response tracks = json['items'].map { |i| Track.new i } @tracks_cache = tracks if limit == 50 && offset == 0 return response if RSpotify.raw_response tracks end
[ "def", "tracks", "(", "limit", ":", "50", ",", "offset", ":", "0", ",", "market", ":", "nil", ")", "last_track", "=", "offset", "+", "limit", "-", "1", "if", "@tracks_cache", "&&", "last_track", "<", "50", "&&", "!", "RSpotify", ".", "raw_response", "return", "@tracks_cache", "[", "offset", "..", "last_track", "]", "end", "url", "=", "\"albums/#{@id}/tracks?limit=#{limit}&offset=#{offset}\"", "url", "<<", "\"&market=#{market}\"", "if", "market", "response", "=", "RSpotify", ".", "get", "(", "url", ")", "json", "=", "RSpotify", ".", "raw_response", "?", "JSON", ".", "parse", "(", "response", ")", ":", "response", "tracks", "=", "json", "[", "'items'", "]", ".", "map", "{", "|", "i", "|", "Track", ".", "new", "i", "}", "@tracks_cache", "=", "tracks", "if", "limit", "==", "50", "&&", "offset", "==", "0", "return", "response", "if", "RSpotify", ".", "raw_response", "tracks", "end" ]
Returns array of tracks from the album @param limit [Integer] Maximum number of tracks to return. Maximum: 50. Default: 50. @param offset [Integer] The index of the first track to return. Use with limit to get the next set of objects. Default: 0. @param market [String] Optional. An {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Default: nil. @return [Array<Track>] @example album = RSpotify::Album.find('41vPD50kQ7JeamkxQW7Vuy') album.tracks.first.name #=> "Do I Wanna Know?"
[ "Returns", "array", "of", "tracks", "from", "the", "album" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/album.rb#L111-L127
train
guilhermesad/rspotify
lib/rspotify/artist.rb
RSpotify.Artist.albums
def albums(limit: 20, offset: 0, **filters) url = "artists/#{@id}/albums?limit=#{limit}&offset=#{offset}" filters.each do |filter_name, filter_value| url << "&#{filter_name}=#{filter_value}" end response = RSpotify.get(url) return response if RSpotify.raw_response response['items'].map { |i| Album.new i } end
ruby
def albums(limit: 20, offset: 0, **filters) url = "artists/#{@id}/albums?limit=#{limit}&offset=#{offset}" filters.each do |filter_name, filter_value| url << "&#{filter_name}=#{filter_value}" end response = RSpotify.get(url) return response if RSpotify.raw_response response['items'].map { |i| Album.new i } end
[ "def", "albums", "(", "limit", ":", "20", ",", "offset", ":", "0", ",", "**", "filters", ")", "url", "=", "\"artists/#{@id}/albums?limit=#{limit}&offset=#{offset}\"", "filters", ".", "each", "do", "|", "filter_name", ",", "filter_value", "|", "url", "<<", "\"&#{filter_name}=#{filter_value}\"", "end", "response", "=", "RSpotify", ".", "get", "(", "url", ")", "return", "response", "if", "RSpotify", ".", "raw_response", "response", "[", "'items'", "]", ".", "map", "{", "|", "i", "|", "Album", ".", "new", "i", "}", "end" ]
Returns array of albums from artist @param limit [Integer] Maximum number of albums to return. Maximum: 50. Default: 20. @param offset [Integer] The index of the first album to return. Use with limit to get the next set of albums. Default: 0. @param album_type [String] Optional. A comma-separated list of keywords that will be used to filter the response. If not supplied, all album types will be returned. Valid values are: album; single; appears_on; compilation. @param market [String] Optional. (synonym: country). An {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Supply this parameter to limit the response to one particular geographical market. If not supplied, results will be returned for all markets. Note if you do not provide this field, you are likely to get duplicate results per album, one for each market in which the album is available. @return [Array<Album>] @example artist.albums artist.albums(album_type: 'single,compilation') artist.albums(limit: 50, country: 'US')
[ "Returns", "array", "of", "albums", "from", "artist" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/artist.rb#L69-L78
train
guilhermesad/rspotify
lib/rspotify/artist.rb
RSpotify.Artist.top_tracks
def top_tracks(country) return @top_tracks[country] unless @top_tracks[country].nil? || RSpotify.raw_response response = RSpotify.get("artists/#{@id}/top-tracks?country=#{country}") return response if RSpotify.raw_response @top_tracks[country] = response['tracks'].map { |t| Track.new t } end
ruby
def top_tracks(country) return @top_tracks[country] unless @top_tracks[country].nil? || RSpotify.raw_response response = RSpotify.get("artists/#{@id}/top-tracks?country=#{country}") return response if RSpotify.raw_response @top_tracks[country] = response['tracks'].map { |t| Track.new t } end
[ "def", "top_tracks", "(", "country", ")", "return", "@top_tracks", "[", "country", "]", "unless", "@top_tracks", "[", "country", "]", ".", "nil?", "||", "RSpotify", ".", "raw_response", "response", "=", "RSpotify", ".", "get", "(", "\"artists/#{@id}/top-tracks?country=#{country}\"", ")", "return", "response", "if", "RSpotify", ".", "raw_response", "@top_tracks", "[", "country", "]", "=", "response", "[", "'tracks'", "]", ".", "map", "{", "|", "t", "|", "Track", ".", "new", "t", "}", "end" ]
Returns artist's 10 top tracks by country. @param country [Symbol] An {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code} @return [Array<Track>] @example top_tracks = artist.top_tracks(:US) top_tracks.class #=> Array top_tracks.size #=> 10 top_tracks.first.class #=> RSpotify::Track
[ "Returns", "artist", "s", "10", "top", "tracks", "by", "country", "." ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/artist.rb#L108-L114
train
guilhermesad/rspotify
lib/rspotify/playlist.rb
RSpotify.Playlist.tracks
def tracks(limit: 100, offset: 0, market: nil) last_track = offset + limit - 1 if @tracks_cache && last_track < 100 && !RSpotify.raw_response return @tracks_cache[offset..last_track] end url = "#{@href}/tracks?limit=#{limit}&offset=#{offset}" url << "&market=#{market}" if market response = RSpotify.resolve_auth_request(@owner.id, url) json = RSpotify.raw_response ? JSON.parse(response) : response tracks = json['items'].select { |i| i['track'] } @tracks_added_at = hash_for(tracks, 'added_at') do |added_at| Time.parse added_at end @tracks_added_by = hash_for(tracks, 'added_by') do |added_by| User.new added_by end @tracks_is_local = hash_for(tracks, 'is_local') do |is_local| is_local end tracks.map! { |t| Track.new t['track'] } @tracks_cache = tracks if limit == 100 && offset == 0 return response if RSpotify.raw_response tracks end
ruby
def tracks(limit: 100, offset: 0, market: nil) last_track = offset + limit - 1 if @tracks_cache && last_track < 100 && !RSpotify.raw_response return @tracks_cache[offset..last_track] end url = "#{@href}/tracks?limit=#{limit}&offset=#{offset}" url << "&market=#{market}" if market response = RSpotify.resolve_auth_request(@owner.id, url) json = RSpotify.raw_response ? JSON.parse(response) : response tracks = json['items'].select { |i| i['track'] } @tracks_added_at = hash_for(tracks, 'added_at') do |added_at| Time.parse added_at end @tracks_added_by = hash_for(tracks, 'added_by') do |added_by| User.new added_by end @tracks_is_local = hash_for(tracks, 'is_local') do |is_local| is_local end tracks.map! { |t| Track.new t['track'] } @tracks_cache = tracks if limit == 100 && offset == 0 return response if RSpotify.raw_response tracks end
[ "def", "tracks", "(", "limit", ":", "100", ",", "offset", ":", "0", ",", "market", ":", "nil", ")", "last_track", "=", "offset", "+", "limit", "-", "1", "if", "@tracks_cache", "&&", "last_track", "<", "100", "&&", "!", "RSpotify", ".", "raw_response", "return", "@tracks_cache", "[", "offset", "..", "last_track", "]", "end", "url", "=", "\"#{@href}/tracks?limit=#{limit}&offset=#{offset}\"", "url", "<<", "\"&market=#{market}\"", "if", "market", "response", "=", "RSpotify", ".", "resolve_auth_request", "(", "@owner", ".", "id", ",", "url", ")", "json", "=", "RSpotify", ".", "raw_response", "?", "JSON", ".", "parse", "(", "response", ")", ":", "response", "tracks", "=", "json", "[", "'items'", "]", ".", "select", "{", "|", "i", "|", "i", "[", "'track'", "]", "}", "@tracks_added_at", "=", "hash_for", "(", "tracks", ",", "'added_at'", ")", "do", "|", "added_at", "|", "Time", ".", "parse", "added_at", "end", "@tracks_added_by", "=", "hash_for", "(", "tracks", ",", "'added_by'", ")", "do", "|", "added_by", "|", "User", ".", "new", "added_by", "end", "@tracks_is_local", "=", "hash_for", "(", "tracks", ",", "'is_local'", ")", "do", "|", "is_local", "|", "is_local", "end", "tracks", ".", "map!", "{", "|", "t", "|", "Track", ".", "new", "t", "[", "'track'", "]", "}", "@tracks_cache", "=", "tracks", "if", "limit", "==", "100", "&&", "offset", "==", "0", "return", "response", "if", "RSpotify", ".", "raw_response", "tracks", "end" ]
Returns array of tracks from the playlist @param limit [Integer] Maximum number of tracks to return. Maximum: 100. Default: 100. @param offset [Integer] The index of the first track to return. Use with limit to get the next set of objects. Default: 0. @param market [String] Optional. An {https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Provide this parameter if you want to apply Track Relinking @return [Array<Track>] @example playlist = RSpotify::Playlist.find('wizzler', '00wHcTN0zQiun4xri9pmvX') playlist.tracks.first.name #=> "Main Theme from Star Wars - Instrumental"
[ "Returns", "array", "of", "tracks", "from", "the", "playlist" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/playlist.rb#L255-L284
train
guilhermesad/rspotify
lib/rspotify/user.rb
RSpotify.User.playlists
def playlists(limit: 20, offset: 0) url = "users/#{@id}/playlists?limit=#{limit}&offset=#{offset}" response = RSpotify.resolve_auth_request(@id, url) return response if RSpotify.raw_response response['items'].map { |i| Playlist.new i } end
ruby
def playlists(limit: 20, offset: 0) url = "users/#{@id}/playlists?limit=#{limit}&offset=#{offset}" response = RSpotify.resolve_auth_request(@id, url) return response if RSpotify.raw_response response['items'].map { |i| Playlist.new i } end
[ "def", "playlists", "(", "limit", ":", "20", ",", "offset", ":", "0", ")", "url", "=", "\"users/#{@id}/playlists?limit=#{limit}&offset=#{offset}\"", "response", "=", "RSpotify", ".", "resolve_auth_request", "(", "@id", ",", "url", ")", "return", "response", "if", "RSpotify", ".", "raw_response", "response", "[", "'items'", "]", ".", "map", "{", "|", "i", "|", "Playlist", ".", "new", "i", "}", "end" ]
Returns all playlists from user @param limit [Integer] Maximum number of playlists to return. Maximum: 50. Minimum: 1. Default: 20. @param offset [Integer] The index of the first playlist to return. Use with limit to get the next set of playlists. Default: 0. @return [Array<Playlist>] @example playlists = user.playlists playlists.class #=> Array playlists.first.class #=> RSpotify::Playlist playlists.first.name #=> "Movie Soundtrack Masterpieces"
[ "Returns", "all", "playlists", "from", "user" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/user.rb#L255-L260
train
guilhermesad/rspotify
lib/rspotify/user.rb
RSpotify.User.to_hash
def to_hash pairs = instance_variables.map do |var| [var.to_s.delete('@'), instance_variable_get(var)] end Hash[pairs] end
ruby
def to_hash pairs = instance_variables.map do |var| [var.to_s.delete('@'), instance_variable_get(var)] end Hash[pairs] end
[ "def", "to_hash", "pairs", "=", "instance_variables", ".", "map", "do", "|", "var", "|", "[", "var", ".", "to_s", ".", "delete", "(", "'@'", ")", ",", "instance_variable_get", "(", "var", ")", "]", "end", "Hash", "[", "pairs", "]", "end" ]
Returns a hash containing all user attributes
[ "Returns", "a", "hash", "containing", "all", "user", "attributes" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/user.rb#L410-L415
train
guilhermesad/rspotify
lib/rspotify/user.rb
RSpotify.User.devices
def devices url = "me/player/devices" response = RSpotify.resolve_auth_request(@id, url) return response if RSpotify.raw_response response['devices'].map { |i| Device.new i } end
ruby
def devices url = "me/player/devices" response = RSpotify.resolve_auth_request(@id, url) return response if RSpotify.raw_response response['devices'].map { |i| Device.new i } end
[ "def", "devices", "url", "=", "\"me/player/devices\"", "response", "=", "RSpotify", ".", "resolve_auth_request", "(", "@id", ",", "url", ")", "return", "response", "if", "RSpotify", ".", "raw_response", "response", "[", "'devices'", "]", ".", "map", "{", "|", "i", "|", "Device", ".", "new", "i", "}", "end" ]
Returns the user's available devices @return [Array<Device>] @example devices = user.devices devices.first.id #=> "5fbb3ba6aa454b5534c4ba43a8c7e8e45a63ad0e"
[ "Returns", "the", "user", "s", "available", "devices" ]
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/user.rb#L493-L499
train
nakiostudio/xcov
lib/xcov/ignore_handler.rb
Xcov.IgnoreHandler.relative_path
def relative_path path require 'pathname' full_path = Pathname.new(path).realpath # /full/path/to/project/where/is/file.extension base_path = Pathname.new(source_directory).realpath # /full/path/to/project/ full_path.relative_path_from(base_path).to_s # where/is/file.extension end
ruby
def relative_path path require 'pathname' full_path = Pathname.new(path).realpath # /full/path/to/project/where/is/file.extension base_path = Pathname.new(source_directory).realpath # /full/path/to/project/ full_path.relative_path_from(base_path).to_s # where/is/file.extension end
[ "def", "relative_path", "path", "require", "'pathname'", "full_path", "=", "Pathname", ".", "new", "(", "path", ")", ".", "realpath", "# /full/path/to/project/where/is/file.extension", "base_path", "=", "Pathname", ".", "new", "(", "source_directory", ")", ".", "realpath", "# /full/path/to/project/", "full_path", ".", "relative_path_from", "(", "base_path", ")", ".", "to_s", "# where/is/file.extension", "end" ]
Auxiliary methods Returns a relative path against `source_directory`.
[ "Auxiliary", "methods", "Returns", "a", "relative", "path", "against", "source_directory", "." ]
9fb0e043438fcc636db964fe6ca547162a170b73
https://github.com/nakiostudio/xcov/blob/9fb0e043438fcc636db964fe6ca547162a170b73/lib/xcov/ignore_handler.rb#L52-L59
train
nakiostudio/xcov
lib/xcov/project_extensions.rb
FastlaneCore.Project.targets
def targets project_path = get_project_path return [] if project_path.nil? proj = Xcodeproj::Project.open(project_path) proj.targets.map do |target| target.name end end
ruby
def targets project_path = get_project_path return [] if project_path.nil? proj = Xcodeproj::Project.open(project_path) proj.targets.map do |target| target.name end end
[ "def", "targets", "project_path", "=", "get_project_path", "return", "[", "]", "if", "project_path", ".", "nil?", "proj", "=", "Xcodeproj", "::", "Project", ".", "open", "(", "project_path", ")", "proj", ".", "targets", ".", "map", "do", "|", "target", "|", "target", ".", "name", "end", "end" ]
Returns project targets
[ "Returns", "project", "targets" ]
9fb0e043438fcc636db964fe6ca547162a170b73
https://github.com/nakiostudio/xcov/blob/9fb0e043438fcc636db964fe6ca547162a170b73/lib/xcov/project_extensions.rb#L8-L17
train
octopress/octopress
lib/octopress/page.rb
Octopress.Page.content
def content # Handle case where user passes the full path # file = @options['template'] || default_template if file file.sub!(/^_templates\//, '') file = File.join(site.source, '_templates', file) if file if File.exist? file parse_template File.open(file).read.encode('UTF-8') elsif @options['template'] abort "No #{@options['type']} template found at #{file}" else parse_template default_front_matter end else parse_template default_front_matter end end
ruby
def content # Handle case where user passes the full path # file = @options['template'] || default_template if file file.sub!(/^_templates\//, '') file = File.join(site.source, '_templates', file) if file if File.exist? file parse_template File.open(file).read.encode('UTF-8') elsif @options['template'] abort "No #{@options['type']} template found at #{file}" else parse_template default_front_matter end else parse_template default_front_matter end end
[ "def", "content", "# Handle case where user passes the full path", "#", "file", "=", "@options", "[", "'template'", "]", "||", "default_template", "if", "file", "file", ".", "sub!", "(", "/", "\\/", "/", ",", "''", ")", "file", "=", "File", ".", "join", "(", "site", ".", "source", ",", "'_templates'", ",", "file", ")", "if", "file", "if", "File", ".", "exist?", "file", "parse_template", "File", ".", "open", "(", "file", ")", ".", "read", ".", "encode", "(", "'UTF-8'", ")", "elsif", "@options", "[", "'template'", "]", "abort", "\"No #{@options['type']} template found at #{file}\"", "else", "parse_template", "default_front_matter", "end", "else", "parse_template", "default_front_matter", "end", "end" ]
Load the user provided or default template for a new post or page.
[ "Load", "the", "user", "provided", "or", "default", "template", "for", "a", "new", "post", "or", "page", "." ]
af048361405919605d50fc45e2e1fd0c7eb02703
https://github.com/octopress/octopress/blob/af048361405919605d50fc45e2e1fd0c7eb02703/lib/octopress/page.rb#L126-L145
train
octopress/octopress
lib/octopress/page.rb
Octopress.Page.parse_template
def parse_template(input) if @config['titlecase'] @options['title'].titlecase! end vars = @options.dup # Allow templates to use slug # vars['slug'] = title_slug # Allow templates to use date fragments # date = Time.parse(vars['date'] || Time.now.iso8601) vars['date'] = date.iso8601 vars['year'] = date.year vars['month'] = date.strftime('%m') vars['day'] = date.strftime('%d') vars['ymd'] = date.strftime('%Y-%m-%d') # If possible only parse the YAML front matter. # If YAML front-matter dashes aren't present parse the whole # template and add dashes. # parsed = if input =~ /\A-{3}\s+(.+?)\s+-{3}(.+)?/m input = $1 content = $2 input << default_front_matter(input) else content = '' end template = Liquid::Template.parse(input) "---\n#{template.render(vars).strip}\n---\n#{content}" end
ruby
def parse_template(input) if @config['titlecase'] @options['title'].titlecase! end vars = @options.dup # Allow templates to use slug # vars['slug'] = title_slug # Allow templates to use date fragments # date = Time.parse(vars['date'] || Time.now.iso8601) vars['date'] = date.iso8601 vars['year'] = date.year vars['month'] = date.strftime('%m') vars['day'] = date.strftime('%d') vars['ymd'] = date.strftime('%Y-%m-%d') # If possible only parse the YAML front matter. # If YAML front-matter dashes aren't present parse the whole # template and add dashes. # parsed = if input =~ /\A-{3}\s+(.+?)\s+-{3}(.+)?/m input = $1 content = $2 input << default_front_matter(input) else content = '' end template = Liquid::Template.parse(input) "---\n#{template.render(vars).strip}\n---\n#{content}" end
[ "def", "parse_template", "(", "input", ")", "if", "@config", "[", "'titlecase'", "]", "@options", "[", "'title'", "]", ".", "titlecase!", "end", "vars", "=", "@options", ".", "dup", "# Allow templates to use slug", "#", "vars", "[", "'slug'", "]", "=", "title_slug", "# Allow templates to use date fragments", "#", "date", "=", "Time", ".", "parse", "(", "vars", "[", "'date'", "]", "||", "Time", ".", "now", ".", "iso8601", ")", "vars", "[", "'date'", "]", "=", "date", ".", "iso8601", "vars", "[", "'year'", "]", "=", "date", ".", "year", "vars", "[", "'month'", "]", "=", "date", ".", "strftime", "(", "'%m'", ")", "vars", "[", "'day'", "]", "=", "date", ".", "strftime", "(", "'%d'", ")", "vars", "[", "'ymd'", "]", "=", "date", ".", "strftime", "(", "'%Y-%m-%d'", ")", "# If possible only parse the YAML front matter.", "# If YAML front-matter dashes aren't present parse the whole ", "# template and add dashes.", "#", "parsed", "=", "if", "input", "=~", "/", "\\A", "\\s", "\\s", "/m", "input", "=", "$1", "content", "=", "$2", "input", "<<", "default_front_matter", "(", "input", ")", "else", "content", "=", "''", "end", "template", "=", "Liquid", "::", "Template", ".", "parse", "(", "input", ")", "\"---\\n#{template.render(vars).strip}\\n---\\n#{content}\"", "end" ]
Render Liquid vars in YAML front-matter.
[ "Render", "Liquid", "vars", "in", "YAML", "front", "-", "matter", "." ]
af048361405919605d50fc45e2e1fd0c7eb02703
https://github.com/octopress/octopress/blob/af048361405919605d50fc45e2e1fd0c7eb02703/lib/octopress/page.rb#L152-L188
train
octopress/octopress
lib/octopress/page.rb
Octopress.Page.title_slug
def title_slug value = (@options['slug'] || @options['title']).downcase value.gsub!(/[^\x00-\x7F]/u, '') value.gsub!(/(&amp;|&)+/, 'and') value.gsub!(/[']+/, '') value.gsub!(/\W+/, ' ') value.strip! value.gsub!(' ', '-') value end
ruby
def title_slug value = (@options['slug'] || @options['title']).downcase value.gsub!(/[^\x00-\x7F]/u, '') value.gsub!(/(&amp;|&)+/, 'and') value.gsub!(/[']+/, '') value.gsub!(/\W+/, ' ') value.strip! value.gsub!(' ', '-') value end
[ "def", "title_slug", "value", "=", "(", "@options", "[", "'slug'", "]", "||", "@options", "[", "'title'", "]", ")", ".", "downcase", "value", ".", "gsub!", "(", "/", "\\x00", "\\x7F", "/u", ",", "''", ")", "value", ".", "gsub!", "(", "/", "/", ",", "'and'", ")", "value", ".", "gsub!", "(", "/", "/", ",", "''", ")", "value", ".", "gsub!", "(", "/", "\\W", "/", ",", "' '", ")", "value", ".", "strip!", "value", ".", "gsub!", "(", "' '", ",", "'-'", ")", "value", "end" ]
Returns a string which is url compatible.
[ "Returns", "a", "string", "which", "is", "url", "compatible", "." ]
af048361405919605d50fc45e2e1fd0c7eb02703
https://github.com/octopress/octopress/blob/af048361405919605d50fc45e2e1fd0c7eb02703/lib/octopress/page.rb#L212-L221
train
poise/poise-python
lib/poise_python/utils.rb
PoisePython.Utils.module_to_path
def module_to_path(mod, base=nil) path = mod.gsub(/\./, ::File::SEPARATOR) + '.py' path = ::File.join(base, path) if base path end
ruby
def module_to_path(mod, base=nil) path = mod.gsub(/\./, ::File::SEPARATOR) + '.py' path = ::File.join(base, path) if base path end
[ "def", "module_to_path", "(", "mod", ",", "base", "=", "nil", ")", "path", "=", "mod", ".", "gsub", "(", "/", "\\.", "/", ",", "::", "File", "::", "SEPARATOR", ")", "+", "'.py'", "path", "=", "::", "File", ".", "join", "(", "base", ",", "path", ")", "if", "base", "path", "end" ]
Convert a Python dotted module name to a path. @param mod [String] Dotted module name. @param base [String] Optional base path to treat the file as relative to. @return [String]
[ "Convert", "a", "Python", "dotted", "module", "name", "to", "a", "path", "." ]
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/utils.rb#L57-L61
train
socketry/nio4r
lib/nio/selector.rb
NIO.Selector.deregister
def deregister(io) @lock.synchronize do monitor = @selectables.delete IO.try_convert(io) monitor.close(false) if monitor && !monitor.closed? monitor end end
ruby
def deregister(io) @lock.synchronize do monitor = @selectables.delete IO.try_convert(io) monitor.close(false) if monitor && !monitor.closed? monitor end end
[ "def", "deregister", "(", "io", ")", "@lock", ".", "synchronize", "do", "monitor", "=", "@selectables", ".", "delete", "IO", ".", "try_convert", "(", "io", ")", "monitor", ".", "close", "(", "false", ")", "if", "monitor", "&&", "!", "monitor", ".", "closed?", "monitor", "end", "end" ]
Deregister the given IO object from the selector
[ "Deregister", "the", "given", "IO", "object", "from", "the", "selector" ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/selector.rb#L65-L71
train
socketry/nio4r
lib/nio/selector.rb
NIO.Selector.select
def select(timeout = nil) selected_monitors = Set.new @lock.synchronize do readers = [@wakeup] writers = [] @selectables.each do |io, monitor| readers << io if monitor.interests == :r || monitor.interests == :rw writers << io if monitor.interests == :w || monitor.interests == :rw monitor.readiness = nil end ready_readers, ready_writers = Kernel.select(readers, writers, [], timeout) return unless ready_readers # timeout ready_readers.each do |io| if io == @wakeup # Clear all wakeup signals we've received by reading them # Wakeups should have level triggered behavior @wakeup.read(@wakeup.stat.size) else monitor = @selectables[io] monitor.readiness = :r selected_monitors << monitor end end ready_writers.each do |io| monitor = @selectables[io] monitor.readiness = monitor.readiness == :r ? :rw : :w selected_monitors << monitor end end if block_given? selected_monitors.each { |m| yield m } selected_monitors.size else selected_monitors.to_a end end
ruby
def select(timeout = nil) selected_monitors = Set.new @lock.synchronize do readers = [@wakeup] writers = [] @selectables.each do |io, monitor| readers << io if monitor.interests == :r || monitor.interests == :rw writers << io if monitor.interests == :w || monitor.interests == :rw monitor.readiness = nil end ready_readers, ready_writers = Kernel.select(readers, writers, [], timeout) return unless ready_readers # timeout ready_readers.each do |io| if io == @wakeup # Clear all wakeup signals we've received by reading them # Wakeups should have level triggered behavior @wakeup.read(@wakeup.stat.size) else monitor = @selectables[io] monitor.readiness = :r selected_monitors << monitor end end ready_writers.each do |io| monitor = @selectables[io] monitor.readiness = monitor.readiness == :r ? :rw : :w selected_monitors << monitor end end if block_given? selected_monitors.each { |m| yield m } selected_monitors.size else selected_monitors.to_a end end
[ "def", "select", "(", "timeout", "=", "nil", ")", "selected_monitors", "=", "Set", ".", "new", "@lock", ".", "synchronize", "do", "readers", "=", "[", "@wakeup", "]", "writers", "=", "[", "]", "@selectables", ".", "each", "do", "|", "io", ",", "monitor", "|", "readers", "<<", "io", "if", "monitor", ".", "interests", "==", ":r", "||", "monitor", ".", "interests", "==", ":rw", "writers", "<<", "io", "if", "monitor", ".", "interests", "==", ":w", "||", "monitor", ".", "interests", "==", ":rw", "monitor", ".", "readiness", "=", "nil", "end", "ready_readers", ",", "ready_writers", "=", "Kernel", ".", "select", "(", "readers", ",", "writers", ",", "[", "]", ",", "timeout", ")", "return", "unless", "ready_readers", "# timeout", "ready_readers", ".", "each", "do", "|", "io", "|", "if", "io", "==", "@wakeup", "# Clear all wakeup signals we've received by reading them", "# Wakeups should have level triggered behavior", "@wakeup", ".", "read", "(", "@wakeup", ".", "stat", ".", "size", ")", "else", "monitor", "=", "@selectables", "[", "io", "]", "monitor", ".", "readiness", "=", ":r", "selected_monitors", "<<", "monitor", "end", "end", "ready_writers", ".", "each", "do", "|", "io", "|", "monitor", "=", "@selectables", "[", "io", "]", "monitor", ".", "readiness", "=", "monitor", ".", "readiness", "==", ":r", "?", ":rw", ":", ":w", "selected_monitors", "<<", "monitor", "end", "end", "if", "block_given?", "selected_monitors", ".", "each", "{", "|", "m", "|", "yield", "m", "}", "selected_monitors", ".", "size", "else", "selected_monitors", ".", "to_a", "end", "end" ]
Select which monitors are ready
[ "Select", "which", "monitors", "are", "ready" ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/selector.rb#L79-L120
train
socketry/nio4r
lib/nio/bytebuffer.rb
NIO.ByteBuffer.position=
def position=(new_position) raise ArgumentError, "negative position given" if new_position < 0 raise ArgumentError, "specified position exceeds capacity" if new_position > @capacity @mark = nil if @mark && @mark > new_position @position = new_position end
ruby
def position=(new_position) raise ArgumentError, "negative position given" if new_position < 0 raise ArgumentError, "specified position exceeds capacity" if new_position > @capacity @mark = nil if @mark && @mark > new_position @position = new_position end
[ "def", "position", "=", "(", "new_position", ")", "raise", "ArgumentError", ",", "\"negative position given\"", "if", "new_position", "<", "0", "raise", "ArgumentError", ",", "\"specified position exceeds capacity\"", "if", "new_position", ">", "@capacity", "@mark", "=", "nil", "if", "@mark", "&&", "@mark", ">", "new_position", "@position", "=", "new_position", "end" ]
Set the position to the given value. New position must be less than limit. Preserves mark if it's less than the new position, otherwise clears it. @param new_position [Integer] position in the buffer @raise [ArgumentError] new position was invalid
[ "Set", "the", "position", "to", "the", "given", "value", ".", "New", "position", "must", "be", "less", "than", "limit", ".", "Preserves", "mark", "if", "it", "s", "less", "than", "the", "new", "position", "otherwise", "clears", "it", "." ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L47-L53
train
socketry/nio4r
lib/nio/bytebuffer.rb
NIO.ByteBuffer.limit=
def limit=(new_limit) raise ArgumentError, "negative limit given" if new_limit < 0 raise ArgumentError, "specified limit exceeds capacity" if new_limit > @capacity @position = new_limit if @position > new_limit @mark = nil if @mark && @mark > new_limit @limit = new_limit end
ruby
def limit=(new_limit) raise ArgumentError, "negative limit given" if new_limit < 0 raise ArgumentError, "specified limit exceeds capacity" if new_limit > @capacity @position = new_limit if @position > new_limit @mark = nil if @mark && @mark > new_limit @limit = new_limit end
[ "def", "limit", "=", "(", "new_limit", ")", "raise", "ArgumentError", ",", "\"negative limit given\"", "if", "new_limit", "<", "0", "raise", "ArgumentError", ",", "\"specified limit exceeds capacity\"", "if", "new_limit", ">", "@capacity", "@position", "=", "new_limit", "if", "@position", ">", "new_limit", "@mark", "=", "nil", "if", "@mark", "&&", "@mark", ">", "new_limit", "@limit", "=", "new_limit", "end" ]
Set the limit to the given value. New limit must be less than capacity. Preserves limit and mark if they're less than the new limit, otherwise sets position to the new limit and clears the mark. @param new_limit [Integer] position in the buffer @raise [ArgumentError] new limit was invalid
[ "Set", "the", "limit", "to", "the", "given", "value", ".", "New", "limit", "must", "be", "less", "than", "capacity", ".", "Preserves", "limit", "and", "mark", "if", "they", "re", "less", "than", "the", "new", "limit", "otherwise", "sets", "position", "to", "the", "new", "limit", "and", "clears", "the", "mark", "." ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L62-L69
train
socketry/nio4r
lib/nio/bytebuffer.rb
NIO.ByteBuffer.get
def get(length = remaining) raise ArgumentError, "negative length given" if length < 0 raise UnderflowError, "not enough data in buffer" if length > @limit - @position result = @buffer[@position...length] @position += length result end
ruby
def get(length = remaining) raise ArgumentError, "negative length given" if length < 0 raise UnderflowError, "not enough data in buffer" if length > @limit - @position result = @buffer[@position...length] @position += length result end
[ "def", "get", "(", "length", "=", "remaining", ")", "raise", "ArgumentError", ",", "\"negative length given\"", "if", "length", "<", "0", "raise", "UnderflowError", ",", "\"not enough data in buffer\"", "if", "length", ">", "@limit", "-", "@position", "result", "=", "@buffer", "[", "@position", "...", "length", "]", "@position", "+=", "length", "result", "end" ]
Obtain the requested number of bytes from the buffer, advancing the position. If no length is given, all remaining bytes are consumed. @raise [NIO::ByteBuffer::UnderflowError] not enough data remaining in buffer @return [String] bytes read from buffer
[ "Obtain", "the", "requested", "number", "of", "bytes", "from", "the", "buffer", "advancing", "the", "position", ".", "If", "no", "length", "is", "given", "all", "remaining", "bytes", "are", "consumed", "." ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L91-L98
train
socketry/nio4r
lib/nio/bytebuffer.rb
NIO.ByteBuffer.put
def put(str) raise TypeError, "expected String, got #{str.class}" unless str.respond_to?(:to_str) str = str.to_str raise OverflowError, "buffer is full" if str.length > @limit - @position @buffer[@position...str.length] = str @position += str.length self end
ruby
def put(str) raise TypeError, "expected String, got #{str.class}" unless str.respond_to?(:to_str) str = str.to_str raise OverflowError, "buffer is full" if str.length > @limit - @position @buffer[@position...str.length] = str @position += str.length self end
[ "def", "put", "(", "str", ")", "raise", "TypeError", ",", "\"expected String, got #{str.class}\"", "unless", "str", ".", "respond_to?", "(", ":to_str", ")", "str", "=", "str", ".", "to_str", "raise", "OverflowError", ",", "\"buffer is full\"", "if", "str", ".", "length", ">", "@limit", "-", "@position", "@buffer", "[", "@position", "...", "str", ".", "length", "]", "=", "str", "@position", "+=", "str", ".", "length", "self", "end" ]
Add a String to the buffer @param str [#to_str] data to add to the buffer @raise [TypeError] given a non-string type @raise [NIO::ByteBuffer::OverflowError] buffer is full @return [self]
[ "Add", "a", "String", "to", "the", "buffer" ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L120-L128
train
socketry/nio4r
lib/nio/bytebuffer.rb
NIO.ByteBuffer.read_from
def read_from(io) nbytes = @limit - @position raise OverflowError, "buffer is full" if nbytes.zero? bytes_read = IO.try_convert(io).read_nonblock(nbytes, exception: false) return 0 if bytes_read == :wait_readable self << bytes_read bytes_read.length end
ruby
def read_from(io) nbytes = @limit - @position raise OverflowError, "buffer is full" if nbytes.zero? bytes_read = IO.try_convert(io).read_nonblock(nbytes, exception: false) return 0 if bytes_read == :wait_readable self << bytes_read bytes_read.length end
[ "def", "read_from", "(", "io", ")", "nbytes", "=", "@limit", "-", "@position", "raise", "OverflowError", ",", "\"buffer is full\"", "if", "nbytes", ".", "zero?", "bytes_read", "=", "IO", ".", "try_convert", "(", "io", ")", ".", "read_nonblock", "(", "nbytes", ",", "exception", ":", "false", ")", "return", "0", "if", "bytes_read", "==", ":wait_readable", "self", "<<", "bytes_read", "bytes_read", ".", "length", "end" ]
Perform a non-blocking read from the given IO object into the buffer Reads as much data as is immediately available and returns @param [IO] Ruby IO object to read from @return [Integer] number of bytes read (0 if none were available)
[ "Perform", "a", "non", "-", "blocking", "read", "from", "the", "given", "IO", "object", "into", "the", "buffer", "Reads", "as", "much", "data", "as", "is", "immediately", "available", "and", "returns" ]
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L137-L146
train
RubyMoney/eu_central_bank
lib/money/rates_store/store_with_historical_data_support.rb
Money::RatesStore.StoreWithHistoricalDataSupport.transaction
def transaction(force_sync = false, &block) # Ruby 1.9.3 does not support @mutex.owned? if @mutex.respond_to?(:owned?) force_sync = false if @mutex.locked? && @mutex.owned? else # If we allowed this in Ruby 1.9.3, it might possibly cause recursive # locking within the same thread. force_sync = false end if !force_sync && (@in_transaction || options[:without_mutex]) block.call self else @mutex.synchronize do @in_transaction = true result = block.call @in_transaction = false result end end end
ruby
def transaction(force_sync = false, &block) # Ruby 1.9.3 does not support @mutex.owned? if @mutex.respond_to?(:owned?) force_sync = false if @mutex.locked? && @mutex.owned? else # If we allowed this in Ruby 1.9.3, it might possibly cause recursive # locking within the same thread. force_sync = false end if !force_sync && (@in_transaction || options[:without_mutex]) block.call self else @mutex.synchronize do @in_transaction = true result = block.call @in_transaction = false result end end end
[ "def", "transaction", "(", "force_sync", "=", "false", ",", "&", "block", ")", "# Ruby 1.9.3 does not support @mutex.owned?", "if", "@mutex", ".", "respond_to?", "(", ":owned?", ")", "force_sync", "=", "false", "if", "@mutex", ".", "locked?", "&&", "@mutex", ".", "owned?", "else", "# If we allowed this in Ruby 1.9.3, it might possibly cause recursive", "# locking within the same thread.", "force_sync", "=", "false", "end", "if", "!", "force_sync", "&&", "(", "@in_transaction", "||", "options", "[", ":without_mutex", "]", ")", "block", ".", "call", "self", "else", "@mutex", ".", "synchronize", "do", "@in_transaction", "=", "true", "result", "=", "block", ".", "call", "@in_transaction", "=", "false", "result", "end", "end", "end" ]
Wraps block execution in a thread-safe transaction
[ "Wraps", "block", "execution", "in", "a", "thread", "-", "safe", "transaction" ]
63487df637c66f4cce3f04683dba23b423304a5d
https://github.com/RubyMoney/eu_central_bank/blob/63487df637c66f4cce3f04683dba23b423304a5d/lib/money/rates_store/store_with_historical_data_support.rb#L14-L33
train
savonrb/httpi
lib/httpi/request.rb
HTTPI.Request.query=
def query=(query) raise ArgumentError, "Invalid URL: #{self.url}" unless self.url.respond_to?(:query) if query.kind_of?(Hash) query = build_query_from_hash(query) end query = query.to_s unless query.is_a?(String) self.url.query = query end
ruby
def query=(query) raise ArgumentError, "Invalid URL: #{self.url}" unless self.url.respond_to?(:query) if query.kind_of?(Hash) query = build_query_from_hash(query) end query = query.to_s unless query.is_a?(String) self.url.query = query end
[ "def", "query", "=", "(", "query", ")", "raise", "ArgumentError", ",", "\"Invalid URL: #{self.url}\"", "unless", "self", ".", "url", ".", "respond_to?", "(", ":query", ")", "if", "query", ".", "kind_of?", "(", "Hash", ")", "query", "=", "build_query_from_hash", "(", "query", ")", "end", "query", "=", "query", ".", "to_s", "unless", "query", ".", "is_a?", "(", "String", ")", "self", ".", "url", ".", "query", "=", "query", "end" ]
Sets the +query+ from +url+. Raises an +ArgumentError+ unless the +url+ is valid.
[ "Sets", "the", "+", "query", "+", "from", "+", "url", "+", ".", "Raises", "an", "+", "ArgumentError", "+", "unless", "the", "+", "url", "+", "is", "valid", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/request.rb#L35-L42
train
savonrb/httpi
lib/httpi/request.rb
HTTPI.Request.mass_assign
def mass_assign(args) ATTRIBUTES.each { |key| send("#{key}=", args[key]) if args[key] } end
ruby
def mass_assign(args) ATTRIBUTES.each { |key| send("#{key}=", args[key]) if args[key] } end
[ "def", "mass_assign", "(", "args", ")", "ATTRIBUTES", ".", "each", "{", "|", "key", "|", "send", "(", "\"#{key}=\"", ",", "args", "[", "key", "]", ")", "if", "args", "[", "key", "]", "}", "end" ]
Expects a Hash of +args+ to assign.
[ "Expects", "a", "Hash", "of", "+", "args", "+", "to", "assign", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/request.rb#L122-L124
train
savonrb/httpi
lib/httpi/request.rb
HTTPI.Request.normalize_url!
def normalize_url!(url) raise ArgumentError, "Invalid URL: #{url}" unless url.to_s =~ /^http|socks/ url.kind_of?(URI) ? url : URI(url) end
ruby
def normalize_url!(url) raise ArgumentError, "Invalid URL: #{url}" unless url.to_s =~ /^http|socks/ url.kind_of?(URI) ? url : URI(url) end
[ "def", "normalize_url!", "(", "url", ")", "raise", "ArgumentError", ",", "\"Invalid URL: #{url}\"", "unless", "url", ".", "to_s", "=~", "/", "/", "url", ".", "kind_of?", "(", "URI", ")", "?", "url", ":", "URI", "(", "url", ")", "end" ]
Expects a +url+, validates its validity and returns a +URI+ object.
[ "Expects", "a", "+", "url", "+", "validates", "its", "validity", "and", "returns", "a", "+", "URI", "+", "object", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/request.rb#L148-L151
train
savonrb/httpi
lib/httpi/dime.rb
HTTPI.Dime.configure_record
def configure_record(record, bytes) byte = bytes.shift record.version = (byte >> 3) & 31 # 5 bits DIME format version (always 1) record.first = (byte >> 2) & 1 # 1 bit Set if this is the first part in the message record.last = (byte >> 1) & 1 # 1 bit Set if this is the last part in the message record.chunked = byte & 1 # 1 bit This file is broken into chunked parts record.type_format = (bytes.shift >> 4) & 15 # 4 bits Type of file in the part (1 for binary data, 2 for XML) # 4 bits Reserved (skipped in the above command) end
ruby
def configure_record(record, bytes) byte = bytes.shift record.version = (byte >> 3) & 31 # 5 bits DIME format version (always 1) record.first = (byte >> 2) & 1 # 1 bit Set if this is the first part in the message record.last = (byte >> 1) & 1 # 1 bit Set if this is the last part in the message record.chunked = byte & 1 # 1 bit This file is broken into chunked parts record.type_format = (bytes.shift >> 4) & 15 # 4 bits Type of file in the part (1 for binary data, 2 for XML) # 4 bits Reserved (skipped in the above command) end
[ "def", "configure_record", "(", "record", ",", "bytes", ")", "byte", "=", "bytes", ".", "shift", "record", ".", "version", "=", "(", "byte", ">>", "3", ")", "&", "31", "# 5 bits DIME format version (always 1)", "record", ".", "first", "=", "(", "byte", ">>", "2", ")", "&", "1", "# 1 bit Set if this is the first part in the message", "record", ".", "last", "=", "(", "byte", ">>", "1", ")", "&", "1", "# 1 bit Set if this is the last part in the message", "record", ".", "chunked", "=", "byte", "&", "1", "# 1 bit This file is broken into chunked parts", "record", ".", "type_format", "=", "(", "bytes", ".", "shift", ">>", "4", ")", "&", "15", "# 4 bits Type of file in the part (1 for binary data, 2 for XML)", "# 4 bits Reserved (skipped in the above command)", "end" ]
Shift out bitfields for the first fields.
[ "Shift", "out", "bitfields", "for", "the", "first", "fields", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/dime.rb#L29-L38
train
savonrb/httpi
lib/httpi/dime.rb
HTTPI.Dime.big_endian_lengths
def big_endian_lengths(bytes) lengths = [] # we can't use a hash since the order will be screwed in Ruby 1.8 lengths << [:options, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "options" field lengths << [:id, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "ID" or "name" field lengths << [:type, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "type" field lengths << [:data, (bytes.shift << 24) | (bytes.shift << 16) | (bytes.shift << 8) | bytes.shift] # 4 bytes Size of the included file lengths end
ruby
def big_endian_lengths(bytes) lengths = [] # we can't use a hash since the order will be screwed in Ruby 1.8 lengths << [:options, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "options" field lengths << [:id, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "ID" or "name" field lengths << [:type, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "type" field lengths << [:data, (bytes.shift << 24) | (bytes.shift << 16) | (bytes.shift << 8) | bytes.shift] # 4 bytes Size of the included file lengths end
[ "def", "big_endian_lengths", "(", "bytes", ")", "lengths", "=", "[", "]", "# we can't use a hash since the order will be screwed in Ruby 1.8", "lengths", "<<", "[", ":options", ",", "(", "bytes", ".", "shift", "<<", "8", ")", "|", "bytes", ".", "shift", "]", "# 2 bytes Length of the \"options\" field", "lengths", "<<", "[", ":id", ",", "(", "bytes", ".", "shift", "<<", "8", ")", "|", "bytes", ".", "shift", "]", "# 2 bytes Length of the \"ID\" or \"name\" field", "lengths", "<<", "[", ":type", ",", "(", "bytes", ".", "shift", "<<", "8", ")", "|", "bytes", ".", "shift", "]", "# 2 bytes Length of the \"type\" field", "lengths", "<<", "[", ":data", ",", "(", "bytes", ".", "shift", "<<", "24", ")", "|", "(", "bytes", ".", "shift", "<<", "16", ")", "|", "(", "bytes", ".", "shift", "<<", "8", ")", "|", "bytes", ".", "shift", "]", "# 4 bytes Size of the included file", "lengths", "end" ]
Fetch big-endian lengths.
[ "Fetch", "big", "-", "endian", "lengths", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/dime.rb#L41-L48
train
savonrb/httpi
lib/httpi/dime.rb
HTTPI.Dime.read_data
def read_data(record, bytes, attribute_set) attribute, length = attribute_set content = bytes.slice!(0, length).pack('C*') if attribute == :data && record.type_format == BINARY content = StringIO.new(content) end record.send "#{attribute.to_s}=", content bytes.slice!(0, 4 - (length & 3)) if (length & 3) != 0 end
ruby
def read_data(record, bytes, attribute_set) attribute, length = attribute_set content = bytes.slice!(0, length).pack('C*') if attribute == :data && record.type_format == BINARY content = StringIO.new(content) end record.send "#{attribute.to_s}=", content bytes.slice!(0, 4 - (length & 3)) if (length & 3) != 0 end
[ "def", "read_data", "(", "record", ",", "bytes", ",", "attribute_set", ")", "attribute", ",", "length", "=", "attribute_set", "content", "=", "bytes", ".", "slice!", "(", "0", ",", "length", ")", ".", "pack", "(", "'C*'", ")", "if", "attribute", "==", ":data", "&&", "record", ".", "type_format", "==", "BINARY", "content", "=", "StringIO", ".", "new", "(", "content", ")", "end", "record", ".", "send", "\"#{attribute.to_s}=\"", ",", "content", "bytes", ".", "slice!", "(", "0", ",", "4", "-", "(", "length", "&", "3", ")", ")", "if", "(", "length", "&", "3", ")", "!=", "0", "end" ]
Read in padded data.
[ "Read", "in", "padded", "data", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/dime.rb#L51-L61
train
savonrb/httpi
lib/httpi/response.rb
HTTPI.Response.decoded_gzip_body
def decoded_gzip_body unless gzip = Zlib::GzipReader.new(StringIO.new(raw_body)) raise ArgumentError, "Unable to create Zlib::GzipReader" end gzip.read ensure gzip.close if gzip end
ruby
def decoded_gzip_body unless gzip = Zlib::GzipReader.new(StringIO.new(raw_body)) raise ArgumentError, "Unable to create Zlib::GzipReader" end gzip.read ensure gzip.close if gzip end
[ "def", "decoded_gzip_body", "unless", "gzip", "=", "Zlib", "::", "GzipReader", ".", "new", "(", "StringIO", ".", "new", "(", "raw_body", ")", ")", "raise", "ArgumentError", ",", "\"Unable to create Zlib::GzipReader\"", "end", "gzip", ".", "read", "ensure", "gzip", ".", "close", "if", "gzip", "end" ]
Returns the gzip decoded response body.
[ "Returns", "the", "gzip", "decoded", "response", "body", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/response.rb#L81-L88
train
savonrb/httpi
lib/httpi/response.rb
HTTPI.Response.decoded_dime_body
def decoded_dime_body(body = nil) dime = Dime.new(body || raw_body) self.attachments = dime.binary_records dime.xml_records.first.data end
ruby
def decoded_dime_body(body = nil) dime = Dime.new(body || raw_body) self.attachments = dime.binary_records dime.xml_records.first.data end
[ "def", "decoded_dime_body", "(", "body", "=", "nil", ")", "dime", "=", "Dime", ".", "new", "(", "body", "||", "raw_body", ")", "self", ".", "attachments", "=", "dime", ".", "binary_records", "dime", ".", "xml_records", ".", "first", ".", "data", "end" ]
Returns the DIME decoded response body.
[ "Returns", "the", "DIME", "decoded", "response", "body", "." ]
2fbd6b14a0a04ed21572251580a9a4c987396e4b
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/response.rb#L91-L95
train
adhearsion/adhearsion
lib/adhearsion/initializer.rb
Adhearsion.Initializer.load_lib_folder
def load_lib_folder return false if Adhearsion.config.core.lib.nil? lib_folder = [Adhearsion.config.core.root, Adhearsion.config.core.lib].join '/' return false unless File.directory? lib_folder $LOAD_PATH.unshift lib_folder Dir.chdir lib_folder do rbfiles = File.join "**", "*.rb" Dir.glob(rbfiles).each do |file| require "#{lib_folder}/#{file}" end end true end
ruby
def load_lib_folder return false if Adhearsion.config.core.lib.nil? lib_folder = [Adhearsion.config.core.root, Adhearsion.config.core.lib].join '/' return false unless File.directory? lib_folder $LOAD_PATH.unshift lib_folder Dir.chdir lib_folder do rbfiles = File.join "**", "*.rb" Dir.glob(rbfiles).each do |file| require "#{lib_folder}/#{file}" end end true end
[ "def", "load_lib_folder", "return", "false", "if", "Adhearsion", ".", "config", ".", "core", ".", "lib", ".", "nil?", "lib_folder", "=", "[", "Adhearsion", ".", "config", ".", "core", ".", "root", ",", "Adhearsion", ".", "config", ".", "core", ".", "lib", "]", ".", "join", "'/'", "return", "false", "unless", "File", ".", "directory?", "lib_folder", "$LOAD_PATH", ".", "unshift", "lib_folder", "Dir", ".", "chdir", "lib_folder", "do", "rbfiles", "=", "File", ".", "join", "\"**\"", ",", "\"*.rb\"", "Dir", ".", "glob", "(", "rbfiles", ")", ".", "each", "do", "|", "file", "|", "require", "\"#{lib_folder}/#{file}\"", "end", "end", "true", "end" ]
Loads files in application lib folder @return [Boolean] if files have been loaded (lib folder is configured to not nil and actually exists)
[ "Loads", "files", "in", "application", "lib", "folder" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/initializer.rb#L129-L144
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.tag
def tag(label) abort ArgumentError.new "Tag must be a String or Symbol" unless [String, Symbol].include?(label.class) @tags << label end
ruby
def tag(label) abort ArgumentError.new "Tag must be a String or Symbol" unless [String, Symbol].include?(label.class) @tags << label end
[ "def", "tag", "(", "label", ")", "abort", "ArgumentError", ".", "new", "\"Tag must be a String or Symbol\"", "unless", "[", "String", ",", "Symbol", "]", ".", "include?", "(", "label", ".", "class", ")", "@tags", "<<", "label", "end" ]
Tag a call with an arbitrary label @param [String, Symbol] label String or Symbol with which to tag this call
[ "Tag", "a", "call", "with", "an", "arbitrary", "label" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L139-L142
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.wait_for_end
def wait_for_end(timeout = nil) if end_reason end_reason else @end_blocker.wait(timeout) end rescue Celluloid::ConditionError => e abort e end
ruby
def wait_for_end(timeout = nil) if end_reason end_reason else @end_blocker.wait(timeout) end rescue Celluloid::ConditionError => e abort e end
[ "def", "wait_for_end", "(", "timeout", "=", "nil", ")", "if", "end_reason", "end_reason", "else", "@end_blocker", ".", "wait", "(", "timeout", ")", "end", "rescue", "Celluloid", "::", "ConditionError", "=>", "e", "abort", "e", "end" ]
Wait for the call to end. Returns immediately if the call has already ended, else blocks until it does so. @param [Integer, nil] timeout a timeout after which to unblock, returning `:timeout` @return [Symbol] the reason for the call ending @raises [Celluloid::ConditionError] in case of a specified timeout expiring
[ "Wait", "for", "the", "call", "to", "end", ".", "Returns", "immediately", "if", "the", "call", "has", "already", "ended", "else", "blocks", "until", "it", "does", "so", "." ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L176-L184
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.on_joined
def on_joined(target = nil, &block) register_event_handler Adhearsion::Event::Joined, *guards_for_target(target) do |event| block.call event end end
ruby
def on_joined(target = nil, &block) register_event_handler Adhearsion::Event::Joined, *guards_for_target(target) do |event| block.call event end end
[ "def", "on_joined", "(", "target", "=", "nil", ",", "&", "block", ")", "register_event_handler", "Adhearsion", "::", "Event", "::", "Joined", ",", "guards_for_target", "(", "target", ")", "do", "|", "event", "|", "block", ".", "call", "event", "end", "end" ]
Registers a callback for when this call is joined to another call or a mixer @param [Call, String, Hash, nil] target the target to guard on. May be a Call object, a call ID (String, Hash) or a mixer name (Hash) @option target [String] call_uri The call ID to guard on @option target [String] mixer_name The mixer name to guard on
[ "Registers", "a", "callback", "for", "when", "this", "call", "is", "joined", "to", "another", "call", "or", "a", "mixer" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L287-L291
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.on_unjoined
def on_unjoined(target = nil, &block) register_event_handler Adhearsion::Event::Unjoined, *guards_for_target(target), &block end
ruby
def on_unjoined(target = nil, &block) register_event_handler Adhearsion::Event::Unjoined, *guards_for_target(target), &block end
[ "def", "on_unjoined", "(", "target", "=", "nil", ",", "&", "block", ")", "register_event_handler", "Adhearsion", "::", "Event", "::", "Unjoined", ",", "guards_for_target", "(", "target", ")", ",", "block", "end" ]
Registers a callback for when this call is unjoined from another call or a mixer @param [Call, String, Hash, nil] target the target to guard on. May be a Call object, a call ID (String, Hash) or a mixer name (Hash) @option target [String] call_uri The call ID to guard on @option target [String] mixer_name The mixer name to guard on
[ "Registers", "a", "callback", "for", "when", "this", "call", "is", "unjoined", "from", "another", "call", "or", "a", "mixer" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L300-L302
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.redirect
def redirect(to, headers = nil) write_and_await_response Adhearsion::Rayo::Command::Redirect.new(to: to, headers: headers) rescue Adhearsion::ProtocolError => e abort e end
ruby
def redirect(to, headers = nil) write_and_await_response Adhearsion::Rayo::Command::Redirect.new(to: to, headers: headers) rescue Adhearsion::ProtocolError => e abort e end
[ "def", "redirect", "(", "to", ",", "headers", "=", "nil", ")", "write_and_await_response", "Adhearsion", "::", "Rayo", "::", "Command", "::", "Redirect", ".", "new", "(", "to", ":", "to", ",", "headers", ":", "headers", ")", "rescue", "Adhearsion", "::", "ProtocolError", "=>", "e", "abort", "e", "end" ]
Redirect the call to some other target system. If the redirect is successful, the call will be released from the telephony engine and Adhearsion will lose control of the call. Note that for the common case, this will result in a SIP 302 or SIP REFER, which provides the caller with a new URI to dial. As such, the redirect target cannot be any telephony-engine specific address (such as sofia/gateway, agent/101, or SIP/mypeer); instead it should be a fully-qualified external SIP URI that the caller can independently reach. @param [String] to the target to redirect to, eg a SIP URI @param [Hash, optional] headers a set of headers to send along with the redirect instruction
[ "Redirect", "the", "call", "to", "some", "other", "target", "system", "." ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L354-L358
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.join
def join(target, options = {}) logger.debug "Joining to #{target}" joined_condition = CountDownLatch.new(1) on_joined target do joined_condition.countdown! end unjoined_condition = CountDownLatch.new(1) on_unjoined target do unjoined_condition.countdown! end on_end do joined_condition.countdown! unjoined_condition.countdown! end command = Adhearsion::Rayo::Command::Join.new options.merge(join_options_with_target(target)) write_and_await_response command {command: command, joined_condition: joined_condition, unjoined_condition: unjoined_condition} rescue Adhearsion::ProtocolError => e abort e end
ruby
def join(target, options = {}) logger.debug "Joining to #{target}" joined_condition = CountDownLatch.new(1) on_joined target do joined_condition.countdown! end unjoined_condition = CountDownLatch.new(1) on_unjoined target do unjoined_condition.countdown! end on_end do joined_condition.countdown! unjoined_condition.countdown! end command = Adhearsion::Rayo::Command::Join.new options.merge(join_options_with_target(target)) write_and_await_response command {command: command, joined_condition: joined_condition, unjoined_condition: unjoined_condition} rescue Adhearsion::ProtocolError => e abort e end
[ "def", "join", "(", "target", ",", "options", "=", "{", "}", ")", "logger", ".", "debug", "\"Joining to #{target}\"", "joined_condition", "=", "CountDownLatch", ".", "new", "(", "1", ")", "on_joined", "target", "do", "joined_condition", ".", "countdown!", "end", "unjoined_condition", "=", "CountDownLatch", ".", "new", "(", "1", ")", "on_unjoined", "target", "do", "unjoined_condition", ".", "countdown!", "end", "on_end", "do", "joined_condition", ".", "countdown!", "unjoined_condition", ".", "countdown!", "end", "command", "=", "Adhearsion", "::", "Rayo", "::", "Command", "::", "Join", ".", "new", "options", ".", "merge", "(", "join_options_with_target", "(", "target", ")", ")", "write_and_await_response", "command", "{", "command", ":", "command", ",", "joined_condition", ":", "joined_condition", ",", "unjoined_condition", ":", "unjoined_condition", "}", "rescue", "Adhearsion", "::", "ProtocolError", "=>", "e", "abort", "e", "end" ]
Joins this call to another call or a mixer @param [Call, String, Hash] target the target to join to. May be a Call object, a call ID (String, Hash) or a mixer name (Hash) @option target [String] call_uri The call ID to join to @option target [String] mixer_name The mixer to join to @param [Hash, Optional] options further options to be joined with @return [Hash] where :command is the issued command, :joined_waiter is a #wait responder which is triggered when the join is complete, and :unjoined_waiter is a #wait responder which is triggered when the entities are unjoined
[ "Joins", "this", "call", "to", "another", "call", "or", "a", "mixer" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L384-L407
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.unjoin
def unjoin(target = nil) logger.info "Unjoining from #{target}" command = Adhearsion::Rayo::Command::Unjoin.new join_options_with_target(target) write_and_await_response command rescue Adhearsion::ProtocolError => e abort e end
ruby
def unjoin(target = nil) logger.info "Unjoining from #{target}" command = Adhearsion::Rayo::Command::Unjoin.new join_options_with_target(target) write_and_await_response command rescue Adhearsion::ProtocolError => e abort e end
[ "def", "unjoin", "(", "target", "=", "nil", ")", "logger", ".", "info", "\"Unjoining from #{target}\"", "command", "=", "Adhearsion", "::", "Rayo", "::", "Command", "::", "Unjoin", ".", "new", "join_options_with_target", "(", "target", ")", "write_and_await_response", "command", "rescue", "Adhearsion", "::", "ProtocolError", "=>", "e", "abort", "e", "end" ]
Unjoins this call from another call or a mixer @param [Call, String, Hash, nil] target the target to unjoin from. May be a Call object, a call ID (String, Hash), a mixer name (Hash) or missing to unjoin from every existing join (nil) @option target [String] call_uri The call ID to unjoin from @option target [String] mixer_name The mixer to unjoin from
[ "Unjoins", "this", "call", "from", "another", "call", "or", "a", "mixer" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L416-L422
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.send_message
def send_message(body, options = {}) logger.debug "Sending message: #{body}" client.send_message id, domain, body, options end
ruby
def send_message(body, options = {}) logger.debug "Sending message: #{body}" client.send_message id, domain, body, options end
[ "def", "send_message", "(", "body", ",", "options", "=", "{", "}", ")", "logger", ".", "debug", "\"Sending message: #{body}\"", "client", ".", "send_message", "id", ",", "domain", ",", "body", ",", "options", "end" ]
Sends a message to the caller @param [String] body The message text. @param [Hash, Optional] options The message options. @option options [String] subject The message subject.
[ "Sends", "a", "message", "to", "the", "caller" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L535-L538
train
adhearsion/adhearsion
lib/adhearsion/call.rb
Adhearsion.Call.execute_controller
def execute_controller(controller = nil, completion_callback = nil, &block) raise ArgumentError, "Cannot supply a controller and a block at the same time" if controller && block_given? controller ||= CallController.new current_actor, &block logger.info "Executing controller #{controller.class}" controller.bg_exec completion_callback end
ruby
def execute_controller(controller = nil, completion_callback = nil, &block) raise ArgumentError, "Cannot supply a controller and a block at the same time" if controller && block_given? controller ||= CallController.new current_actor, &block logger.info "Executing controller #{controller.class}" controller.bg_exec completion_callback end
[ "def", "execute_controller", "(", "controller", "=", "nil", ",", "completion_callback", "=", "nil", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\"Cannot supply a controller and a block at the same time\"", "if", "controller", "&&", "block_given?", "controller", "||=", "CallController", ".", "new", "current_actor", ",", "block", "logger", ".", "info", "\"Executing controller #{controller.class}\"", "controller", ".", "bg_exec", "completion_callback", "end" ]
Execute a call controller asynchronously against this call. To block and wait until the controller completes, call `#join` on the result of this method. @param [Adhearsion::CallController] controller an instance of a controller initialized for this call @param [Proc] a callback to be executed when the controller finishes execution @yield execute the current block as the body of a controller by specifying no controller instance @return [Celluloid::ThreadHandle]
[ "Execute", "a", "call", "controller", "asynchronously", "against", "this", "call", "." ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L565-L570
train
adhearsion/adhearsion
lib/adhearsion/statistics.rb
Adhearsion.Statistics.dump
def dump Dump.new timestamp: Time.now, call_counts: dump_call_counts, calls_by_route: dump_calls_by_route end
ruby
def dump Dump.new timestamp: Time.now, call_counts: dump_call_counts, calls_by_route: dump_calls_by_route end
[ "def", "dump", "Dump", ".", "new", "timestamp", ":", "Time", ".", "now", ",", "call_counts", ":", "dump_call_counts", ",", "calls_by_route", ":", "dump_calls_by_route", "end" ]
Create a point-time dump of process statistics @return [Adhearsion::Statistics::Dump]
[ "Create", "a", "point", "-", "time", "dump", "of", "process", "statistics" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/statistics.rb#L53-L55
train
adhearsion/adhearsion
lib/adhearsion/call_controller.rb
Adhearsion.CallController.invoke
def invoke(controller_class, metadata = nil) controller = controller_class.new call, metadata controller.run end
ruby
def invoke(controller_class, metadata = nil) controller = controller_class.new call, metadata controller.run end
[ "def", "invoke", "(", "controller_class", ",", "metadata", "=", "nil", ")", "controller", "=", "controller_class", ".", "new", "call", ",", "metadata", "controller", ".", "run", "end" ]
Invoke another controller class within this controller, returning to this context on completion. @param [Class] controller_class The class of controller to execute @param [Hash] metadata generic key-value storage applicable to the controller @return The return value of the controller's run method
[ "Invoke", "another", "controller", "class", "within", "this", "controller", "returning", "to", "this", "context", "on", "completion", "." ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call_controller.rb#L151-L154
train
adhearsion/adhearsion
lib/adhearsion/call_controller.rb
Adhearsion.CallController.stop_all_components
def stop_all_components logger.info "Stopping all controller components" @active_components.each do |component| begin component.stop! rescue Adhearsion::Rayo::Component::InvalidActionError end end end
ruby
def stop_all_components logger.info "Stopping all controller components" @active_components.each do |component| begin component.stop! rescue Adhearsion::Rayo::Component::InvalidActionError end end end
[ "def", "stop_all_components", "logger", ".", "info", "\"Stopping all controller components\"", "@active_components", ".", "each", "do", "|", "component", "|", "begin", "component", ".", "stop!", "rescue", "Adhearsion", "::", "Rayo", "::", "Component", "::", "InvalidActionError", "end", "end", "end" ]
Stop execution of all the components currently running in the controller.
[ "Stop", "execution", "of", "all", "the", "components", "currently", "running", "in", "the", "controller", "." ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call_controller.rb#L169-L177
train
adhearsion/adhearsion
lib/adhearsion/configuration.rb
Adhearsion.Configuration.method_missing
def method_missing(method_name, *args, &block) config = Loquacious::Configuration.for method_name, &block raise Adhearsion::Configuration::ConfigurationError.new "Invalid plugin #{method_name}" if config.nil? config end
ruby
def method_missing(method_name, *args, &block) config = Loquacious::Configuration.for method_name, &block raise Adhearsion::Configuration::ConfigurationError.new "Invalid plugin #{method_name}" if config.nil? config end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "config", "=", "Loquacious", "::", "Configuration", ".", "for", "method_name", ",", "block", "raise", "Adhearsion", "::", "Configuration", "::", "ConfigurationError", ".", "new", "\"Invalid plugin #{method_name}\"", "if", "config", ".", "nil?", "config", "end" ]
Wrapper to access to a specific configuration object Adhearsion.config.foo => returns the configuration object associated to the foo plugin
[ "Wrapper", "to", "access", "to", "a", "specific", "configuration", "object" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/configuration.rb#L147-L151
train
adhearsion/adhearsion
lib/adhearsion/console.rb
Adhearsion.Console.run
def run if jruby? || cruby_with_readline? set_prompt Pry.config.command_prefix = "%" logger.info "Launching Adhearsion Console" @pry_thread = Thread.current pry logger.info "Adhearsion Console exiting" else logger.error "Unable to launch Adhearsion Console: This version of Ruby is using libedit. You must use readline for the console to work." end end
ruby
def run if jruby? || cruby_with_readline? set_prompt Pry.config.command_prefix = "%" logger.info "Launching Adhearsion Console" @pry_thread = Thread.current pry logger.info "Adhearsion Console exiting" else logger.error "Unable to launch Adhearsion Console: This version of Ruby is using libedit. You must use readline for the console to work." end end
[ "def", "run", "if", "jruby?", "||", "cruby_with_readline?", "set_prompt", "Pry", ".", "config", ".", "command_prefix", "=", "\"%\"", "logger", ".", "info", "\"Launching Adhearsion Console\"", "@pry_thread", "=", "Thread", ".", "current", "pry", "logger", ".", "info", "\"Adhearsion Console exiting\"", "else", "logger", ".", "error", "\"Unable to launch Adhearsion Console: This version of Ruby is using libedit. You must use readline for the console to work.\"", "end", "end" ]
Start the Adhearsion console
[ "Start", "the", "Adhearsion", "console" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/console.rb#L33-L44
train
adhearsion/adhearsion
lib/adhearsion/outbound_call.rb
Adhearsion.OutboundCall.dial
def dial(to, options = {}) options = options.dup options[:to] = to if options[:timeout] wait_timeout = options[:timeout] options[:timeout] = options[:timeout] * 1000 else wait_timeout = 60 end uri = client.new_call_uri options[:uri] = uri @dial_command = Adhearsion::Rayo::Command::Dial.new(options) ref = Adhearsion::Rayo::Ref.new uri: uri @transport = ref.scheme @id = ref.call_id @domain = ref.domain Adhearsion.active_calls << current_actor write_and_await_response(@dial_command, wait_timeout, true).tap do |dial_command| @start_time = dial_command.timestamp.to_time if @dial_command.uri != self.uri logger.warn "Requested call URI (#{uri}) was not respected. Tracking by new URI #{self.uri}. This might cause a race in event handling, please upgrade your Rayo server." Adhearsion.active_calls << current_actor Adhearsion.active_calls.delete(@id) end Adhearsion::Events.trigger :call_dialed, current_actor end rescue clear_from_active_calls raise end
ruby
def dial(to, options = {}) options = options.dup options[:to] = to if options[:timeout] wait_timeout = options[:timeout] options[:timeout] = options[:timeout] * 1000 else wait_timeout = 60 end uri = client.new_call_uri options[:uri] = uri @dial_command = Adhearsion::Rayo::Command::Dial.new(options) ref = Adhearsion::Rayo::Ref.new uri: uri @transport = ref.scheme @id = ref.call_id @domain = ref.domain Adhearsion.active_calls << current_actor write_and_await_response(@dial_command, wait_timeout, true).tap do |dial_command| @start_time = dial_command.timestamp.to_time if @dial_command.uri != self.uri logger.warn "Requested call URI (#{uri}) was not respected. Tracking by new URI #{self.uri}. This might cause a race in event handling, please upgrade your Rayo server." Adhearsion.active_calls << current_actor Adhearsion.active_calls.delete(@id) end Adhearsion::Events.trigger :call_dialed, current_actor end rescue clear_from_active_calls raise end
[ "def", "dial", "(", "to", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "options", "[", ":to", "]", "=", "to", "if", "options", "[", ":timeout", "]", "wait_timeout", "=", "options", "[", ":timeout", "]", "options", "[", ":timeout", "]", "=", "options", "[", ":timeout", "]", "*", "1000", "else", "wait_timeout", "=", "60", "end", "uri", "=", "client", ".", "new_call_uri", "options", "[", ":uri", "]", "=", "uri", "@dial_command", "=", "Adhearsion", "::", "Rayo", "::", "Command", "::", "Dial", ".", "new", "(", "options", ")", "ref", "=", "Adhearsion", "::", "Rayo", "::", "Ref", ".", "new", "uri", ":", "uri", "@transport", "=", "ref", ".", "scheme", "@id", "=", "ref", ".", "call_id", "@domain", "=", "ref", ".", "domain", "Adhearsion", ".", "active_calls", "<<", "current_actor", "write_and_await_response", "(", "@dial_command", ",", "wait_timeout", ",", "true", ")", ".", "tap", "do", "|", "dial_command", "|", "@start_time", "=", "dial_command", ".", "timestamp", ".", "to_time", "if", "@dial_command", ".", "uri", "!=", "self", ".", "uri", "logger", ".", "warn", "\"Requested call URI (#{uri}) was not respected. Tracking by new URI #{self.uri}. This might cause a race in event handling, please upgrade your Rayo server.\"", "Adhearsion", ".", "active_calls", "<<", "current_actor", "Adhearsion", ".", "active_calls", ".", "delete", "(", "@id", ")", "end", "Adhearsion", "::", "Events", ".", "trigger", ":call_dialed", ",", "current_actor", "end", "rescue", "clear_from_active_calls", "raise", "end" ]
Dial out an existing outbound call @param [String] to the URI of the party to dial @param [Hash] options modifier options @option options [String, Optional] :from what to set the Caller ID to @option options [Integer, Optional] :timeout in seconds @option options [Hash, Optional] :headers SIP headers to attach to the new call.
[ "Dial", "out", "an", "existing", "outbound", "call" ]
73beca70000671fa89dfc056e8c62bd839c5417a
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/outbound_call.rb#L74-L108
train