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
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.drop_while
def drop_while(&block) raise Erlang::ImproperListError if improper? return enum_for(:drop_while) unless block_given? list = self list = list.tail while !list.empty? && yield(list.head) return list end
ruby
def drop_while(&block) raise Erlang::ImproperListError if improper? return enum_for(:drop_while) unless block_given? list = self list = list.tail while !list.empty? && yield(list.head) return list end
[ "def", "drop_while", "(", "&", "block", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "enum_for", "(", ":drop_while", ")", "unless", "block_given?", "list", "=", "self", "list", "=", "list", ".", "tail", "while", "!", "list", ".", "empty?", "&&", "yield", "(", "list", ".", "head", ")", "return", "list", "end" ]
Return a `List` which contains all elements starting from the first element for which the block returns `nil` or `false`. @example Erlang::List[1, 3, 5, 7, 6, 4, 2].drop_while { |e| e < 5 } # => Erlang::List[5, 7, 6, 4, 2] @return [List, Enumerator] @yield [item]
[ "Return", "a", "List", "which", "contains", "all", "elements", "starting", "from", "the", "first", "element", "for", "which", "the", "block", "returns", "nil", "or", "false", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L317-L323
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.pop
def pop raise Erlang::ImproperListError if improper? return self if empty? new_size = size - 1 return Erlang::List.new(head, tail.take(new_size - 1)) if new_size >= 1 return Erlang::Nil end
ruby
def pop raise Erlang::ImproperListError if improper? return self if empty? new_size = size - 1 return Erlang::List.new(head, tail.take(new_size - 1)) if new_size >= 1 return Erlang::Nil end
[ "def", "pop", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "self", "if", "empty?", "new_size", "=", "size", "-", "1", "return", "Erlang", "::", "List", ".", "new", "(", "head", ",", "tail", ".", "take", "(", "new_size", "-", "1", ")", ")", "if", "new_size", ">=", "1", "return", "Erlang", "::", "Nil", "end" ]
Return a `List` containing all but the last item from this `List`. @example Erlang::List["A", "B", "C"].pop # => Erlang::List["A", "B"] @return [List]
[ "Return", "a", "List", "containing", "all", "but", "the", "last", "item", "from", "this", "List", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L363-L369
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.drop
def drop(number) raise Erlang::ImproperListError if improper? list = self while !list.empty? && number > 0 number -= 1 list = list.tail end return list end
ruby
def drop(number) raise Erlang::ImproperListError if improper? list = self while !list.empty? && number > 0 number -= 1 list = list.tail end return list end
[ "def", "drop", "(", "number", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "list", "=", "self", "while", "!", "list", ".", "empty?", "&&", "number", ">", "0", "number", "-=", "1", "list", "=", "list", ".", "tail", "end", "return", "list", "end" ]
Return a `List` containing all items after the first `number` items from this `List`. @example Erlang::List[1, 3, 5, 7, 6, 4, 2].drop(3) # => Erlang::List[7, 6, 4, 2] @param number [Integer] The number of items to skip over @return [List]
[ "Return", "a", "List", "containing", "all", "items", "after", "the", "first", "number", "items", "from", "this", "List", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L380-L388
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.append
def append(other) # raise Erlang::ImproperListError if improper? other = Erlang.from(other) return self if not improper? and Erlang.is_list(other) and other.empty? return other if Erlang.is_list(other) and empty? is_improper = Erlang.is_list(other) ? other.improper? : true out = tail = Erlang::Cons.allocate list = self until list.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, is_improper) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, is_improper) tail.immutable! tail = new_node if not Erlang.is_list(list.tail) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.tail) new_node.instance_variable_set(:@improper, is_improper) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, is_improper) tail.immutable! tail = new_node list = Erlang::Nil else list = list.tail end end if not tail.immutable? tail.instance_variable_set(:@tail, other) tail.immutable! end return out.tail end
ruby
def append(other) # raise Erlang::ImproperListError if improper? other = Erlang.from(other) return self if not improper? and Erlang.is_list(other) and other.empty? return other if Erlang.is_list(other) and empty? is_improper = Erlang.is_list(other) ? other.improper? : true out = tail = Erlang::Cons.allocate list = self until list.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, is_improper) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, is_improper) tail.immutable! tail = new_node if not Erlang.is_list(list.tail) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.tail) new_node.instance_variable_set(:@improper, is_improper) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, is_improper) tail.immutable! tail = new_node list = Erlang::Nil else list = list.tail end end if not tail.immutable? tail.instance_variable_set(:@tail, other) tail.immutable! end return out.tail end
[ "def", "append", "(", "other", ")", "other", "=", "Erlang", ".", "from", "(", "other", ")", "return", "self", "if", "not", "improper?", "and", "Erlang", ".", "is_list", "(", "other", ")", "and", "other", ".", "empty?", "return", "other", "if", "Erlang", ".", "is_list", "(", "other", ")", "and", "empty?", "is_improper", "=", "Erlang", ".", "is_list", "(", "other", ")", "?", "other", ".", "improper?", ":", "true", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "empty?", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "is_improper", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "is_improper", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "if", "not", "Erlang", ".", "is_list", "(", "list", ".", "tail", ")", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "tail", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "is_improper", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "is_improper", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "list", "=", "Erlang", "::", "Nil", "else", "list", "=", "list", ".", "tail", "end", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "other", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end" ]
Return a `List` with all items from this `List`, followed by all items from `other`. @example Erlang::List[1, 2, 3].append(Erlang::List[4, 5]) # => Erlang::List[1, 2, 3, 4, 5] @param other [List] The list to add onto the end of this one @return [List]
[ "Return", "a", "List", "with", "all", "items", "from", "this", "List", "followed", "by", "all", "items", "from", "other", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L399-L433
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.transpose
def transpose raise Erlang::ImproperListError if improper? return Erlang::Nil if empty? return Erlang::Nil if any? { |list| list.empty? } heads, tails = Erlang::Nil, Erlang::Nil reverse_each { |list| heads, tails = heads.cons(list.head), tails.cons(list.tail) } return Erlang::Cons.new(heads, tails.transpose) end
ruby
def transpose raise Erlang::ImproperListError if improper? return Erlang::Nil if empty? return Erlang::Nil if any? { |list| list.empty? } heads, tails = Erlang::Nil, Erlang::Nil reverse_each { |list| heads, tails = heads.cons(list.head), tails.cons(list.tail) } return Erlang::Cons.new(heads, tails.transpose) end
[ "def", "transpose", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "Erlang", "::", "Nil", "if", "empty?", "return", "Erlang", "::", "Nil", "if", "any?", "{", "|", "list", "|", "list", ".", "empty?", "}", "heads", ",", "tails", "=", "Erlang", "::", "Nil", ",", "Erlang", "::", "Nil", "reverse_each", "{", "|", "list", "|", "heads", ",", "tails", "=", "heads", ".", "cons", "(", "list", ".", "head", ")", ",", "tails", ".", "cons", "(", "list", ".", "tail", ")", "}", "return", "Erlang", "::", "Cons", ".", "new", "(", "heads", ",", "tails", ".", "transpose", ")", "end" ]
Gather the first element of each nested list into a new `List`, then the second element of each nested list, then the third, and so on. In other words, if each nested list is a "row", return a `List` of "columns" instead. @return [List]
[ "Gather", "the", "first", "element", "of", "each", "nested", "list", "into", "a", "new", "List", "then", "the", "second", "element", "of", "each", "nested", "list", "then", "the", "third", "and", "so", "on", ".", "In", "other", "words", "if", "each", "nested", "list", "is", "a", "row", "return", "a", "List", "of", "columns", "instead", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L490-L497
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.rotate
def rotate(count = 1) raise Erlang::ImproperListError if improper? raise TypeError, "expected Integer" if not count.is_a?(Integer) return self if empty? || (count % size) == 0 count = (count >= 0) ? count % size : (size - (~count % size) - 1) return drop(count).append(take(count)) end
ruby
def rotate(count = 1) raise Erlang::ImproperListError if improper? raise TypeError, "expected Integer" if not count.is_a?(Integer) return self if empty? || (count % size) == 0 count = (count >= 0) ? count % size : (size - (~count % size) - 1) return drop(count).append(take(count)) end
[ "def", "rotate", "(", "count", "=", "1", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "raise", "TypeError", ",", "\"expected Integer\"", "if", "not", "count", ".", "is_a?", "(", "Integer", ")", "return", "self", "if", "empty?", "||", "(", "count", "%", "size", ")", "==", "0", "count", "=", "(", "count", ">=", "0", ")", "?", "count", "%", "size", ":", "(", "size", "-", "(", "~", "count", "%", "size", ")", "-", "1", ")", "return", "drop", "(", "count", ")", ".", "append", "(", "take", "(", "count", ")", ")", "end" ]
Return a new `List` with the same elements, but rotated so that the one at index `count` is the first element of the new list. If `count` is positive, the elements will be shifted left, and those shifted past the lowest position will be moved to the end. If `count` is negative, the elements will be shifted right, and those shifted past the last position will be moved to the beginning. @example l = Erlang::List["A", "B", "C", "D", "E", "F"] l.rotate(2) # => Erlang::List["C", "D", "E", "F", "A", "B"] l.rotate(-1) # => Erlang::List["F", "A", "B", "C", "D", "E"] @param count [Integer] The number of positions to shift items by @return [List] @raise [TypeError] if count is not an integer.
[ "Return", "a", "new", "List", "with", "the", "same", "elements", "but", "rotated", "so", "that", "the", "one", "at", "index", "count", "is", "the", "first", "element", "of", "the", "new", "list", ".", "If", "count", "is", "positive", "the", "elements", "will", "be", "shifted", "left", "and", "those", "shifted", "past", "the", "lowest", "position", "will", "be", "moved", "to", "the", "end", ".", "If", "count", "is", "negative", "the", "elements", "will", "be", "shifted", "right", "and", "those", "shifted", "past", "the", "last", "position", "will", "be", "moved", "to", "the", "beginning", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L513-L519
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.sort
def sort(&comparator) comparator = Erlang.method(:compare) unless block_given? array = super(&comparator) return List.from_enum(array) end
ruby
def sort(&comparator) comparator = Erlang.method(:compare) unless block_given? array = super(&comparator) return List.from_enum(array) end
[ "def", "sort", "(", "&", "comparator", ")", "comparator", "=", "Erlang", ".", "method", "(", ":compare", ")", "unless", "block_given?", "array", "=", "super", "(", "&", "comparator", ")", "return", "List", ".", "from_enum", "(", "array", ")", "end" ]
Return a new `List` with the same items, but sorted. @overload sort Compare elements with their natural sort key (`#<=>`). @example Erlang::List["Elephant", "Dog", "Lion"].sort # => Erlang::List["Dog", "Elephant", "Lion"] @overload sort Uses the block as a comparator to determine sorted order. @yield [a, b] Any number of times with different pairs of elements. @yieldreturn [Integer] Negative if the first element should be sorted lower, positive if the latter element, or 0 if equal. @example Erlang::List["Elephant", "Dog", "Lion"].sort { |a,b| a.size <=> b.size } # => Erlang::List["Dog", "Lion", "Elephant"] @return [List]
[ "Return", "a", "new", "List", "with", "the", "same", "items", "but", "sorted", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L613-L617
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.intersperse
def intersperse(sep) raise Erlang::ImproperListError if improper? return self if tail.empty? sep = Erlang.from(sep) out = tail = Erlang::Cons.allocate list = self until list.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) if not list.tail.empty? sep_node = Erlang::Cons.allocate sep_node.instance_variable_set(:@head, sep) sep_node.instance_variable_set(:@improper, false) new_node.instance_variable_set(:@tail, sep_node) new_node.immutable! end tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! if list.tail.empty? tail = new_node else tail = new_node.tail end list = list.tail end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
ruby
def intersperse(sep) raise Erlang::ImproperListError if improper? return self if tail.empty? sep = Erlang.from(sep) out = tail = Erlang::Cons.allocate list = self until list.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) if not list.tail.empty? sep_node = Erlang::Cons.allocate sep_node.instance_variable_set(:@head, sep) sep_node.instance_variable_set(:@improper, false) new_node.instance_variable_set(:@tail, sep_node) new_node.immutable! end tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! if list.tail.empty? tail = new_node else tail = new_node.tail end list = list.tail end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
[ "def", "intersperse", "(", "sep", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "self", "if", "tail", ".", "empty?", "sep", "=", "Erlang", ".", "from", "(", "sep", ")", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "empty?", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "if", "not", "list", ".", "tail", ".", "empty?", "sep_node", "=", "Erlang", "::", "Cons", ".", "allocate", "sep_node", ".", "instance_variable_set", "(", ":@head", ",", "sep", ")", "sep_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "new_node", ".", "instance_variable_set", "(", ":@tail", ",", "sep_node", ")", "new_node", ".", "immutable!", "end", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "immutable!", "if", "list", ".", "tail", ".", "empty?", "tail", "=", "new_node", "else", "tail", "=", "new_node", ".", "tail", "end", "list", "=", "list", ".", "tail", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end" ]
Return a new `List` with `sep` inserted between each of the existing elements. @example Erlang::List["one", "two", "three"].intersperse(" ") # => Erlang::List["one", " ", "two", " ", "three"] @return [List]
[ "Return", "a", "new", "List", "with", "sep", "inserted", "between", "each", "of", "the", "existing", "elements", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L645-L677
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.union
def union(other) raise Erlang::ImproperListError if improper? other = Erlang.from(other) raise ArgumentError, "other must be of Erlang::List type" if not Erlang.is_list(other) raise Erlang::ImproperListError if other.improper? items = ::Set.new return _uniq(items).append(other._uniq(items)) end
ruby
def union(other) raise Erlang::ImproperListError if improper? other = Erlang.from(other) raise ArgumentError, "other must be of Erlang::List type" if not Erlang.is_list(other) raise Erlang::ImproperListError if other.improper? items = ::Set.new return _uniq(items).append(other._uniq(items)) end
[ "def", "union", "(", "other", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "other", "=", "Erlang", ".", "from", "(", "other", ")", "raise", "ArgumentError", ",", "\"other must be of Erlang::List type\"", "if", "not", "Erlang", ".", "is_list", "(", "other", ")", "raise", "Erlang", "::", "ImproperListError", "if", "other", ".", "improper?", "items", "=", "::", "Set", ".", "new", "return", "_uniq", "(", "items", ")", ".", "append", "(", "other", ".", "_uniq", "(", "items", ")", ")", "end" ]
Return a `List` with all the elements from both this list and `other`, with all duplicates removed. @example Erlang::List[1, 2].union(Erlang::List[2, 3]) # => Erlang::List[1, 2, 3] @param other [List] The list to merge with @return [List]
[ "Return", "a", "List", "with", "all", "the", "elements", "from", "both", "this", "list", "and", "other", "with", "all", "duplicates", "removed", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L750-L757
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.init
def init raise Erlang::ImproperListError if improper? return Erlang::Nil if tail.empty? out = tail = Erlang::Cons.allocate list = self until list.tail.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
ruby
def init raise Erlang::ImproperListError if improper? return Erlang::Nil if tail.empty? out = tail = Erlang::Cons.allocate list = self until list.tail.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
[ "def", "init", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "Erlang", "::", "Nil", "if", "tail", ".", "empty?", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "tail", ".", "empty?", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "list", "=", "list", ".", "tail", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end" ]
Return a `List` with all elements except the last one. @example Erlang::List["a", "b", "c"].init # => Erlang::List["a", "b"] @return [List]
[ "Return", "a", "List", "with", "all", "elements", "except", "the", "last", "one", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L766-L786
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.last
def last(allow_improper = false) if allow_improper and improper? list = self list = list.tail while list.tail.kind_of?(Erlang::List) return list.tail else raise Erlang::ImproperListError if improper? list = self list = list.tail until list.tail.empty? return list.head end end
ruby
def last(allow_improper = false) if allow_improper and improper? list = self list = list.tail while list.tail.kind_of?(Erlang::List) return list.tail else raise Erlang::ImproperListError if improper? list = self list = list.tail until list.tail.empty? return list.head end end
[ "def", "last", "(", "allow_improper", "=", "false", ")", "if", "allow_improper", "and", "improper?", "list", "=", "self", "list", "=", "list", ".", "tail", "while", "list", ".", "tail", ".", "kind_of?", "(", "Erlang", "::", "List", ")", "return", "list", ".", "tail", "else", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "list", "=", "self", "list", "=", "list", ".", "tail", "until", "list", ".", "tail", ".", "empty?", "return", "list", ".", "head", "end", "end" ]
Return the last item in this list. @return [Object]
[ "Return", "the", "last", "item", "in", "this", "list", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L790-L801
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.tails
def tails raise Erlang::ImproperListError if improper? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) list = list.tail tail = new_node end tail.instance_variable_set(:@tail, Erlang::Nil) return out.tail end
ruby
def tails raise Erlang::ImproperListError if improper? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) list = list.tail tail = new_node end tail.instance_variable_set(:@tail, Erlang::Nil) return out.tail end
[ "def", "tails", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "self", "if", "empty?", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "empty?", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "list", "=", "list", ".", "tail", "tail", "=", "new_node", "end", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "return", "out", ".", "tail", "end" ]
Return a `List` of all suffixes of this list. @example Erlang::List[1,2,3].tails # => Erlang::List[ # Erlang::List[1, 2, 3], # Erlang::List[2, 3], # Erlang::List[3]] @return [List]
[ "Return", "a", "List", "of", "all", "suffixes", "of", "this", "list", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L813-L828
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.inits
def inits raise Erlang::ImproperListError if improper? return self if empty? prev = nil return map do |head| if prev.nil? Erlang::List.from_enum(prev = [head]) else Erlang::List.from_enum(prev.push(head)) end end end
ruby
def inits raise Erlang::ImproperListError if improper? return self if empty? prev = nil return map do |head| if prev.nil? Erlang::List.from_enum(prev = [head]) else Erlang::List.from_enum(prev.push(head)) end end end
[ "def", "inits", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "self", "if", "empty?", "prev", "=", "nil", "return", "map", "do", "|", "head", "|", "if", "prev", ".", "nil?", "Erlang", "::", "List", ".", "from_enum", "(", "prev", "=", "[", "head", "]", ")", "else", "Erlang", "::", "List", ".", "from_enum", "(", "prev", ".", "push", "(", "head", ")", ")", "end", "end", "end" ]
Return a `List` of all prefixes of this list. @example Erlang::List[1,2,3].inits # => Erlang::List[ # Erlang::List[1], # Erlang::List[1, 2], # Erlang::List[1, 2, 3]] @return [List]
[ "Return", "a", "List", "of", "all", "prefixes", "of", "this", "list", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L840-L851
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.combination
def combination(n) raise Erlang::ImproperListError if improper? return Erlang::Cons.new(Erlang::Nil) if n == 0 return self if empty? return tail.combination(n - 1).map { |list| list.cons(head) }.append(tail.combination(n)) end
ruby
def combination(n) raise Erlang::ImproperListError if improper? return Erlang::Cons.new(Erlang::Nil) if n == 0 return self if empty? return tail.combination(n - 1).map { |list| list.cons(head) }.append(tail.combination(n)) end
[ "def", "combination", "(", "n", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "Erlang", "::", "Cons", ".", "new", "(", "Erlang", "::", "Nil", ")", "if", "n", "==", "0", "return", "self", "if", "empty?", "return", "tail", ".", "combination", "(", "n", "-", "1", ")", ".", "map", "{", "|", "list", "|", "list", ".", "cons", "(", "head", ")", "}", ".", "append", "(", "tail", ".", "combination", "(", "n", ")", ")", "end" ]
Return a `List` of all combinations of length `n` of items from this `List`. @example Erlang::List[1,2,3].combination(2) # => Erlang::List[ # Erlang::List[1, 2], # Erlang::List[1, 3], # Erlang::List[2, 3]] @return [List]
[ "Return", "a", "List", "of", "all", "combinations", "of", "length", "n", "of", "items", "from", "this", "List", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L863-L868
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.chunk
def chunk(number) raise Erlang::ImproperListError if improper? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? first, list = list.split_at(number) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, first) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
ruby
def chunk(number) raise Erlang::ImproperListError if improper? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? first, list = list.split_at(number) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, first) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
[ "def", "chunk", "(", "number", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "self", "if", "empty?", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "empty?", "first", ",", "list", "=", "list", ".", "split_at", "(", "number", ")", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "first", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end" ]
Split the items in this list in groups of `number`. Return a list of lists. @example ("a".."o").to_list.chunk(5) # => Erlang::List[ # Erlang::List["a", "b", "c", "d", "e"], # Erlang::List["f", "g", "h", "i", "j"], # Erlang::List["k", "l", "m", "n", "o"]] @return [List]
[ "Split", "the", "items", "in", "this", "list", "in", "groups", "of", "number", ".", "Return", "a", "list", "of", "lists", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L880-L900
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.flatten
def flatten raise Erlang::ImproperListError if improper? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? if list.head.is_a?(Erlang::Cons) list = list.head.append(list.tail) elsif Erlang::Nil.equal?(list.head) list = list.tail else new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.immutable! list = list.tail tail = new_node end end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
ruby
def flatten raise Erlang::ImproperListError if improper? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? if list.head.is_a?(Erlang::Cons) list = list.head.append(list.tail) elsif Erlang::Nil.equal?(list.head) list = list.tail else new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.immutable! list = list.tail tail = new_node end end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
[ "def", "flatten", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "self", "if", "empty?", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "empty?", "if", "list", ".", "head", ".", "is_a?", "(", "Erlang", "::", "Cons", ")", "list", "=", "list", ".", "head", ".", "append", "(", "list", ".", "tail", ")", "elsif", "Erlang", "::", "Nil", ".", "equal?", "(", "list", ".", "head", ")", "list", "=", "list", ".", "tail", "else", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "immutable!", "list", "=", "list", ".", "tail", "tail", "=", "new_node", "end", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end" ]
Return a new `List` with all nested lists recursively "flattened out", that is, their elements inserted into the new `List` in the place where the nested list originally was. @example Erlang::List[Erlang::List[1, 2], Erlang::List[3, 4]].flatten # => Erlang::List[1, 2, 3, 4] @return [List]
[ "Return", "a", "new", "List", "with", "all", "nested", "lists", "recursively", "flattened", "out", "that", "is", "their", "elements", "inserted", "into", "the", "new", "List", "in", "the", "place", "where", "the", "nested", "list", "originally", "was", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L925-L950
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.slice
def slice(arg, length = (missing_length = true)) raise Erlang::ImproperListError if improper? if missing_length if arg.is_a?(Range) from, to = arg.begin, arg.end from += size if from < 0 return nil if from < 0 to += size if to < 0 to += 1 if !arg.exclude_end? length = to - from length = 0 if length < 0 list = self while from > 0 return nil if list.empty? list = list.tail from -= 1 end return list.take(length) else return at(arg) end else return nil if length < 0 arg += size if arg < 0 return nil if arg < 0 list = self while arg > 0 return nil if list.empty? list = list.tail arg -= 1 end return list.take(length) end end
ruby
def slice(arg, length = (missing_length = true)) raise Erlang::ImproperListError if improper? if missing_length if arg.is_a?(Range) from, to = arg.begin, arg.end from += size if from < 0 return nil if from < 0 to += size if to < 0 to += 1 if !arg.exclude_end? length = to - from length = 0 if length < 0 list = self while from > 0 return nil if list.empty? list = list.tail from -= 1 end return list.take(length) else return at(arg) end else return nil if length < 0 arg += size if arg < 0 return nil if arg < 0 list = self while arg > 0 return nil if list.empty? list = list.tail arg -= 1 end return list.take(length) end end
[ "def", "slice", "(", "arg", ",", "length", "=", "(", "missing_length", "=", "true", ")", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "if", "missing_length", "if", "arg", ".", "is_a?", "(", "Range", ")", "from", ",", "to", "=", "arg", ".", "begin", ",", "arg", ".", "end", "from", "+=", "size", "if", "from", "<", "0", "return", "nil", "if", "from", "<", "0", "to", "+=", "size", "if", "to", "<", "0", "to", "+=", "1", "if", "!", "arg", ".", "exclude_end?", "length", "=", "to", "-", "from", "length", "=", "0", "if", "length", "<", "0", "list", "=", "self", "while", "from", ">", "0", "return", "nil", "if", "list", ".", "empty?", "list", "=", "list", ".", "tail", "from", "-=", "1", "end", "return", "list", ".", "take", "(", "length", ")", "else", "return", "at", "(", "arg", ")", "end", "else", "return", "nil", "if", "length", "<", "0", "arg", "+=", "size", "if", "arg", "<", "0", "return", "nil", "if", "arg", "<", "0", "list", "=", "self", "while", "arg", ">", "0", "return", "nil", "if", "list", ".", "empty?", "list", "=", "list", ".", "tail", "arg", "-=", "1", "end", "return", "list", ".", "take", "(", "length", ")", "end", "end" ]
Return specific objects from the `List`. All overloads return `nil` if the starting index is out of range. @overload list.slice(index) Returns a single object at the given `index`. If `index` is negative, count backwards from the end. @param index [Integer] The index to retrieve. May be negative. @return [Object] @example l = Erlang::List["A", "B", "C", "D", "E", "F"] l[2] # => "C" l[-1] # => "F" l[6] # => nil @overload list.slice(index, length) Return a sublist starting at `index` and continuing for `length` elements or until the end of the `List`, whichever occurs first. @param start [Integer] The index to start retrieving items from. May be negative. @param length [Integer] The number of items to retrieve. @return [List] @example l = Erlang::List["A", "B", "C", "D", "E", "F"] l[2, 3] # => Erlang::List["C", "D", "E"] l[-2, 3] # => Erlang::List["E", "F"] l[20, 1] # => nil @overload list.slice(index..end) Return a sublist starting at `index` and continuing to index `end` or the end of the `List`, whichever occurs first. @param range [Range] The range of indices to retrieve. @return [Vector] @example l = Erlang::List["A", "B", "C", "D", "E", "F"] l[2..3] # => Erlang::List["C", "D"] l[-2..100] # => Erlang::List["E", "F"] l[20..21] # => nil
[ "Return", "specific", "objects", "from", "the", "List", ".", "All", "overloads", "return", "nil", "if", "the", "starting", "index", "is", "out", "of", "range", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1027-L1060
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.indices
def indices(object = Erlang::Undefined, i = 0, &block) raise Erlang::ImproperListError if improper? object = Erlang.from(object) if object != Erlang::Undefined return indices { |item| item == object } if not block_given? return Erlang::Nil if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? if yield(list.head) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, i) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail else list = list.tail end i += 1 end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
ruby
def indices(object = Erlang::Undefined, i = 0, &block) raise Erlang::ImproperListError if improper? object = Erlang.from(object) if object != Erlang::Undefined return indices { |item| item == object } if not block_given? return Erlang::Nil if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? if yield(list.head) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, i) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail else list = list.tail end i += 1 end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end return out.tail end
[ "def", "indices", "(", "object", "=", "Erlang", "::", "Undefined", ",", "i", "=", "0", ",", "&", "block", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "object", "=", "Erlang", ".", "from", "(", "object", ")", "if", "object", "!=", "Erlang", "::", "Undefined", "return", "indices", "{", "|", "item", "|", "item", "==", "object", "}", "if", "not", "block_given?", "return", "Erlang", "::", "Nil", "if", "empty?", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "until", "list", ".", "empty?", "if", "yield", "(", "list", ".", "head", ")", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "i", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "list", "=", "list", ".", "tail", "else", "list", "=", "list", ".", "tail", "end", "i", "+=", "1", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end" ]
Return a `List` of indices of matching objects. @overload indices(object) Return a `List` of indices where `object` is found. Use `#==` for testing equality. @example Erlang::List[1, 2, 3, 4].indices(2) # => Erlang::List[1] @overload indices Pass each item successively to the block. Return a list of indices where the block returns true. @yield [item] @example Erlang::List[1, 2, 3, 4].indices { |e| e.even? } # => Erlang::List[1, 3] @return [List]
[ "Return", "a", "List", "of", "indices", "of", "matching", "objects", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1083-L1110
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.merge
def merge(&comparator) raise Erlang::ImproperListError if improper? return merge_by unless block_given? sorted = reject(&:empty?).sort do |a, b| yield(a.head, b.head) end return Erlang::Nil if sorted.empty? return Erlang::Cons.new(sorted.head.head, sorted.tail.cons(sorted.head.tail).merge(&comparator)) end
ruby
def merge(&comparator) raise Erlang::ImproperListError if improper? return merge_by unless block_given? sorted = reject(&:empty?).sort do |a, b| yield(a.head, b.head) end return Erlang::Nil if sorted.empty? return Erlang::Cons.new(sorted.head.head, sorted.tail.cons(sorted.head.tail).merge(&comparator)) end
[ "def", "merge", "(", "&", "comparator", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "merge_by", "unless", "block_given?", "sorted", "=", "reject", "(", "&", ":empty?", ")", ".", "sort", "do", "|", "a", ",", "b", "|", "yield", "(", "a", ".", "head", ",", "b", ".", "head", ")", "end", "return", "Erlang", "::", "Nil", "if", "sorted", ".", "empty?", "return", "Erlang", "::", "Cons", ".", "new", "(", "sorted", ".", "head", ".", "head", ",", "sorted", ".", "tail", ".", "cons", "(", "sorted", ".", "head", ".", "tail", ")", ".", "merge", "(", "&", "comparator", ")", ")", "end" ]
Merge all the nested lists into a single list, using the given comparator block to determine the order which items should be shifted out of the nested lists and into the output list. @example list_1 = Erlang::List[1, -3, -5] list_2 = Erlang::List[-2, 4, 6] Erlang::List[list_1, list_2].merge { |a,b| a.abs <=> b.abs } # => Erlang::List[1, -2, -3, 4, -5, 6] @return [List] @yield [a, b] Pairs of items from matching indices in each list. @yieldreturn [Integer] Negative if the first element should be selected first, positive if the latter element, or zero if either.
[ "Merge", "all", "the", "nested", "lists", "into", "a", "single", "list", "using", "the", "given", "comparator", "block", "to", "determine", "the", "order", "which", "items", "should", "be", "shifted", "out", "of", "the", "nested", "lists", "and", "into", "the", "output", "list", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1127-L1135
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.insert
def insert(index, *items) raise Erlang::ImproperListError if improper? if index == 0 return Erlang::List.from_enum(items).append(self) elsif index > 0 out = tail = Erlang::Cons.allocate list = self while index > 0 new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail index -= 1 end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::List.from_enum(items).append(list)) tail.immutable! end return out.tail else raise IndexError if index < -size return insert(index + size, *items) end end
ruby
def insert(index, *items) raise Erlang::ImproperListError if improper? if index == 0 return Erlang::List.from_enum(items).append(self) elsif index > 0 out = tail = Erlang::Cons.allocate list = self while index > 0 new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail index -= 1 end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::List.from_enum(items).append(list)) tail.immutable! end return out.tail else raise IndexError if index < -size return insert(index + size, *items) end end
[ "def", "insert", "(", "index", ",", "*", "items", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "if", "index", "==", "0", "return", "Erlang", "::", "List", ".", "from_enum", "(", "items", ")", ".", "append", "(", "self", ")", "elsif", "index", ">", "0", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "while", "index", ">", "0", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "list", "=", "list", ".", "tail", "index", "-=", "1", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "List", ".", "from_enum", "(", "items", ")", ".", "append", "(", "list", ")", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "else", "raise", "IndexError", "if", "index", "<", "-", "size", "return", "insert", "(", "index", "+", "size", ",", "*", "items", ")", "end", "end" ]
Return a new `List` with the given items inserted before the item at `index`. @example Erlang::List["A", "D", "E"].insert(1, "B", "C") # => Erlang::List["A", "B", "C", "D", "E"] @param index [Integer] The index where the new items should go @param items [Array] The items to add @return [List]
[ "Return", "a", "new", "List", "with", "the", "given", "items", "inserted", "before", "the", "item", "at", "index", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1176-L1203
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.delete_at
def delete_at(index) raise Erlang::ImproperListError if improper? if index == 0 tail elsif index < 0 index += size if index < 0 return self if index < 0 delete_at(index) else out = tail = Erlang::Cons.allocate list = self while index > 0 new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail index -= 1 end if not tail.immutable? tail.instance_variable_set(:@tail, list.tail) tail.immutable! end return out.tail end end
ruby
def delete_at(index) raise Erlang::ImproperListError if improper? if index == 0 tail elsif index < 0 index += size if index < 0 return self if index < 0 delete_at(index) else out = tail = Erlang::Cons.allocate list = self while index > 0 new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) tail.instance_variable_set(:@tail, new_node) tail.instance_variable_set(:@improper, false) tail.immutable! tail = new_node list = list.tail index -= 1 end if not tail.immutable? tail.instance_variable_set(:@tail, list.tail) tail.immutable! end return out.tail end end
[ "def", "delete_at", "(", "index", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "if", "index", "==", "0", "tail", "elsif", "index", "<", "0", "index", "+=", "size", "if", "index", "<", "0", "return", "self", "if", "index", "<", "0", "delete_at", "(", "index", ")", "else", "out", "=", "tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "while", "index", ">", "0", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "tail", ".", "immutable!", "tail", "=", "new_node", "list", "=", "list", ".", "tail", "index", "-=", "1", "end", "if", "not", "tail", ".", "immutable?", "tail", ".", "instance_variable_set", "(", ":@tail", ",", "list", ".", "tail", ")", "tail", ".", "immutable!", "end", "return", "out", ".", "tail", "end", "end" ]
Return a `List` containing the same items, minus the one at `index`. If `index` is negative, it counts back from the end of the list. @example Erlang::List[1, 2, 3].delete_at(1) # => Erlang::List[1, 3] Erlang::List[1, 2, 3].delete_at(-1) # => Erlang::List[1, 2] @param index [Integer] The index of the item to remove @return [List]
[ "Return", "a", "List", "containing", "the", "same", "items", "minus", "the", "one", "at", "index", ".", "If", "index", "is", "negative", "it", "counts", "back", "from", "the", "end", "of", "the", "list", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1250-L1278
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.permutation
def permutation(length = size, &block) raise Erlang::ImproperListError if improper? return enum_for(:permutation, length) if not block_given? if length == 0 yield Erlang::Nil elsif length == 1 each { |obj| yield Erlang::Cons.new(obj, Erlang::Nil) } elsif not empty? if length < size tail.permutation(length, &block) end tail.permutation(length-1) do |p| 0.upto(length-1) do |i| left,right = p.split_at(i) yield left.append(right.cons(head)) end end end return self end
ruby
def permutation(length = size, &block) raise Erlang::ImproperListError if improper? return enum_for(:permutation, length) if not block_given? if length == 0 yield Erlang::Nil elsif length == 1 each { |obj| yield Erlang::Cons.new(obj, Erlang::Nil) } elsif not empty? if length < size tail.permutation(length, &block) end tail.permutation(length-1) do |p| 0.upto(length-1) do |i| left,right = p.split_at(i) yield left.append(right.cons(head)) end end end return self end
[ "def", "permutation", "(", "length", "=", "size", ",", "&", "block", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "enum_for", "(", ":permutation", ",", "length", ")", "if", "not", "block_given?", "if", "length", "==", "0", "yield", "Erlang", "::", "Nil", "elsif", "length", "==", "1", "each", "{", "|", "obj", "|", "yield", "Erlang", "::", "Cons", ".", "new", "(", "obj", ",", "Erlang", "::", "Nil", ")", "}", "elsif", "not", "empty?", "if", "length", "<", "size", "tail", ".", "permutation", "(", "length", ",", "&", "block", ")", "end", "tail", ".", "permutation", "(", "length", "-", "1", ")", "do", "|", "p", "|", "0", ".", "upto", "(", "length", "-", "1", ")", "do", "|", "i", "|", "left", ",", "right", "=", "p", ".", "split_at", "(", "i", ")", "yield", "left", ".", "append", "(", "right", ".", "cons", "(", "head", ")", ")", "end", "end", "end", "return", "self", "end" ]
Yields all permutations of length `n` of the items in the list, and then returns `self`. If no length `n` is specified, permutations of the entire list will be yielded. There is no guarantee about which order the permutations will be yielded in. If no block is given, an `Enumerator` is returned instead. @example Erlang::List[1, 2, 3].permutation.to_a # => [Erlang::List[1, 2, 3], # Erlang::List[2, 1, 3], # Erlang::List[2, 3, 1], # Erlang::List[1, 3, 2], # Erlang::List[3, 1, 2], # Erlang::List[3, 2, 1]] @return [self, Enumerator] @yield [list] Once for each permutation.
[ "Yields", "all", "permutations", "of", "length", "n", "of", "the", "items", "in", "the", "list", "and", "then", "returns", "self", ".", "If", "no", "length", "n", "is", "specified", "permutations", "of", "the", "entire", "list", "will", "be", "yielded", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1400-L1420
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.partition
def partition(&block) raise Erlang::ImproperListError if improper? return enum_for(:partition) if not block_given? left = left_tail = Erlang::Cons.allocate right = right_tail = Erlang::Cons.allocate list = self while !list.empty? if yield(list.head) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) left_tail.instance_variable_set(:@tail, new_node) left_tail.instance_variable_set(:@improper, false) left_tail.immutable! left_tail = new_node list = list.tail else new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) right_tail.instance_variable_set(:@tail, new_node) right_tail.instance_variable_set(:@improper, false) right_tail.immutable! right_tail = new_node list = list.tail end end if not left_tail.immutable? left_tail.instance_variable_set(:@tail, Erlang::Nil) left_tail.immutable! end if not right_tail.immutable? right_tail.instance_variable_set(:@tail, Erlang::Nil) right_tail.immutable! end return Erlang::Tuple[left.tail, right.tail] end
ruby
def partition(&block) raise Erlang::ImproperListError if improper? return enum_for(:partition) if not block_given? left = left_tail = Erlang::Cons.allocate right = right_tail = Erlang::Cons.allocate list = self while !list.empty? if yield(list.head) new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) left_tail.instance_variable_set(:@tail, new_node) left_tail.instance_variable_set(:@improper, false) left_tail.immutable! left_tail = new_node list = list.tail else new_node = Erlang::Cons.allocate new_node.instance_variable_set(:@head, list.head) new_node.instance_variable_set(:@improper, false) right_tail.instance_variable_set(:@tail, new_node) right_tail.instance_variable_set(:@improper, false) right_tail.immutable! right_tail = new_node list = list.tail end end if not left_tail.immutable? left_tail.instance_variable_set(:@tail, Erlang::Nil) left_tail.immutable! end if not right_tail.immutable? right_tail.instance_variable_set(:@tail, Erlang::Nil) right_tail.immutable! end return Erlang::Tuple[left.tail, right.tail] end
[ "def", "partition", "(", "&", "block", ")", "raise", "Erlang", "::", "ImproperListError", "if", "improper?", "return", "enum_for", "(", ":partition", ")", "if", "not", "block_given?", "left", "=", "left_tail", "=", "Erlang", "::", "Cons", ".", "allocate", "right", "=", "right_tail", "=", "Erlang", "::", "Cons", ".", "allocate", "list", "=", "self", "while", "!", "list", ".", "empty?", "if", "yield", "(", "list", ".", "head", ")", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "left_tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "left_tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "left_tail", ".", "immutable!", "left_tail", "=", "new_node", "list", "=", "list", ".", "tail", "else", "new_node", "=", "Erlang", "::", "Cons", ".", "allocate", "new_node", ".", "instance_variable_set", "(", ":@head", ",", "list", ".", "head", ")", "new_node", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "right_tail", ".", "instance_variable_set", "(", ":@tail", ",", "new_node", ")", "right_tail", ".", "instance_variable_set", "(", ":@improper", ",", "false", ")", "right_tail", ".", "immutable!", "right_tail", "=", "new_node", "list", "=", "list", ".", "tail", "end", "end", "if", "not", "left_tail", ".", "immutable?", "left_tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "left_tail", ".", "immutable!", "end", "if", "not", "right_tail", ".", "immutable?", "right_tail", ".", "instance_variable_set", "(", ":@tail", ",", "Erlang", "::", "Nil", ")", "right_tail", ".", "immutable!", "end", "return", "Erlang", "::", "Tuple", "[", "left", ".", "tail", ",", "right", ".", "tail", "]", "end" ]
Return two `List`s, the first containing all the elements for which the block evaluates to true, the second containing the rest. @example Erlang::List[1, 2, 3, 4, 5, 6].partition { |x| x.even? } # => Erlang::Tuple[Erlang::List[2, 4, 6], Erlang::List[1, 3, 5]] @return [Tuple] @yield [item] Once for each item.
[ "Return", "two", "List", "s", "the", "first", "containing", "all", "the", "elements", "for", "which", "the", "block", "evaluates", "to", "true", "the", "second", "containing", "the", "rest", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1458-L1494
train
potatosalad/ruby-erlang-terms
lib/erlang/list.rb
Erlang.List.inspect
def inspect if improper? result = 'Erlang::List[' list = to_proper_list list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect } result << ']' result << " + #{last(true).inspect}" return result else result = '[' list = self list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect } result << ']' return result end end
ruby
def inspect if improper? result = 'Erlang::List[' list = to_proper_list list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect } result << ']' result << " + #{last(true).inspect}" return result else result = '[' list = self list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect } result << ']' return result end end
[ "def", "inspect", "if", "improper?", "result", "=", "'Erlang::List['", "list", "=", "to_proper_list", "list", ".", "each_with_index", "{", "|", "obj", ",", "i", "|", "result", "<<", "', '", "if", "i", ">", "0", ";", "result", "<<", "obj", ".", "inspect", "}", "result", "<<", "']'", "result", "<<", "\" + #{last(true).inspect}\"", "return", "result", "else", "result", "=", "'['", "list", "=", "self", "list", ".", "each_with_index", "{", "|", "obj", ",", "i", "|", "result", "<<", "', '", "if", "i", ">", "0", ";", "result", "<<", "obj", ".", "inspect", "}", "result", "<<", "']'", "return", "result", "end", "end" ]
Return the contents of this `List` as a programmer-readable `String`. If all the items in the list are serializable as Ruby literal strings, the returned string can be passed to `eval` to reconstitute an equivalent `List`. @return [::String]
[ "Return", "the", "contents", "of", "this", "List", "as", "a", "programmer", "-", "readable", "String", ".", "If", "all", "the", "items", "in", "the", "list", "are", "serializable", "as", "Ruby", "literal", "strings", "the", "returned", "string", "can", "be", "passed", "to", "eval", "to", "reconstitute", "an", "equivalent", "List", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L1647-L1662
train
potatosalad/ruby-erlang-terms
lib/erlang/binary.rb
Erlang.Binary.copy
def copy(n = 1) raise ArgumentError, 'n must be a non-negative Integer' if not n.is_a?(::Integer) or n < 0 return self if n == 1 return Erlang::Binary[(@data * n)] end
ruby
def copy(n = 1) raise ArgumentError, 'n must be a non-negative Integer' if not n.is_a?(::Integer) or n < 0 return self if n == 1 return Erlang::Binary[(@data * n)] end
[ "def", "copy", "(", "n", "=", "1", ")", "raise", "ArgumentError", ",", "'n must be a non-negative Integer'", "if", "not", "n", ".", "is_a?", "(", "::", "Integer", ")", "or", "n", "<", "0", "return", "self", "if", "n", "==", "1", "return", "Erlang", "::", "Binary", "[", "(", "@data", "*", "n", ")", "]", "end" ]
Returns a new `Binary` containing `n` copies of itself. `n` must be greater than or equal to 0. @param n [Integer] The number of copies @return [Binary] @raise [ArgumentError] if `n` is less than 0
[ "Returns", "a", "new", "Binary", "containing", "n", "copies", "of", "itself", ".", "n", "must", "be", "greater", "than", "or", "equal", "to", "0", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/binary.rb#L225-L229
train
potatosalad/ruby-erlang-terms
lib/erlang/binary.rb
Erlang.Binary.each_bit
def each_bit return enum_for(:each_bit) unless block_given? index = 0 bitsize = self.bitsize @data.each_byte do |byte| loop do break if index == bitsize bit = (byte >> (7 - (index & 7))) & 1 yield bit index += 1 break if (index & 7) == 0 end end return self end
ruby
def each_bit return enum_for(:each_bit) unless block_given? index = 0 bitsize = self.bitsize @data.each_byte do |byte| loop do break if index == bitsize bit = (byte >> (7 - (index & 7))) & 1 yield bit index += 1 break if (index & 7) == 0 end end return self end
[ "def", "each_bit", "return", "enum_for", "(", ":each_bit", ")", "unless", "block_given?", "index", "=", "0", "bitsize", "=", "self", ".", "bitsize", "@data", ".", "each_byte", "do", "|", "byte", "|", "loop", "do", "break", "if", "index", "==", "bitsize", "bit", "=", "(", "byte", ">>", "(", "7", "-", "(", "index", "&", "7", ")", ")", ")", "&", "1", "yield", "bit", "index", "+=", "1", "break", "if", "(", "index", "&", "7", ")", "==", "0", "end", "end", "return", "self", "end" ]
Call the given block once for each bit in the `Binary`, passing each bit from first to last successively to the block. If no block is given, returns an `Enumerator`. @return [self] @yield [Integer]
[ "Call", "the", "given", "block", "once", "for", "each", "bit", "in", "the", "Binary", "passing", "each", "bit", "from", "first", "to", "last", "successively", "to", "the", "block", ".", "If", "no", "block", "is", "given", "returns", "an", "Enumerator", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/binary.rb#L245-L259
train
potatosalad/ruby-erlang-terms
lib/erlang/binary.rb
Erlang.Binary.part
def part(position, length) raise ArgumentError, 'position must be an Integer' if not position.is_a?(::Integer) raise ArgumentError, 'length must be a non-negative Integer' if not length.is_a?(::Integer) or length < 0 return Erlang::Binary[@data.byteslice(position, length)] end
ruby
def part(position, length) raise ArgumentError, 'position must be an Integer' if not position.is_a?(::Integer) raise ArgumentError, 'length must be a non-negative Integer' if not length.is_a?(::Integer) or length < 0 return Erlang::Binary[@data.byteslice(position, length)] end
[ "def", "part", "(", "position", ",", "length", ")", "raise", "ArgumentError", ",", "'position must be an Integer'", "if", "not", "position", ".", "is_a?", "(", "::", "Integer", ")", "raise", "ArgumentError", ",", "'length must be a non-negative Integer'", "if", "not", "length", ".", "is_a?", "(", "::", "Integer", ")", "or", "length", "<", "0", "return", "Erlang", "::", "Binary", "[", "@data", ".", "byteslice", "(", "position", ",", "length", ")", "]", "end" ]
Returns the section of this `Binary` starting at `position` of `length`. @param position [Integer] The starting position @param length [Integer] The non-negative length @return [Binary] @raise [ArgumentError] if `position` is not an `Integer` or `length` is not a non-negative `Integer`
[ "Returns", "the", "section", "of", "this", "Binary", "starting", "at", "position", "of", "length", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/binary.rb#L336-L340
train
langalex/culerity
lib/culerity/remote_browser_proxy.rb
Culerity.RemoteBrowserProxy.wait_until
def wait_until time_to_wait=30, &block time_limit = Time.now + time_to_wait until block.call if Time.now > time_limit raise "wait_until timeout after #{time_to_wait} seconds" end sleep 0.1 end true end
ruby
def wait_until time_to_wait=30, &block time_limit = Time.now + time_to_wait until block.call if Time.now > time_limit raise "wait_until timeout after #{time_to_wait} seconds" end sleep 0.1 end true end
[ "def", "wait_until", "time_to_wait", "=", "30", ",", "&", "block", "time_limit", "=", "Time", ".", "now", "+", "time_to_wait", "until", "block", ".", "call", "if", "Time", ".", "now", ">", "time_limit", "raise", "\"wait_until timeout after #{time_to_wait} seconds\"", "end", "sleep", "0.1", "end", "true", "end" ]
Calls the block until it returns true or +time_to_wait+ is reached. +time_to_wait+ is 30 seconds by default Returns true upon success Raises RuntimeError when +time_to_wait+ is reached.
[ "Calls", "the", "block", "until", "it", "returns", "true", "or", "+", "time_to_wait", "+", "is", "reached", ".", "+", "time_to_wait", "+", "is", "30", "seconds", "by", "default" ]
8e330ce79e88d00a213ece7755a22f4e0ca4f042
https://github.com/langalex/culerity/blob/8e330ce79e88d00a213ece7755a22f4e0ca4f042/lib/culerity/remote_browser_proxy.rb#L18-L27
train
langalex/culerity
lib/culerity/remote_browser_proxy.rb
Culerity.RemoteBrowserProxy.confirm
def confirm(bool, &block) blk = "lambda { #{bool} }" self.send_remote(:add_listener, :confirm) { blk } block.call self.send_remote(:remove_listener, :confirm, lambda {blk}) end
ruby
def confirm(bool, &block) blk = "lambda { #{bool} }" self.send_remote(:add_listener, :confirm) { blk } block.call self.send_remote(:remove_listener, :confirm, lambda {blk}) end
[ "def", "confirm", "(", "bool", ",", "&", "block", ")", "blk", "=", "\"lambda { #{bool} }\"", "self", ".", "send_remote", "(", ":add_listener", ",", ":confirm", ")", "{", "blk", "}", "block", ".", "call", "self", ".", "send_remote", "(", ":remove_listener", ",", ":confirm", ",", "lambda", "{", "blk", "}", ")", "end" ]
Specify whether to accept or reject all confirm js dialogs for the code in the block that's run.
[ "Specify", "whether", "to", "accept", "or", "reject", "all", "confirm", "js", "dialogs", "for", "the", "code", "in", "the", "block", "that", "s", "run", "." ]
8e330ce79e88d00a213ece7755a22f4e0ca4f042
https://github.com/langalex/culerity/blob/8e330ce79e88d00a213ece7755a22f4e0ca4f042/lib/culerity/remote_browser_proxy.rb#L52-L58
train
uasi/pixiv
lib/pixiv/page.rb
Pixiv.Page.bind
def bind(client) if self.class.const_defined?(:WithClient) mod = self.class.const_get(:WithClient) else mod = Page::WithClient end unless singleton_class.include?(mod) extend(mod) end self.client = client self end
ruby
def bind(client) if self.class.const_defined?(:WithClient) mod = self.class.const_get(:WithClient) else mod = Page::WithClient end unless singleton_class.include?(mod) extend(mod) end self.client = client self end
[ "def", "bind", "(", "client", ")", "if", "self", ".", "class", ".", "const_defined?", "(", ":WithClient", ")", "mod", "=", "self", ".", "class", ".", "const_get", "(", ":WithClient", ")", "else", "mod", "=", "Page", "::", "WithClient", "end", "unless", "singleton_class", ".", "include?", "(", "mod", ")", "extend", "(", "mod", ")", "end", "self", ".", "client", "=", "client", "self", "end" ]
Bind +self+ to +client+ @api private @return self
[ "Bind", "+", "self", "+", "to", "+", "client", "+" ]
6750829692fa9c3f56605d3319616072756c9d7c
https://github.com/uasi/pixiv/blob/6750829692fa9c3f56605d3319616072756c9d7c/lib/pixiv/page.rb#L58-L69
train
uasi/pixiv
lib/pixiv/client.rb
Pixiv.Client.login
def login(pixiv_id, password) doc = agent.get("https://accounts.pixiv.net/login?lang=ja&source=pc&view_type=page") return if doc && doc.body =~ /logout/ form = doc.forms_with(action: '/login').first puts doc.body and raise Error::LoginFailed, 'login form is not available' unless form form.pixiv_id = pixiv_id form.password = password doc = agent.submit(form) raise Error::LoginFailed unless doc && doc.body =~ /logout/ @member_id = member_id_from_mypage(doc) end
ruby
def login(pixiv_id, password) doc = agent.get("https://accounts.pixiv.net/login?lang=ja&source=pc&view_type=page") return if doc && doc.body =~ /logout/ form = doc.forms_with(action: '/login').first puts doc.body and raise Error::LoginFailed, 'login form is not available' unless form form.pixiv_id = pixiv_id form.password = password doc = agent.submit(form) raise Error::LoginFailed unless doc && doc.body =~ /logout/ @member_id = member_id_from_mypage(doc) end
[ "def", "login", "(", "pixiv_id", ",", "password", ")", "doc", "=", "agent", ".", "get", "(", "\"https://accounts.pixiv.net/login?lang=ja&source=pc&view_type=page\"", ")", "return", "if", "doc", "&&", "doc", ".", "body", "=~", "/", "/", "form", "=", "doc", ".", "forms_with", "(", "action", ":", "'/login'", ")", ".", "first", "puts", "doc", ".", "body", "and", "raise", "Error", "::", "LoginFailed", ",", "'login form is not available'", "unless", "form", "form", ".", "pixiv_id", "=", "pixiv_id", "form", ".", "password", "=", "password", "doc", "=", "agent", ".", "submit", "(", "form", ")", "raise", "Error", "::", "LoginFailed", "unless", "doc", "&&", "doc", ".", "body", "=~", "/", "/", "@member_id", "=", "member_id_from_mypage", "(", "doc", ")", "end" ]
A new instance of Client, logged in with the given credentials @overload initialize(pixiv_id, password) @param [String] pixiv_id @param [String] password @yield [agent] (optional) gives a chance to customize the +agent+ before logging in @overload initialize(agent) @param [Mechanize::HTTP::Agent] agent @return [Pixiv::Client] Log in to Pixiv @param [String] pixiv_id @param [String] password
[ "A", "new", "instance", "of", "Client", "logged", "in", "with", "the", "given", "credentials" ]
6750829692fa9c3f56605d3319616072756c9d7c
https://github.com/uasi/pixiv/blob/6750829692fa9c3f56605d3319616072756c9d7c/lib/pixiv/client.rb#L43-L53
train
uasi/pixiv
lib/pixiv/client.rb
Pixiv.Client.download_illust
def download_illust(illust, io_or_filename, size = :original) size = {:s => :small, :m => :medium, :o => :original}[size] || size url = illust.__send__("#{size}_image_url") referer = case size when :small then nil when :medium then illust.url when :original then illust.url else raise ArgumentError, "unknown size `#{size}`" end save_to = io_or_filename if save_to.is_a?(Array) save_to = filename_from_pattern(save_to, illust, url) end FileUtils.mkdir_p(File.dirname(save_to)) unless save_to.respond_to?(:write) @agent.download(url, save_to, [], referer) end
ruby
def download_illust(illust, io_or_filename, size = :original) size = {:s => :small, :m => :medium, :o => :original}[size] || size url = illust.__send__("#{size}_image_url") referer = case size when :small then nil when :medium then illust.url when :original then illust.url else raise ArgumentError, "unknown size `#{size}`" end save_to = io_or_filename if save_to.is_a?(Array) save_to = filename_from_pattern(save_to, illust, url) end FileUtils.mkdir_p(File.dirname(save_to)) unless save_to.respond_to?(:write) @agent.download(url, save_to, [], referer) end
[ "def", "download_illust", "(", "illust", ",", "io_or_filename", ",", "size", "=", ":original", ")", "size", "=", "{", ":s", "=>", ":small", ",", ":m", "=>", ":medium", ",", ":o", "=>", ":original", "}", "[", "size", "]", "||", "size", "url", "=", "illust", ".", "__send__", "(", "\"#{size}_image_url\"", ")", "referer", "=", "case", "size", "when", ":small", "then", "nil", "when", ":medium", "then", "illust", ".", "url", "when", ":original", "then", "illust", ".", "url", "else", "raise", "ArgumentError", ",", "\"unknown size `#{size}`\"", "end", "save_to", "=", "io_or_filename", "if", "save_to", ".", "is_a?", "(", "Array", ")", "save_to", "=", "filename_from_pattern", "(", "save_to", ",", "illust", ",", "url", ")", "end", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "save_to", ")", ")", "unless", "save_to", ".", "respond_to?", "(", ":write", ")", "@agent", ".", "download", "(", "url", ",", "save_to", ",", "[", "]", ",", "referer", ")", "end" ]
Downloads the image to +io_or_filename+ @param [Pixiv::Illust] illust @param [#write, String, Array<String, Symbol, #call>] io_or_filename io or filename or pattern for {#filename_from_pattern} @param [Symbol] size image size (+:small+, +:medium+, or +:original+)
[ "Downloads", "the", "image", "to", "+", "io_or_filename", "+" ]
6750829692fa9c3f56605d3319616072756c9d7c
https://github.com/uasi/pixiv/blob/6750829692fa9c3f56605d3319616072756c9d7c/lib/pixiv/client.rb#L141-L156
train
uasi/pixiv
lib/pixiv/client.rb
Pixiv.Client.download_manga
def download_manga(illust, pattern, &block) action = DownloadActionRegistry.new(&block) illust.original_image_urls.each_with_index do |url, n| begin action.before_each.call(url, n) if action.before_each filename = filename_from_pattern(pattern, illust, url) FileUtils.mkdir_p(File.dirname(filename)) @agent.download(url, filename, [], illust.original_image_referer) action.after_each.call(url, n) if action.after_each rescue action.on_error ? action.on_error.call($!) : raise end end end
ruby
def download_manga(illust, pattern, &block) action = DownloadActionRegistry.new(&block) illust.original_image_urls.each_with_index do |url, n| begin action.before_each.call(url, n) if action.before_each filename = filename_from_pattern(pattern, illust, url) FileUtils.mkdir_p(File.dirname(filename)) @agent.download(url, filename, [], illust.original_image_referer) action.after_each.call(url, n) if action.after_each rescue action.on_error ? action.on_error.call($!) : raise end end end
[ "def", "download_manga", "(", "illust", ",", "pattern", ",", "&", "block", ")", "action", "=", "DownloadActionRegistry", ".", "new", "(", "&", "block", ")", "illust", ".", "original_image_urls", ".", "each_with_index", "do", "|", "url", ",", "n", "|", "begin", "action", ".", "before_each", ".", "call", "(", "url", ",", "n", ")", "if", "action", ".", "before_each", "filename", "=", "filename_from_pattern", "(", "pattern", ",", "illust", ",", "url", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "filename", ")", ")", "@agent", ".", "download", "(", "url", ",", "filename", ",", "[", "]", ",", "illust", ".", "original_image_referer", ")", "action", ".", "after_each", ".", "call", "(", "url", ",", "n", ")", "if", "action", ".", "after_each", "rescue", "action", ".", "on_error", "?", "action", ".", "on_error", ".", "call", "(", "$!", ")", ":", "raise", "end", "end", "end" ]
Downloads the images to +pattern+ @param [Pixiv::Illust] illust the manga to download @param [Array<String, Symbol, #call>] pattern pattern for {#filename_from_pattern} @note +illust#manga?+ must be +true+ @todo Document +&block+
[ "Downloads", "the", "images", "to", "+", "pattern", "+" ]
6750829692fa9c3f56605d3319616072756c9d7c
https://github.com/uasi/pixiv/blob/6750829692fa9c3f56605d3319616072756c9d7c/lib/pixiv/client.rb#L163-L176
train
uasi/pixiv
lib/pixiv/client.rb
Pixiv.Client.filename_from_pattern
def filename_from_pattern(pattern, illust, url) pattern.map {|i| if i == :image_name name = File.basename(url) if name =~ /\.(\w+)\?\d+$/ name += '.' + $1 end name elsif i.is_a?(Symbol) then illust.send(i) elsif i.respond_to?(:call) then i.call(illust) else i end }.join('') end
ruby
def filename_from_pattern(pattern, illust, url) pattern.map {|i| if i == :image_name name = File.basename(url) if name =~ /\.(\w+)\?\d+$/ name += '.' + $1 end name elsif i.is_a?(Symbol) then illust.send(i) elsif i.respond_to?(:call) then i.call(illust) else i end }.join('') end
[ "def", "filename_from_pattern", "(", "pattern", ",", "illust", ",", "url", ")", "pattern", ".", "map", "{", "|", "i", "|", "if", "i", "==", ":image_name", "name", "=", "File", ".", "basename", "(", "url", ")", "if", "name", "=~", "/", "\\.", "\\w", "\\?", "\\d", "/", "name", "+=", "'.'", "+", "$1", "end", "name", "elsif", "i", ".", "is_a?", "(", "Symbol", ")", "then", "illust", ".", "send", "(", "i", ")", "elsif", "i", ".", "respond_to?", "(", ":call", ")", "then", "i", ".", "call", "(", "illust", ")", "else", "i", "end", "}", ".", "join", "(", "''", ")", "end" ]
Generate filename from +pattern+ in context of +illust+ and +url+ @api private @param [Array<String, Symbol, #call>] pattern @param [Pixiv::Illust] illust @param [String] url @return [String] filename The +pattern+ is an array of string, symbol, or object that responds to +#call+. Each component of the +pattern+ is replaced by the following rules and then the +pattern+ is concatenated as the returning +filename+. * +:image_name+ in the +pattern+ is replaced with the base name of the +url+ * Any other symbol is replaced with the value of +illust.send(the_symbol)+ * +#call+-able object is replaced with the value of +the_object.call(illust)+ * String is left as-is
[ "Generate", "filename", "from", "+", "pattern", "+", "in", "context", "of", "+", "illust", "+", "and", "+", "url", "+" ]
6750829692fa9c3f56605d3319616072756c9d7c
https://github.com/uasi/pixiv/blob/6750829692fa9c3f56605d3319616072756c9d7c/lib/pixiv/client.rb#L194-L207
train
lantins/dns-zone
lib/dns/zone.rb
DNS.Zone.soa
def soa # return the first SOA we find in the records array. rr = @records.find { |rr| rr.type == "SOA" } return rr if rr # otherwise create a new SOA rr = DNS::Zone::RR::SOA.new rr.serial = Time.now.utc.strftime("%Y%m%d01") rr.refresh_ttl = '3h' rr.retry_ttl = '15m' rr.expiry_ttl = '4w' rr.minimum_ttl = '30m' # store and return new SOA @records << rr return rr end
ruby
def soa # return the first SOA we find in the records array. rr = @records.find { |rr| rr.type == "SOA" } return rr if rr # otherwise create a new SOA rr = DNS::Zone::RR::SOA.new rr.serial = Time.now.utc.strftime("%Y%m%d01") rr.refresh_ttl = '3h' rr.retry_ttl = '15m' rr.expiry_ttl = '4w' rr.minimum_ttl = '30m' # store and return new SOA @records << rr return rr end
[ "def", "soa", "rr", "=", "@records", ".", "find", "{", "|", "rr", "|", "rr", ".", "type", "==", "\"SOA\"", "}", "return", "rr", "if", "rr", "rr", "=", "DNS", "::", "Zone", "::", "RR", "::", "SOA", ".", "new", "rr", ".", "serial", "=", "Time", ".", "now", ".", "utc", ".", "strftime", "(", "\"%Y%m%d01\"", ")", "rr", ".", "refresh_ttl", "=", "'3h'", "rr", ".", "retry_ttl", "=", "'15m'", "rr", ".", "expiry_ttl", "=", "'4w'", "rr", ".", "minimum_ttl", "=", "'30m'", "@records", "<<", "rr", "return", "rr", "end" ]
Create an empty instance of a DNS zone that you can drive programmatically. @api public Helper method to access the zones SOA RR. @api public
[ "Create", "an", "empty", "instance", "of", "a", "DNS", "zone", "that", "you", "can", "drive", "programmatically", "." ]
f60cbfd7ec72217288be6c6ece9a83c22350cb58
https://github.com/lantins/dns-zone/blob/f60cbfd7ec72217288be6c6ece9a83c22350cb58/lib/dns/zone.rb#L36-L50
train
lantins/dns-zone
lib/dns/zone.rb
DNS.Zone.dump_pretty
def dump_pretty content = [] last_type = "SOA" sorted_records.each do |rr| content << '' if last_type != rr.type content << rr.dump last_type = rr.type end content.join("\n") << "\n" end
ruby
def dump_pretty content = [] last_type = "SOA" sorted_records.each do |rr| content << '' if last_type != rr.type content << rr.dump last_type = rr.type end content.join("\n") << "\n" end
[ "def", "dump_pretty", "content", "=", "[", "]", "last_type", "=", "\"SOA\"", "sorted_records", ".", "each", "do", "|", "rr", "|", "content", "<<", "''", "if", "last_type", "!=", "rr", ".", "type", "content", "<<", "rr", ".", "dump", "last_type", "=", "rr", ".", "type", "end", "content", ".", "join", "(", "\"\\n\"", ")", "<<", "\"\\n\"", "end" ]
Generates pretty output of the zone and its records. @api public
[ "Generates", "pretty", "output", "of", "the", "zone", "and", "its", "records", "." ]
f60cbfd7ec72217288be6c6ece9a83c22350cb58
https://github.com/lantins/dns-zone/blob/f60cbfd7ec72217288be6c6ece9a83c22350cb58/lib/dns/zone.rb#L68-L79
train
lantins/dns-zone
lib/dns/zone.rb
DNS.Zone.sorted_records
def sorted_records # pull out RRs we want to stick near the top top_rrs = {} top = %w{SOA NS MX SPF TXT} top.each { |t| top_rrs[t] = @records.select { |rr| rr.type == t } } remaining = @records.reject { |rr| top.include?(rr.type) } # sort remaining RRs by type, alphabeticly remaining.sort! { |a,b| a.type <=> b.type } top_rrs.values.flatten + remaining end
ruby
def sorted_records # pull out RRs we want to stick near the top top_rrs = {} top = %w{SOA NS MX SPF TXT} top.each { |t| top_rrs[t] = @records.select { |rr| rr.type == t } } remaining = @records.reject { |rr| top.include?(rr.type) } # sort remaining RRs by type, alphabeticly remaining.sort! { |a,b| a.type <=> b.type } top_rrs.values.flatten + remaining end
[ "def", "sorted_records", "top_rrs", "=", "{", "}", "top", "=", "%w{", "SOA", "NS", "MX", "SPF", "TXT", "}", "top", ".", "each", "{", "|", "t", "|", "top_rrs", "[", "t", "]", "=", "@records", ".", "select", "{", "|", "rr", "|", "rr", ".", "type", "==", "t", "}", "}", "remaining", "=", "@records", ".", "reject", "{", "|", "rr", "|", "top", ".", "include?", "(", "rr", ".", "type", ")", "}", "remaining", ".", "sort!", "{", "|", "a", ",", "b", "|", "a", ".", "type", "<=>", "b", ".", "type", "}", "top_rrs", ".", "values", ".", "flatten", "+", "remaining", "end" ]
Records sorted with more important types being at the top. @api private
[ "Records", "sorted", "with", "more", "important", "types", "being", "at", "the", "top", "." ]
f60cbfd7ec72217288be6c6ece9a83c22350cb58
https://github.com/lantins/dns-zone/blob/f60cbfd7ec72217288be6c6ece9a83c22350cb58/lib/dns/zone.rb#L191-L203
train
potatosalad/ruby-erlang-terms
lib/erlang/associable.rb
Erlang.Associable.update_in
def update_in(*key_path, &block) if key_path.empty? raise ArgumentError, "must have at least one key in path" end key = key_path[0] if key_path.size == 1 new_value = block.call(fetch(key, nil)) else value = fetch(key, EmptyMap) new_value = value.update_in(*key_path[1..-1], &block) end return put(key, new_value) end
ruby
def update_in(*key_path, &block) if key_path.empty? raise ArgumentError, "must have at least one key in path" end key = key_path[0] if key_path.size == 1 new_value = block.call(fetch(key, nil)) else value = fetch(key, EmptyMap) new_value = value.update_in(*key_path[1..-1], &block) end return put(key, new_value) end
[ "def", "update_in", "(", "*", "key_path", ",", "&", "block", ")", "if", "key_path", ".", "empty?", "raise", "ArgumentError", ",", "\"must have at least one key in path\"", "end", "key", "=", "key_path", "[", "0", "]", "if", "key_path", ".", "size", "==", "1", "new_value", "=", "block", ".", "call", "(", "fetch", "(", "key", ",", "nil", ")", ")", "else", "value", "=", "fetch", "(", "key", ",", "EmptyMap", ")", "new_value", "=", "value", ".", "update_in", "(", "*", "key_path", "[", "1", "..", "-", "1", "]", ",", "&", "block", ")", "end", "return", "put", "(", "key", ",", "new_value", ")", "end" ]
Return a new container with a deeply nested value modified to the result of the given code block. When traversing the nested containers non-existing keys are created with empty `Hash` values. The code block receives the existing value of the deeply nested key/index (or `nil` if it doesn't exist). This is useful for "transforming" the value associated with a certain key/index. Naturally, the original container and sub-containers are left unmodified; new data structure copies are created along the path as needed. @example t = Erlang::Tuple[123, 456, 789, Erlang::Map["a" => Erlang::Tuple[5, 6, 7]]] t.update_in(3, "a", 1) { |value| value + 9 } # => Erlang::Tuple[123, 456, 789, Erlang::Map["a'" => Erlang::Tuple[5, 15, 7]]] map = Erlang::Map["a" => Erlang::Map["b" => Erlang::Map["c" => 42]]] map.update_in("a", "b", "c") { |value| value + 5 } # => Erlang::Map["a" => Erlang::Map["b" => Erlang::Map["c" => 47]]] @param key_path [Object(s)] List of keys/indexes which form the path to the key to be modified @yield [value] The previously stored value @yieldreturn [Object] The new value to store @return [Associable]
[ "Return", "a", "new", "container", "with", "a", "deeply", "nested", "value", "modified", "to", "the", "result", "of", "the", "given", "code", "block", ".", "When", "traversing", "the", "nested", "containers", "non", "-", "existing", "keys", "are", "created", "with", "empty", "Hash", "values", "." ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/associable.rb#L63-L75
train
potatosalad/ruby-erlang-terms
lib/erlang/associable.rb
Erlang.Associable.dig
def dig(key, *rest) value = get(key) if rest.empty? || value.nil? return value elsif value.respond_to?(:dig) return value.dig(*rest) end end
ruby
def dig(key, *rest) value = get(key) if rest.empty? || value.nil? return value elsif value.respond_to?(:dig) return value.dig(*rest) end end
[ "def", "dig", "(", "key", ",", "*", "rest", ")", "value", "=", "get", "(", "key", ")", "if", "rest", ".", "empty?", "||", "value", ".", "nil?", "return", "value", "elsif", "value", ".", "respond_to?", "(", ":dig", ")", "return", "value", ".", "dig", "(", "*", "rest", ")", "end", "end" ]
Return the value of successively indexing into a collection. If any of the keys is not present in the collection, return `nil`. keys that the Erlang type doesn't understand, raises an argument error @example m = Erlang::Map[:a => 9, :b => Erlang::Tuple['a', 'b'], :e => nil] m.dig(:b, 0) # => "a" m.dig(:b, 5) # => nil m.dig(:b, 0, 0) # => nil m.dig(:b, :a) # ArgumentError @param key to fetch from the collection @return [Object]
[ "Return", "the", "value", "of", "successively", "indexing", "into", "a", "collection", ".", "If", "any", "of", "the", "keys", "is", "not", "present", "in", "the", "collection", "return", "nil", ".", "keys", "that", "the", "Erlang", "type", "doesn", "t", "understand", "raises", "an", "argument", "error" ]
a3eaa3d976610466a5f5da177109a1248dac020d
https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/associable.rb#L89-L96
train
ustasb/pandata
lib/pandata/scraper.rb
Pandata.Scraper.download_all_data
def download_all_data(url) next_data_indices = {} while next_data_indices html = Downloader.read_page(url) # Sometimes Pandora returns the same next_data_indices as the previous page. # If we don't check for this, an infinite loop occurs. # This problem occurs with tconrad. prev_next_data_indices = next_data_indices next_data_indices = @parser.get_next_data_indices(html) next_data_indices = false if prev_next_data_indices == next_data_indices url = yield(html, next_data_indices) end end
ruby
def download_all_data(url) next_data_indices = {} while next_data_indices html = Downloader.read_page(url) # Sometimes Pandora returns the same next_data_indices as the previous page. # If we don't check for this, an infinite loop occurs. # This problem occurs with tconrad. prev_next_data_indices = next_data_indices next_data_indices = @parser.get_next_data_indices(html) next_data_indices = false if prev_next_data_indices == next_data_indices url = yield(html, next_data_indices) end end
[ "def", "download_all_data", "(", "url", ")", "next_data_indices", "=", "{", "}", "while", "next_data_indices", "html", "=", "Downloader", ".", "read_page", "(", "url", ")", "prev_next_data_indices", "=", "next_data_indices", "next_data_indices", "=", "@parser", ".", "get_next_data_indices", "(", "html", ")", "next_data_indices", "=", "false", "if", "prev_next_data_indices", "==", "next_data_indices", "url", "=", "yield", "(", "html", ",", "next_data_indices", ")", "end", "end" ]
Downloads all data given a starting URL. Some Pandora feeds only return 5 - 10 items per page but contain a link to the next set of data. Threads cannot be used because page A be must visited to know how to obtain page B. @param url [String]
[ "Downloads", "all", "data", "given", "a", "starting", "URL", ".", "Some", "Pandora", "feeds", "only", "return", "5", "-", "10", "items", "per", "page", "but", "contain", "a", "link", "to", "the", "next", "set", "of", "data", ".", "Threads", "cannot", "be", "used", "because", "page", "A", "be", "must", "visited", "to", "know", "how", "to", "obtain", "page", "B", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/scraper.rb#L119-L134
train
ustasb/pandata
lib/pandata/scraper.rb
Pandata.Scraper.get_url
def get_url(data_name, next_data_indices = {}) if next_data_indices.empty? next_data_indices = { nextStartIndex: 0, nextLikeStartIndex: 0, nextThumbStartIndex: 0 } else next_data_indices = next_data_indices.dup end next_data_indices[:webname] = @webname next_data_indices[:pat] = Downloader.get_pat DATA_FEED_URLS[data_name] % next_data_indices end
ruby
def get_url(data_name, next_data_indices = {}) if next_data_indices.empty? next_data_indices = { nextStartIndex: 0, nextLikeStartIndex: 0, nextThumbStartIndex: 0 } else next_data_indices = next_data_indices.dup end next_data_indices[:webname] = @webname next_data_indices[:pat] = Downloader.get_pat DATA_FEED_URLS[data_name] % next_data_indices end
[ "def", "get_url", "(", "data_name", ",", "next_data_indices", "=", "{", "}", ")", "if", "next_data_indices", ".", "empty?", "next_data_indices", "=", "{", "nextStartIndex", ":", "0", ",", "nextLikeStartIndex", ":", "0", ",", "nextThumbStartIndex", ":", "0", "}", "else", "next_data_indices", "=", "next_data_indices", ".", "dup", "end", "next_data_indices", "[", ":webname", "]", "=", "@webname", "next_data_indices", "[", ":pat", "]", "=", "Downloader", ".", "get_pat", "DATA_FEED_URLS", "[", "data_name", "]", "%", "next_data_indices", "end" ]
Grabs a URL from DATA_FEED_URLS and formats it appropriately. @param data_name [Symbol] @param next_data_indices [Symbol] query parameters to get the next set of data
[ "Grabs", "a", "URL", "from", "DATA_FEED_URLS", "and", "formats", "it", "appropriately", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/scraper.rb#L139-L150
train
dennisreimann/masq
app/models/masq/account.rb
Masq.Account.yubikey_authenticated?
def yubikey_authenticated?(otp) if yubico_identity? && Account.verify_yubico_otp(otp) (Account.extract_yubico_identity_from_otp(otp) == yubico_identity) else false end end
ruby
def yubikey_authenticated?(otp) if yubico_identity? && Account.verify_yubico_otp(otp) (Account.extract_yubico_identity_from_otp(otp) == yubico_identity) else false end end
[ "def", "yubikey_authenticated?", "(", "otp", ")", "if", "yubico_identity?", "&&", "Account", ".", "verify_yubico_otp", "(", "otp", ")", "(", "Account", ".", "extract_yubico_identity_from_otp", "(", "otp", ")", "==", "yubico_identity", ")", "else", "false", "end", "end" ]
Is the Yubico OTP valid and belongs to this account?
[ "Is", "the", "Yubico", "OTP", "valid", "and", "belongs", "to", "this", "account?" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/account.rb#L127-L133
train
qoobaa/vcard
lib/vcard/dirinfo.rb
Vcard.DirectoryInfo.[]
def [](name) enum_by_name(name).each { |f| return f.value if f.value != ""} enum_by_name(name).each { |f| return f.value } nil end
ruby
def [](name) enum_by_name(name).each { |f| return f.value if f.value != ""} enum_by_name(name).each { |f| return f.value } nil end
[ "def", "[]", "(", "name", ")", "enum_by_name", "(", "name", ")", ".", "each", "{", "|", "f", "|", "return", "f", ".", "value", "if", "f", ".", "value", "!=", "\"\"", "}", "enum_by_name", "(", "name", ")", ".", "each", "{", "|", "f", "|", "return", "f", ".", "value", "}", "nil", "end" ]
The value of the first field named +name+, or nil if no match is found.
[ "The", "value", "of", "the", "first", "field", "named", "+", "name", "+", "or", "nil", "if", "no", "match", "is", "found", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/dirinfo.rb#L113-L117
train
qoobaa/vcard
lib/vcard/dirinfo.rb
Vcard.DirectoryInfo.push_unique
def push_unique(field) push(field) unless @fields.detect { |f| f.name? field.name } self end
ruby
def push_unique(field) push(field) unless @fields.detect { |f| f.name? field.name } self end
[ "def", "push_unique", "(", "field", ")", "push", "(", "field", ")", "unless", "@fields", ".", "detect", "{", "|", "f", "|", "f", ".", "name?", "field", ".", "name", "}", "self", "end" ]
Push +field+ onto the fields, unless there is already a field with this name.
[ "Push", "+", "field", "+", "onto", "the", "fields", "unless", "there", "is", "already", "a", "field", "with", "this", "name", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/dirinfo.rb#L212-L215
train
qoobaa/vcard
lib/vcard/dirinfo.rb
Vcard.DirectoryInfo.delete
def delete(field) case when field.name?("BEGIN"), field.name?("END") raise ArgumentError, "Cannot delete BEGIN or END fields." else @fields.delete field end self end
ruby
def delete(field) case when field.name?("BEGIN"), field.name?("END") raise ArgumentError, "Cannot delete BEGIN or END fields." else @fields.delete field end self end
[ "def", "delete", "(", "field", ")", "case", "when", "field", ".", "name?", "(", "\"BEGIN\"", ")", ",", "field", ".", "name?", "(", "\"END\"", ")", "raise", "ArgumentError", ",", "\"Cannot delete BEGIN or END fields.\"", "else", "@fields", ".", "delete", "field", "end", "self", "end" ]
Delete +field+. Warning: You can't delete BEGIN: or END: fields, but other profile-specific fields can be deleted, including mandatory ones. For vCards in particular, in order to avoid destroying them, I suggest creating a new Vcard, and copying over all the fields that you still want, rather than using #delete. This is easy with Vcard::Maker#copy, see the Vcard::Maker examples.
[ "Delete", "+", "field", "+", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/dirinfo.rb#L233-L242
train
tomharris/random_data
lib/random_data/numbers.rb
RandomData.Numbers.number
def number(n) n.is_a?(Range) ? n.to_a.rand : rand(n) end
ruby
def number(n) n.is_a?(Range) ? n.to_a.rand : rand(n) end
[ "def", "number", "(", "n", ")", "n", ".", "is_a?", "(", "Range", ")", "?", "n", ".", "to_a", ".", "rand", ":", "rand", "(", "n", ")", "end" ]
n can be an Integer or a Range. If it is an Integer, it just returns a random number greater than or equal to 0 and less than n. If it is a Range, it returns a random number within the range Examples >> Random.number(5) => 4 >> Random.number(5) => 2 >> Random.number(5) => 1
[ "n", "can", "be", "an", "Integer", "or", "a", "Range", ".", "If", "it", "is", "an", "Integer", "it", "just", "returns", "a", "random", "number", "greater", "than", "or", "equal", "to", "0", "and", "less", "than", "n", ".", "If", "it", "is", "a", "Range", "it", "returns", "a", "random", "number", "within", "the", "range", "Examples" ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/numbers.rb#L14-L16
train
rmosolgo/css_modules
lib/css_modules/rewrite.rb
CSSModules.Rewrite.rewrite_css
def rewrite_css(css_module_code) # Parse incoming CSS into an AST css_root = Sass::SCSS::CssParser.new(css_module_code, "(CSSModules)", 1).parse Sass::Tree::Visitors::SetOptions.visit(css_root, {}) ModuleVisitor.visit(css_root) css_root.render end
ruby
def rewrite_css(css_module_code) # Parse incoming CSS into an AST css_root = Sass::SCSS::CssParser.new(css_module_code, "(CSSModules)", 1).parse Sass::Tree::Visitors::SetOptions.visit(css_root, {}) ModuleVisitor.visit(css_root) css_root.render end
[ "def", "rewrite_css", "(", "css_module_code", ")", "css_root", "=", "Sass", "::", "SCSS", "::", "CssParser", ".", "new", "(", "css_module_code", ",", "\"(CSSModules)\"", ",", "1", ")", ".", "parse", "Sass", "::", "Tree", "::", "Visitors", "::", "SetOptions", ".", "visit", "(", "css_root", ",", "{", "}", ")", "ModuleVisitor", ".", "visit", "(", "css_root", ")", "css_root", ".", "render", "end" ]
Take css module code as input, and rewrite it as browser-friendly CSS code. Apply opaque transformations so that selectors can only be accessed programatically, not by class name literals.
[ "Take", "css", "module", "code", "as", "input", "and", "rewrite", "it", "as", "browser", "-", "friendly", "CSS", "code", ".", "Apply", "opaque", "transformations", "so", "that", "selectors", "can", "only", "be", "accessed", "programatically", "not", "by", "class", "name", "literals", "." ]
c1a80f6b7b76193c7dda616877a75eec6bbe600d
https://github.com/rmosolgo/css_modules/blob/c1a80f6b7b76193c7dda616877a75eec6bbe600d/lib/css_modules/rewrite.rb#L15-L23
train
tomharris/random_data
lib/random_data/grammar.rb
RandomData.Grammar.grammatical_construct
def grammatical_construct(grammar, what=nil) output = "" if what.nil? case grammar when Hash a_key = grammar.keys.sort_by{rand}[0] output += grammatical_construct(grammar, a_key) when Array grammar.each do |item| output += grammatical_construct(item) end when String output += grammar end else rhs = grammar[what] case rhs when Array rhs.each do |item| case item when Symbol output += grammatical_construct(grammar,item) when String output += item when Hash output += grammatical_construct(item) else raise "#{item.inspect} must be a symbol or string or Hash" end end when Hash output+= grammatical_construct(rhs) when Symbol output += grammatical_construct(rhs) when String output += rhs else raise "#{rhs.inspect} must be a symbol, string, Array or Hash" end end return output end
ruby
def grammatical_construct(grammar, what=nil) output = "" if what.nil? case grammar when Hash a_key = grammar.keys.sort_by{rand}[0] output += grammatical_construct(grammar, a_key) when Array grammar.each do |item| output += grammatical_construct(item) end when String output += grammar end else rhs = grammar[what] case rhs when Array rhs.each do |item| case item when Symbol output += grammatical_construct(grammar,item) when String output += item when Hash output += grammatical_construct(item) else raise "#{item.inspect} must be a symbol or string or Hash" end end when Hash output+= grammatical_construct(rhs) when Symbol output += grammatical_construct(rhs) when String output += rhs else raise "#{rhs.inspect} must be a symbol, string, Array or Hash" end end return output end
[ "def", "grammatical_construct", "(", "grammar", ",", "what", "=", "nil", ")", "output", "=", "\"\"", "if", "what", ".", "nil?", "case", "grammar", "when", "Hash", "a_key", "=", "grammar", ".", "keys", ".", "sort_by", "{", "rand", "}", "[", "0", "]", "output", "+=", "grammatical_construct", "(", "grammar", ",", "a_key", ")", "when", "Array", "grammar", ".", "each", "do", "|", "item", "|", "output", "+=", "grammatical_construct", "(", "item", ")", "end", "when", "String", "output", "+=", "grammar", "end", "else", "rhs", "=", "grammar", "[", "what", "]", "case", "rhs", "when", "Array", "rhs", ".", "each", "do", "|", "item", "|", "case", "item", "when", "Symbol", "output", "+=", "grammatical_construct", "(", "grammar", ",", "item", ")", "when", "String", "output", "+=", "item", "when", "Hash", "output", "+=", "grammatical_construct", "(", "item", ")", "else", "raise", "\"#{item.inspect} must be a symbol or string or Hash\"", "end", "end", "when", "Hash", "output", "+=", "grammatical_construct", "(", "rhs", ")", "when", "Symbol", "output", "+=", "grammatical_construct", "(", "rhs", ")", "when", "String", "output", "+=", "rhs", "else", "raise", "\"#{rhs.inspect} must be a symbol, string, Array or Hash\"", "end", "end", "return", "output", "end" ]
Returns simple sentences based on a supplied grammar, which must be a hash, the keys of which are symbols. The values are either an array of successive values or a grammar (i.e, hash with symbols as keys, and hashes or arrays as values. The arrays contain symbols referencing the keys in the present grammar, or strings to be output. The keys are always symbols. Example: Random.grammatical_construct({:story => [:man, " bites ", :dog], :man => { :bob => "Bob"}, :dog => {:a =>"Rex", :b =>"Rover"}}, :story) => "Bob bites Rover"
[ "Returns", "simple", "sentences", "based", "on", "a", "supplied", "grammar", "which", "must", "be", "a", "hash", "the", "keys", "of", "which", "are", "symbols", ".", "The", "values", "are", "either", "an", "array", "of", "successive", "values", "or", "a", "grammar", "(", "i", ".", "e", "hash", "with", "symbols", "as", "keys", "and", "hashes", "or", "arrays", "as", "values", ".", "The", "arrays", "contain", "symbols", "referencing", "the", "keys", "in", "the", "present", "grammar", "or", "strings", "to", "be", "output", ".", "The", "keys", "are", "always", "symbols", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/grammar.rb#L17-L58
train
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/location.rb
GoogleStaticMapsHelper.Location.endpoints_for_circle_with_radius
def endpoints_for_circle_with_radius(radius, steps = 30) raise ArgumentError, "Number of points has to be in range of 1..360!" unless (1..360).include? steps points = [] steps.times do |i| points << endpoint(radius, i * 360 / steps) end points << points.first points end
ruby
def endpoints_for_circle_with_radius(radius, steps = 30) raise ArgumentError, "Number of points has to be in range of 1..360!" unless (1..360).include? steps points = [] steps.times do |i| points << endpoint(radius, i * 360 / steps) end points << points.first points end
[ "def", "endpoints_for_circle_with_radius", "(", "radius", ",", "steps", "=", "30", ")", "raise", "ArgumentError", ",", "\"Number of points has to be in range of 1..360!\"", "unless", "(", "1", "..", "360", ")", ".", "include?", "steps", "points", "=", "[", "]", "steps", ".", "times", "do", "|", "i", "|", "points", "<<", "endpoint", "(", "radius", ",", "i", "*", "360", "/", "steps", ")", "end", "points", "<<", "points", ".", "first", "points", "end" ]
Returns ends poionts which will make up a circle around current location and have given radius
[ "Returns", "ends", "poionts", "which", "will", "make", "up", "a", "circle", "around", "current", "location", "and", "have", "given", "radius" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/location.rb#L81-L91
train
tomharris/random_data
lib/random_data/names.rb
RandomData.Names.companyname
def companyname num = rand(5) if num == 0 num = 1 end final = num.times.collect { @@lastnames.rand.capitalize } if final.count == 1 "#{final.first} #{@@company_types.rand}, #{@@incorporation_types.rand}" else incorporation_type = rand(17) % 2 == 0 ? @@incorporation_types.rand : nil company_type = rand(17) % 2 == 0 ? @@company_types.rand : nil trailer = company_type.nil? ? "" : " #{company_type}" trailer << ", #{incorporation_type}" unless incorporation_type.nil? "#{final[0..-1].join(', ')} & #{final.last}#{trailer}" end end
ruby
def companyname num = rand(5) if num == 0 num = 1 end final = num.times.collect { @@lastnames.rand.capitalize } if final.count == 1 "#{final.first} #{@@company_types.rand}, #{@@incorporation_types.rand}" else incorporation_type = rand(17) % 2 == 0 ? @@incorporation_types.rand : nil company_type = rand(17) % 2 == 0 ? @@company_types.rand : nil trailer = company_type.nil? ? "" : " #{company_type}" trailer << ", #{incorporation_type}" unless incorporation_type.nil? "#{final[0..-1].join(', ')} & #{final.last}#{trailer}" end end
[ "def", "companyname", "num", "=", "rand", "(", "5", ")", "if", "num", "==", "0", "num", "=", "1", "end", "final", "=", "num", ".", "times", ".", "collect", "{", "@@lastnames", ".", "rand", ".", "capitalize", "}", "if", "final", ".", "count", "==", "1", "\"#{final.first} #{@@company_types.rand}, #{@@incorporation_types.rand}\"", "else", "incorporation_type", "=", "rand", "(", "17", ")", "%", "2", "==", "0", "?", "@@incorporation_types", ".", "rand", ":", "nil", "company_type", "=", "rand", "(", "17", ")", "%", "2", "==", "0", "?", "@@company_types", ".", "rand", ":", "nil", "trailer", "=", "company_type", ".", "nil?", "?", "\"\"", ":", "\" #{company_type}\"", "trailer", "<<", "\", #{incorporation_type}\"", "unless", "incorporation_type", ".", "nil?", "\"#{final[0..-1].join(', ')} & #{final.last}#{trailer}\"", "end", "end" ]
Returns a random company name >> Random.company_name "Harris & Thomas"
[ "Returns", "a", "random", "company", "name" ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/names.rb#L26-L42
train
jhass/open_graph_reader
lib/open_graph_reader/builder.rb
OpenGraphReader.Builder.base
def base base = Base.new type = @parser.graph.fetch("og:type", "website").downcase validate_type type @parser.graph.each do |property| build_property base, property end synthesize_required_properties base drop_empty_children base validate base base end
ruby
def base base = Base.new type = @parser.graph.fetch("og:type", "website").downcase validate_type type @parser.graph.each do |property| build_property base, property end synthesize_required_properties base drop_empty_children base validate base base end
[ "def", "base", "base", "=", "Base", ".", "new", "type", "=", "@parser", ".", "graph", ".", "fetch", "(", "\"og:type\"", ",", "\"website\"", ")", ".", "downcase", "validate_type", "type", "@parser", ".", "graph", ".", "each", "do", "|", "property", "|", "build_property", "base", ",", "property", "end", "synthesize_required_properties", "base", "drop_empty_children", "base", "validate", "base", "base", "end" ]
Create a new builder. @param [Parser] parser @see Parser#graph @see Parser#additional_namespaces Build and return the base. @return [Base]
[ "Create", "a", "new", "builder", "." ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/builder.rb#L24-L40
train
dennisreimann/masq
app/helpers/masq/application_helper.rb
Masq.ApplicationHelper.nav
def nav(name, url, pages = nil, active = false) content_tag :li, link_to(name, url), :class => (active || (pages && active_page?(pages)) ? 'act' : nil) end
ruby
def nav(name, url, pages = nil, active = false) content_tag :li, link_to(name, url), :class => (active || (pages && active_page?(pages)) ? 'act' : nil) end
[ "def", "nav", "(", "name", ",", "url", ",", "pages", "=", "nil", ",", "active", "=", "false", ")", "content_tag", ":li", ",", "link_to", "(", "name", ",", "url", ")", ",", ":class", "=>", "(", "active", "||", "(", "pages", "&&", "active_page?", "(", "pages", ")", ")", "?", "'act'", ":", "nil", ")", "end" ]
Renders a navigation element and marks it as active where appropriate. See active_page? for details
[ "Renders", "a", "navigation", "element", "and", "marks", "it", "as", "active", "where", "appropriate", ".", "See", "active_page?", "for", "details" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/helpers/masq/application_helper.rb#L45-L47
train
dennisreimann/masq
app/helpers/masq/application_helper.rb
Masq.ApplicationHelper.active_page?
def active_page?(pages = {}) is_active = pages.include?(params[:controller]) is_active = pages[params[:controller]].include?(params[:action]) if is_active && !pages[params[:controller]].empty? is_active end
ruby
def active_page?(pages = {}) is_active = pages.include?(params[:controller]) is_active = pages[params[:controller]].include?(params[:action]) if is_active && !pages[params[:controller]].empty? is_active end
[ "def", "active_page?", "(", "pages", "=", "{", "}", ")", "is_active", "=", "pages", ".", "include?", "(", "params", "[", ":controller", "]", ")", "is_active", "=", "pages", "[", "params", "[", ":controller", "]", "]", ".", "include?", "(", "params", "[", ":action", "]", ")", "if", "is_active", "&&", "!", "pages", "[", "params", "[", ":controller", "]", "]", ".", "empty?", "is_active", "end" ]
Takes a hash with pages and tells whether the current page is among them. The keys must be controller names and their value must be an array of action names. If the array is empty, every action is supposed to be valid.
[ "Takes", "a", "hash", "with", "pages", "and", "tells", "whether", "the", "current", "page", "is", "among", "them", ".", "The", "keys", "must", "be", "controller", "names", "and", "their", "value", "must", "be", "an", "array", "of", "action", "names", ".", "If", "the", "array", "is", "empty", "every", "action", "is", "supposed", "to", "be", "valid", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/helpers/masq/application_helper.rb#L52-L56
train
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.get_webnames_from_search
def get_webnames_from_search(html) user_links = Nokogiri::HTML(html).css('.user_name a') webnames = [] user_links.each do |link| webnames << link['webname'] end webnames end
ruby
def get_webnames_from_search(html) user_links = Nokogiri::HTML(html).css('.user_name a') webnames = [] user_links.each do |link| webnames << link['webname'] end webnames end
[ "def", "get_webnames_from_search", "(", "html", ")", "user_links", "=", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.user_name a'", ")", "webnames", "=", "[", "]", "user_links", ".", "each", "do", "|", "link", "|", "webnames", "<<", "link", "[", "'webname'", "]", "end", "webnames", "end" ]
Get the webnames from a user ID search. @param html [String] @return [Array] array of webnames
[ "Get", "the", "webnames", "from", "a", "user", "ID", "search", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L11-L20
train
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.get_next_data_indices
def get_next_data_indices(html) # .js-more-link is found on mobile pages. show_more = Nokogiri::HTML(html).css('.show_more, .js-more-link')[0] if show_more next_indices = {} data_attributes = ['nextStartIndex', 'nextLikeStartIndex', 'nextThumbStartIndex'] data_attributes.each do |attr_name| attr = show_more.attributes['data-' + attr_name.downcase] next_indices[attr_name.to_sym] = attr.value.to_i if attr end next_indices else false end end
ruby
def get_next_data_indices(html) # .js-more-link is found on mobile pages. show_more = Nokogiri::HTML(html).css('.show_more, .js-more-link')[0] if show_more next_indices = {} data_attributes = ['nextStartIndex', 'nextLikeStartIndex', 'nextThumbStartIndex'] data_attributes.each do |attr_name| attr = show_more.attributes['data-' + attr_name.downcase] next_indices[attr_name.to_sym] = attr.value.to_i if attr end next_indices else false end end
[ "def", "get_next_data_indices", "(", "html", ")", "show_more", "=", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.show_more, .js-more-link'", ")", "[", "0", "]", "if", "show_more", "next_indices", "=", "{", "}", "data_attributes", "=", "[", "'nextStartIndex'", ",", "'nextLikeStartIndex'", ",", "'nextThumbStartIndex'", "]", "data_attributes", ".", "each", "do", "|", "attr_name", "|", "attr", "=", "show_more", ".", "attributes", "[", "'data-'", "+", "attr_name", ".", "downcase", "]", "next_indices", "[", "attr_name", ".", "to_sym", "]", "=", "attr", ".", "value", ".", "to_i", "if", "attr", "end", "next_indices", "else", "false", "end", "end" ]
Get the query parameters necessary to get the next page of data from Pandora. @param html [String] @return [Hash, False]
[ "Get", "the", "query", "parameters", "necessary", "to", "get", "the", "next", "page", "of", "data", "from", "Pandora", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L25-L41
train
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.infobox_each_link
def infobox_each_link(html) Nokogiri::HTML(html).css('.infobox').each do |infobox| infobox_body = infobox.css('.infobox-body') title_link = infobox_body.css('h3 a').text.strip subtitle_link = infobox_body.css('p a').first subtitle_link = subtitle_link.text.strip if subtitle_link yield(title_link, subtitle_link) end end
ruby
def infobox_each_link(html) Nokogiri::HTML(html).css('.infobox').each do |infobox| infobox_body = infobox.css('.infobox-body') title_link = infobox_body.css('h3 a').text.strip subtitle_link = infobox_body.css('p a').first subtitle_link = subtitle_link.text.strip if subtitle_link yield(title_link, subtitle_link) end end
[ "def", "infobox_each_link", "(", "html", ")", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.infobox'", ")", ".", "each", "do", "|", "infobox", "|", "infobox_body", "=", "infobox", ".", "css", "(", "'.infobox-body'", ")", "title_link", "=", "infobox_body", ".", "css", "(", "'h3 a'", ")", ".", "text", ".", "strip", "subtitle_link", "=", "infobox_body", ".", "css", "(", "'p a'", ")", ".", "first", "subtitle_link", "=", "subtitle_link", ".", "text", ".", "strip", "if", "subtitle_link", "yield", "(", "title_link", ",", "subtitle_link", ")", "end", "end" ]
Loops over each .infobox container and yields the title and subtitle. @param html [String]
[ "Loops", "over", "each", ".", "infobox", "container", "and", "yields", "the", "title", "and", "subtitle", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L96-L106
train
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.doublelink_each_link
def doublelink_each_link(html) Nokogiri::HTML(html).css('.double-link').each do |doublelink| title_link = doublelink.css('.media__bd__header').text.strip subtitle_link = doublelink.css('.media__bd__subheader').text.strip yield(title_link, subtitle_link) end end
ruby
def doublelink_each_link(html) Nokogiri::HTML(html).css('.double-link').each do |doublelink| title_link = doublelink.css('.media__bd__header').text.strip subtitle_link = doublelink.css('.media__bd__subheader').text.strip yield(title_link, subtitle_link) end end
[ "def", "doublelink_each_link", "(", "html", ")", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.double-link'", ")", ".", "each", "do", "|", "doublelink", "|", "title_link", "=", "doublelink", ".", "css", "(", "'.media__bd__header'", ")", ".", "text", ".", "strip", "subtitle_link", "=", "doublelink", ".", "css", "(", "'.media__bd__subheader'", ")", ".", "text", ".", "strip", "yield", "(", "title_link", ",", "subtitle_link", ")", "end", "end" ]
Loops over each .double-link container and yields the title and subtitle. Encountered on mobile pages. @param html [String]
[ "Loops", "over", "each", ".", "double", "-", "link", "container", "and", "yields", "the", "title", "and", "subtitle", ".", "Encountered", "on", "mobile", "pages", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L111-L118
train
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.get_followx_users
def get_followx_users(html) users = [] Nokogiri::HTML(html).css('.follow_section').each do |section| listener_name = section.css('.listener_name').first webname = listener_name['webname'] # Remove any 'spans with a space' that sometimes appear with special characters. listener_name.css('span').each(&:remove) name = listener_name.text.strip href = section.css('a').first['href'] users << { name: name, webname: webname, href: href } end users end
ruby
def get_followx_users(html) users = [] Nokogiri::HTML(html).css('.follow_section').each do |section| listener_name = section.css('.listener_name').first webname = listener_name['webname'] # Remove any 'spans with a space' that sometimes appear with special characters. listener_name.css('span').each(&:remove) name = listener_name.text.strip href = section.css('a').first['href'] users << { name: name, webname: webname, href: href } end users end
[ "def", "get_followx_users", "(", "html", ")", "users", "=", "[", "]", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.follow_section'", ")", ".", "each", "do", "|", "section", "|", "listener_name", "=", "section", ".", "css", "(", "'.listener_name'", ")", ".", "first", "webname", "=", "listener_name", "[", "'webname'", "]", "listener_name", ".", "css", "(", "'span'", ")", ".", "each", "(", "&", ":remove", ")", "name", "=", "listener_name", ".", "text", ".", "strip", "href", "=", "section", ".", "css", "(", "'a'", ")", ".", "first", "[", "'href'", "]", "users", "<<", "{", "name", ":", "name", ",", "webname", ":", "webname", ",", "href", ":", "href", "}", "end", "users", "end" ]
Loops over each .follow_section container. @param html [String] @return [Hash] with keys :name, :webname and :href
[ "Loops", "over", "each", ".", "follow_section", "container", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L132-L149
train
piotrmurach/tty-platform
lib/tty/platform.rb
TTY.Platform.detect_system_properties
def detect_system_properties(arch) parts = (arch || architecture).split('-', 2) if parts.length == 1 @cpu, system = nil, parts.shift else @cpu, system = *parts end @os, @version = *find_os_and_version(system) [@cpu, @os, @version] end
ruby
def detect_system_properties(arch) parts = (arch || architecture).split('-', 2) if parts.length == 1 @cpu, system = nil, parts.shift else @cpu, system = *parts end @os, @version = *find_os_and_version(system) [@cpu, @os, @version] end
[ "def", "detect_system_properties", "(", "arch", ")", "parts", "=", "(", "arch", "||", "architecture", ")", ".", "split", "(", "'-'", ",", "2", ")", "if", "parts", ".", "length", "==", "1", "@cpu", ",", "system", "=", "nil", ",", "parts", ".", "shift", "else", "@cpu", ",", "system", "=", "*", "parts", "end", "@os", ",", "@version", "=", "*", "find_os_and_version", "(", "system", ")", "[", "@cpu", ",", "@os", ",", "@version", "]", "end" ]
Infer system properties from architecture information @return [Array[String, String String]] @api private
[ "Infer", "system", "properties", "from", "architecture", "information" ]
ef35579edc941e79b9bbe1ce3952b961088e2210
https://github.com/piotrmurach/tty-platform/blob/ef35579edc941e79b9bbe1ce3952b961088e2210/lib/tty/platform.rb#L104-L114
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.decide
def decide @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root) @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request end
ruby
def decide @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root) @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request end
[ "def", "decide", "@site", "=", "current_account", ".", "sites", ".", "find_or_initialize_by_url", "(", "checkid_request", ".", "trust_root", ")", "@site", ".", "persona", "=", "current_account", ".", "personas", ".", "find", "(", "params", "[", ":persona_id", "]", "||", ":first", ")", "if", "sreg_request", "||", "ax_store_request", "||", "ax_fetch_request", "end" ]
Displays the decision page on that the user can confirm the request and choose which data should be transfered to the relying party.
[ "Displays", "the", "decision", "page", "on", "that", "the", "user", "can", "confirm", "the", "request", "and", "choose", "which", "data", "should", "be", "transfered", "to", "the", "relying", "party", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L64-L67
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.complete
def complete if params[:cancel] cancel else resp = checkid_request.answer(true, nil, identifier(current_account)) if params[:always] @site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.update_attributes(params[:site]) elsif sreg_request || ax_fetch_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.attributes = params[:site] elsif ax_store_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) not_supported, not_accepted, accepted = [], [], [] ax_store_request.data.each do |type_uri, values| if property = Persona.attribute_name_for_type_uri(type_uri) store_attribute = params[:site][:ax_store][property.to_sym] if store_attribute && !store_attribute[:value].blank? @site.persona.update_attribute(property, values.first) accepted << type_uri else not_accepted << type_uri end else not_supported << type_uri end end ax_store_response = (accepted.count > 0) ? OpenID::AX::StoreResponse.new : OpenID::AX::StoreResponse.new(false, "None of the attributes were accepted.") resp.add_extension(ax_store_response) end resp = add_pape(resp, auth_policies, auth_level, auth_time) resp = add_sreg(resp, @site.sreg_properties) if sreg_request && @site.sreg_properties resp = add_ax(resp, @site.ax_properties) if ax_fetch_request && @site.ax_properties render_response(resp) end end
ruby
def complete if params[:cancel] cancel else resp = checkid_request.answer(true, nil, identifier(current_account)) if params[:always] @site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.update_attributes(params[:site]) elsif sreg_request || ax_fetch_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.attributes = params[:site] elsif ax_store_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) not_supported, not_accepted, accepted = [], [], [] ax_store_request.data.each do |type_uri, values| if property = Persona.attribute_name_for_type_uri(type_uri) store_attribute = params[:site][:ax_store][property.to_sym] if store_attribute && !store_attribute[:value].blank? @site.persona.update_attribute(property, values.first) accepted << type_uri else not_accepted << type_uri end else not_supported << type_uri end end ax_store_response = (accepted.count > 0) ? OpenID::AX::StoreResponse.new : OpenID::AX::StoreResponse.new(false, "None of the attributes were accepted.") resp.add_extension(ax_store_response) end resp = add_pape(resp, auth_policies, auth_level, auth_time) resp = add_sreg(resp, @site.sreg_properties) if sreg_request && @site.sreg_properties resp = add_ax(resp, @site.ax_properties) if ax_fetch_request && @site.ax_properties render_response(resp) end end
[ "def", "complete", "if", "params", "[", ":cancel", "]", "cancel", "else", "resp", "=", "checkid_request", ".", "answer", "(", "true", ",", "nil", ",", "identifier", "(", "current_account", ")", ")", "if", "params", "[", ":always", "]", "@site", "=", "current_account", ".", "sites", ".", "find_or_create_by_persona_id_and_url", "(", "params", "[", ":site", "]", "[", ":persona_id", "]", ",", "params", "[", ":site", "]", "[", ":url", "]", ")", "@site", ".", "update_attributes", "(", "params", "[", ":site", "]", ")", "elsif", "sreg_request", "||", "ax_fetch_request", "@site", "=", "current_account", ".", "sites", ".", "find_or_initialize_by_persona_id_and_url", "(", "params", "[", ":site", "]", "[", ":persona_id", "]", ",", "params", "[", ":site", "]", "[", ":url", "]", ")", "@site", ".", "attributes", "=", "params", "[", ":site", "]", "elsif", "ax_store_request", "@site", "=", "current_account", ".", "sites", ".", "find_or_initialize_by_persona_id_and_url", "(", "params", "[", ":site", "]", "[", ":persona_id", "]", ",", "params", "[", ":site", "]", "[", ":url", "]", ")", "not_supported", ",", "not_accepted", ",", "accepted", "=", "[", "]", ",", "[", "]", ",", "[", "]", "ax_store_request", ".", "data", ".", "each", "do", "|", "type_uri", ",", "values", "|", "if", "property", "=", "Persona", ".", "attribute_name_for_type_uri", "(", "type_uri", ")", "store_attribute", "=", "params", "[", ":site", "]", "[", ":ax_store", "]", "[", "property", ".", "to_sym", "]", "if", "store_attribute", "&&", "!", "store_attribute", "[", ":value", "]", ".", "blank?", "@site", ".", "persona", ".", "update_attribute", "(", "property", ",", "values", ".", "first", ")", "accepted", "<<", "type_uri", "else", "not_accepted", "<<", "type_uri", "end", "else", "not_supported", "<<", "type_uri", "end", "end", "ax_store_response", "=", "(", "accepted", ".", "count", ">", "0", ")", "?", "OpenID", "::", "AX", "::", "StoreResponse", ".", "new", ":", "OpenID", "::", "AX", "::", "StoreResponse", ".", "new", "(", "false", ",", "\"None of the attributes were accepted.\"", ")", "resp", ".", "add_extension", "(", "ax_store_response", ")", "end", "resp", "=", "add_pape", "(", "resp", ",", "auth_policies", ",", "auth_level", ",", "auth_time", ")", "resp", "=", "add_sreg", "(", "resp", ",", "@site", ".", "sreg_properties", ")", "if", "sreg_request", "&&", "@site", ".", "sreg_properties", "resp", "=", "add_ax", "(", "resp", ",", "@site", ".", "ax_properties", ")", "if", "ax_fetch_request", "&&", "@site", ".", "ax_properties", "render_response", "(", "resp", ")", "end", "end" ]
This action is called by submitting the decision form, the information entered by the user is used to answer the request. If the user decides to always trust the relying party, a new site according to the release policies the will be created.
[ "This", "action", "is", "called", "by", "submitting", "the", "decision", "form", "the", "information", "entered", "by", "the", "user", "is", "used", "to", "answer", "the", "request", ".", "If", "the", "user", "decides", "to", "always", "trust", "the", "relying", "party", "a", "new", "site", "according", "to", "the", "release", "policies", "the", "will", "be", "created", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L72-L107
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.handle_checkid_request
def handle_checkid_request if allow_verification? save_checkid_request redirect_to proceed_path elsif openid_request.immediate render_response(openid_request.answer(false)) else reset_session request = save_checkid_request session[:return_to] = proceed_path redirect_to( request.from_trusted_domain? ? login_path : safe_login_path ) end end
ruby
def handle_checkid_request if allow_verification? save_checkid_request redirect_to proceed_path elsif openid_request.immediate render_response(openid_request.answer(false)) else reset_session request = save_checkid_request session[:return_to] = proceed_path redirect_to( request.from_trusted_domain? ? login_path : safe_login_path ) end end
[ "def", "handle_checkid_request", "if", "allow_verification?", "save_checkid_request", "redirect_to", "proceed_path", "elsif", "openid_request", ".", "immediate", "render_response", "(", "openid_request", ".", "answer", "(", "false", ")", ")", "else", "reset_session", "request", "=", "save_checkid_request", "session", "[", ":return_to", "]", "=", "proceed_path", "redirect_to", "(", "request", ".", "from_trusted_domain?", "?", "login_path", ":", "safe_login_path", ")", "end", "end" ]
Decides how to process an incoming checkid request. If the user is already logged in he will be forwarded to the proceed action. If the user is not logged in and the request is immediate, the request cannot be answered successfully. In case the user is not logged in, the request will be stored and the user is asked to log in.
[ "Decides", "how", "to", "process", "an", "incoming", "checkid", "request", ".", "If", "the", "user", "is", "already", "logged", "in", "he", "will", "be", "forwarded", "to", "the", "proceed", "action", ".", "If", "the", "user", "is", "not", "logged", "in", "and", "the", "request", "is", "immediate", "the", "request", "cannot", "be", "answered", "successfully", ".", "In", "case", "the", "user", "is", "not", "logged", "in", "the", "request", "will", "be", "stored", "and", "the", "user", "is", "asked", "to", "log", "in", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L121-L133
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.save_checkid_request
def save_checkid_request clear_checkid_request request = OpenIdRequest.create!(:parameters => openid_params) session[:request_token] = request.token request end
ruby
def save_checkid_request clear_checkid_request request = OpenIdRequest.create!(:parameters => openid_params) session[:request_token] = request.token request end
[ "def", "save_checkid_request", "clear_checkid_request", "request", "=", "OpenIdRequest", ".", "create!", "(", ":parameters", "=>", "openid_params", ")", "session", "[", ":request_token", "]", "=", "request", ".", "token", "request", "end" ]
Stores the current OpenID request. Returns the OpenIdRequest
[ "Stores", "the", "current", "OpenID", "request", ".", "Returns", "the", "OpenIdRequest" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L137-L143
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.ensure_valid_checkid_request
def ensure_valid_checkid_request self.openid_request = checkid_request if !openid_request.is_a?(OpenID::Server::CheckIDRequest) redirect_to root_path, :alert => t(:identity_verification_request_invalid) elsif !allow_verification? flash[:notice] = logged_in? && !pape_requirements_met?(auth_time) ? t(:service_provider_requires_reauthentication_last_login_too_long_ago) : t(:login_to_verify_identity) session[:return_to] = proceed_path redirect_to login_path end end
ruby
def ensure_valid_checkid_request self.openid_request = checkid_request if !openid_request.is_a?(OpenID::Server::CheckIDRequest) redirect_to root_path, :alert => t(:identity_verification_request_invalid) elsif !allow_verification? flash[:notice] = logged_in? && !pape_requirements_met?(auth_time) ? t(:service_provider_requires_reauthentication_last_login_too_long_ago) : t(:login_to_verify_identity) session[:return_to] = proceed_path redirect_to login_path end end
[ "def", "ensure_valid_checkid_request", "self", ".", "openid_request", "=", "checkid_request", "if", "!", "openid_request", ".", "is_a?", "(", "OpenID", "::", "Server", "::", "CheckIDRequest", ")", "redirect_to", "root_path", ",", ":alert", "=>", "t", "(", ":identity_verification_request_invalid", ")", "elsif", "!", "allow_verification?", "flash", "[", ":notice", "]", "=", "logged_in?", "&&", "!", "pape_requirements_met?", "(", "auth_time", ")", "?", "t", "(", ":service_provider_requires_reauthentication_last_login_too_long_ago", ")", ":", "t", "(", ":login_to_verify_identity", ")", "session", "[", ":return_to", "]", "=", "proceed_path", "redirect_to", "login_path", "end", "end" ]
Use this as before_filter for every CheckID request based action. Loads the current openid request and cancels if none can be found. The user has to log in, if he has not verified his ownership of the identifier, yet.
[ "Use", "this", "as", "before_filter", "for", "every", "CheckID", "request", "based", "action", ".", "Loads", "the", "current", "openid", "request", "and", "cancels", "if", "none", "can", "be", "found", ".", "The", "user", "has", "to", "log", "in", "if", "he", "has", "not", "verified", "his", "ownership", "of", "the", "identifier", "yet", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L157-L168
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.transform_ax_data
def transform_ax_data(parameters) data = {} parameters.each_pair do |key, details| if details['value'] data["type.#{key}"] = details['type'] data["value.#{key}"] = details['value'] end end data end
ruby
def transform_ax_data(parameters) data = {} parameters.each_pair do |key, details| if details['value'] data["type.#{key}"] = details['type'] data["value.#{key}"] = details['value'] end end data end
[ "def", "transform_ax_data", "(", "parameters", ")", "data", "=", "{", "}", "parameters", ".", "each_pair", "do", "|", "key", ",", "details", "|", "if", "details", "[", "'value'", "]", "data", "[", "\"type.#{key}\"", "]", "=", "details", "[", "'type'", "]", "data", "[", "\"value.#{key}\"", "]", "=", "details", "[", "'value'", "]", "end", "end", "data", "end" ]
Transforms the parameters from the form to valid AX response values
[ "Transforms", "the", "parameters", "from", "the", "form", "to", "valid", "AX", "response", "values" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L190-L199
train
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.render_openid_error
def render_openid_error(exception) error = case exception when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'" else exception.to_s end render :text => h("Invalid OpenID request: #{error}"), :status => 500 end
ruby
def render_openid_error(exception) error = case exception when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'" else exception.to_s end render :text => h("Invalid OpenID request: #{error}"), :status => 500 end
[ "def", "render_openid_error", "(", "exception", ")", "error", "=", "case", "exception", "when", "OpenID", "::", "Server", "::", "MalformedTrustRoot", "then", "\"Malformed trust root '#{exception.to_s}'\"", "else", "exception", ".", "to_s", "end", "render", ":text", "=>", "h", "(", "\"Invalid OpenID request: #{error}\"", ")", ",", ":status", "=>", "500", "end" ]
Renders the exception message as text output
[ "Renders", "the", "exception", "message", "as", "text", "output" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L202-L208
train
mceachen/micro_magick
lib/micro_magick/image.rb
MicroMagick.Image.add_input_option
def add_input_option(option_name, *args) (@input_options ||= []).push(option_name) args.each { |ea| @input_options.push(Shellwords.escape(ea.to_s)) } # Support call chaining: self end
ruby
def add_input_option(option_name, *args) (@input_options ||= []).push(option_name) args.each { |ea| @input_options.push(Shellwords.escape(ea.to_s)) } # Support call chaining: self end
[ "def", "add_input_option", "(", "option_name", ",", "*", "args", ")", "(", "@input_options", "||=", "[", "]", ")", ".", "push", "(", "option_name", ")", "args", ".", "each", "{", "|", "ea", "|", "@input_options", ".", "push", "(", "Shellwords", ".", "escape", "(", "ea", ".", "to_s", ")", ")", "}", "self", "end" ]
If you need to add an option that affects processing of input files, you can use this method.
[ "If", "you", "need", "to", "add", "an", "option", "that", "affects", "processing", "of", "input", "files", "you", "can", "use", "this", "method", "." ]
c4b9259826f16295a561c83e6e084660f4f9229e
https://github.com/mceachen/micro_magick/blob/c4b9259826f16295a561c83e6e084660f4f9229e/lib/micro_magick/image.rb#L17-L23
train
mceachen/micro_magick
lib/micro_magick/image.rb
MicroMagick.Image.square_crop
def square_crop(gravity = 'Center') gravity(gravity) unless gravity.nil? d = [width, height].min crop("#{d}x#{d}+0+0!") end
ruby
def square_crop(gravity = 'Center') gravity(gravity) unless gravity.nil? d = [width, height].min crop("#{d}x#{d}+0+0!") end
[ "def", "square_crop", "(", "gravity", "=", "'Center'", ")", "gravity", "(", "gravity", ")", "unless", "gravity", ".", "nil?", "d", "=", "[", "width", ",", "height", "]", ".", "min", "crop", "(", "\"#{d}x#{d}+0+0!\"", ")", "end" ]
Crop to a square, using the specified gravity.
[ "Crop", "to", "a", "square", "using", "the", "specified", "gravity", "." ]
c4b9259826f16295a561c83e6e084660f4f9229e
https://github.com/mceachen/micro_magick/blob/c4b9259826f16295a561c83e6e084660f4f9229e/lib/micro_magick/image.rb#L55-L59
train
jhass/open_graph_reader
lib/open_graph_reader/base.rb
OpenGraphReader.Base.method_missing
def method_missing(method, *args, &block) name = method.to_s if respond_to_missing? name @bases[name] else super(method, *args, &block) end end
ruby
def method_missing(method, *args, &block) name = method.to_s if respond_to_missing? name @bases[name] else super(method, *args, &block) end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "name", "=", "method", ".", "to_s", "if", "respond_to_missing?", "name", "@bases", "[", "name", "]", "else", "super", "(", "method", ",", "*", "args", ",", "&", "block", ")", "end", "end" ]
Makes the found root objects available. @return [Object]
[ "Makes", "the", "found", "root", "objects", "available", "." ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/base.rb#L61-L68
train
tomharris/random_data
lib/random_data/locations.rb
RandomData.Locations.uk_post_code
def uk_post_code post_towns = %w(BM CB CV LE LI LS KT MK NE OX PL YO) # Can't remember any othes at the moment number_1 = rand(100).to_s number_2 = rand(100).to_s # Easier way to do this? letters = ("AA".."ZZ").to_a.rand return "#{post_towns.rand}#{number_1} #{number_2}#{letters}" end
ruby
def uk_post_code post_towns = %w(BM CB CV LE LI LS KT MK NE OX PL YO) # Can't remember any othes at the moment number_1 = rand(100).to_s number_2 = rand(100).to_s # Easier way to do this? letters = ("AA".."ZZ").to_a.rand return "#{post_towns.rand}#{number_1} #{number_2}#{letters}" end
[ "def", "uk_post_code", "post_towns", "=", "%w(", "BM", "CB", "CV", "LE", "LI", "LS", "KT", "MK", "NE", "OX", "PL", "YO", ")", "number_1", "=", "rand", "(", "100", ")", ".", "to_s", "number_2", "=", "rand", "(", "100", ")", ".", "to_s", "letters", "=", "(", "\"AA\"", "..", "\"ZZ\"", ")", ".", "to_a", ".", "rand", "return", "\"#{post_towns.rand}#{number_1} #{number_2}#{letters}\"", "end" ]
Returns a string providing something in the general form of a UK post code. Like the zip codes, this might not actually be valid. Doesn't cover London whose codes are like "SE1".
[ "Returns", "a", "string", "providing", "something", "in", "the", "general", "form", "of", "a", "UK", "post", "code", ".", "Like", "the", "zip", "codes", "this", "might", "not", "actually", "be", "valid", ".", "Doesn", "t", "cover", "London", "whose", "codes", "are", "like", "SE1", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/locations.rb#L56-L65
train
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/map.rb
GoogleStaticMapsHelper.Map.url
def url raise BuildDataMissing, "We have to have markers, paths or center and zoom set when url is called!" unless can_build? out = "#{API_URL}?" params = [] (REQUIRED_OPTIONS + OPTIONAL_OPTIONS).each do |key| value = send(key) params << "#{key}=#{URI.escape(value.to_s)}" unless value.nil? end out += params.join('&') params = [] grouped_markers.each_pair do |marker_options_as_url_params, markers| markers_locations = markers.map { |m| m.location_to_url }.join('|') params << "markers=#{marker_options_as_url_params}|#{markers_locations}" end out += "&#{params.join('&')}" unless params.empty? params = [] paths.each {|path| params << path.url_params} out += "&#{params.join('&')}" unless params.empty? out end
ruby
def url raise BuildDataMissing, "We have to have markers, paths or center and zoom set when url is called!" unless can_build? out = "#{API_URL}?" params = [] (REQUIRED_OPTIONS + OPTIONAL_OPTIONS).each do |key| value = send(key) params << "#{key}=#{URI.escape(value.to_s)}" unless value.nil? end out += params.join('&') params = [] grouped_markers.each_pair do |marker_options_as_url_params, markers| markers_locations = markers.map { |m| m.location_to_url }.join('|') params << "markers=#{marker_options_as_url_params}|#{markers_locations}" end out += "&#{params.join('&')}" unless params.empty? params = [] paths.each {|path| params << path.url_params} out += "&#{params.join('&')}" unless params.empty? out end
[ "def", "url", "raise", "BuildDataMissing", ",", "\"We have to have markers, paths or center and zoom set when url is called!\"", "unless", "can_build?", "out", "=", "\"#{API_URL}?\"", "params", "=", "[", "]", "(", "REQUIRED_OPTIONS", "+", "OPTIONAL_OPTIONS", ")", ".", "each", "do", "|", "key", "|", "value", "=", "send", "(", "key", ")", "params", "<<", "\"#{key}=#{URI.escape(value.to_s)}\"", "unless", "value", ".", "nil?", "end", "out", "+=", "params", ".", "join", "(", "'&'", ")", "params", "=", "[", "]", "grouped_markers", ".", "each_pair", "do", "|", "marker_options_as_url_params", ",", "markers", "|", "markers_locations", "=", "markers", ".", "map", "{", "|", "m", "|", "m", ".", "location_to_url", "}", ".", "join", "(", "'|'", ")", "params", "<<", "\"markers=#{marker_options_as_url_params}|#{markers_locations}\"", "end", "out", "+=", "\"&#{params.join('&')}\"", "unless", "params", ".", "empty?", "params", "=", "[", "]", "paths", ".", "each", "{", "|", "path", "|", "params", "<<", "path", ".", "url_params", "}", "out", "+=", "\"&#{params.join('&')}\"", "unless", "params", ".", "empty?", "out", "end" ]
Creates a new Map object <tt>:options</tt>:: The options available are the same as described in Google's API documentation[http://code.google.com/apis/maps/documentation/staticmaps/#Usage]. In short, valid options are: <tt>:size</tt>:: The size of the map. Can be a "wxh", [w,h] or {:width => x, :height => y} <tt>:sensor</tt>:: Set to true if your application is using a sensor. See the API doc. <tt>:center</tt>:: The center point of your map. Optional if you add markers or path to the map <tt>:zoom</tt>:: The zoom level you want, also optional as center <tt>:format</tt>:: Defaults to png <tt>:maptype</tt>:: Defaults to roadmap <tt>:mobile</tt>:: Returns map tiles better suited for mobile devices with small screens. <tt>:language</tt>:: The language used in the map Builds up a URL representing the state of this Map object
[ "Creates", "a", "new", "Map", "object" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/map.rb#L50-L74
train
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/map.rb
GoogleStaticMapsHelper.Map.grouped_markers
def grouped_markers markers.inject(Hash.new {|hash, key| hash[key] = []}) do |groups, marker| groups[marker.options_to_url_params] << marker groups end end
ruby
def grouped_markers markers.inject(Hash.new {|hash, key| hash[key] = []}) do |groups, marker| groups[marker.options_to_url_params] << marker groups end end
[ "def", "grouped_markers", "markers", ".", "inject", "(", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "[", "]", "}", ")", "do", "|", "groups", ",", "marker", "|", "groups", "[", "marker", ".", "options_to_url_params", "]", "<<", "marker", "groups", "end", "end" ]
Returns the markers grouped by it's label, color and size. This is handy when building the URL because the API wants us to group together equal markers and just list the position of the markers thereafter in the URL.
[ "Returns", "the", "markers", "grouped", "by", "it", "s", "label", "color", "and", "size", "." ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/map.rb#L89-L94
train
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/map.rb
GoogleStaticMapsHelper.Map.size=
def size=(size) unless size.nil? case size when String width, height = size.split('x') when Array width, height = size when Hash width = size[:width] height = size[:height] else raise "Don't know how to set size from #{size.class}!" end self.width = width if width self.height = height if height end end
ruby
def size=(size) unless size.nil? case size when String width, height = size.split('x') when Array width, height = size when Hash width = size[:width] height = size[:height] else raise "Don't know how to set size from #{size.class}!" end self.width = width if width self.height = height if height end end
[ "def", "size", "=", "(", "size", ")", "unless", "size", ".", "nil?", "case", "size", "when", "String", "width", ",", "height", "=", "size", ".", "split", "(", "'x'", ")", "when", "Array", "width", ",", "height", "=", "size", "when", "Hash", "width", "=", "size", "[", ":width", "]", "height", "=", "size", "[", ":height", "]", "else", "raise", "\"Don't know how to set size from #{size.class}!\"", "end", "self", ".", "width", "=", "width", "if", "width", "self", ".", "height", "=", "height", "if", "height", "end", "end" ]
Sets the size of the map <tt>size</tt>:: Can be a "wxh", [w,h] or {:width => x, :height => y}
[ "Sets", "the", "size", "of", "the", "map" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/map.rb#L144-L161
train
tomharris/random_data
lib/random_data/text.rb
RandomData.Text.alphanumeric
def alphanumeric(size=16) s = "" size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr } s end
ruby
def alphanumeric(size=16) s = "" size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr } s end
[ "def", "alphanumeric", "(", "size", "=", "16", ")", "s", "=", "\"\"", "size", ".", "times", "{", "s", "<<", "(", "i", "=", "Kernel", ".", "rand", "(", "62", ")", ";", "i", "+=", "(", "(", "i", "<", "10", ")", "?", "48", ":", "(", "(", "i", "<", "36", ")", "?", "55", ":", "61", ")", ")", ")", ".", "chr", "}", "s", "end" ]
Methods to create random strings and paragraphs. Returns a string of random upper- and lowercase alphanumeric characters. Accepts a size parameters, defaults to 16 characters. >> Random.alphanumeric "Ke2jdknPYAI8uCXj" >> Random.alphanumeric(5) "7sj7i"
[ "Methods", "to", "create", "random", "strings", "and", "paragraphs", ".", "Returns", "a", "string", "of", "random", "upper", "-", "and", "lowercase", "alphanumeric", "characters", ".", "Accepts", "a", "size", "parameters", "defaults", "to", "16", "characters", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/text.rb#L17-L21
train
tomharris/random_data
lib/random_data/markov.rb
RandomData.MarkovGenerator.insert
def insert(result) # puts "insert called with #{result}" tabindex = Marshal.dump(@state) if @table[tabindex].has_key?(result) @table[tabindex][result] += 1 else @table[tabindex][result] = 1 end # puts "table #{@table.inspect}" next_state(result) end
ruby
def insert(result) # puts "insert called with #{result}" tabindex = Marshal.dump(@state) if @table[tabindex].has_key?(result) @table[tabindex][result] += 1 else @table[tabindex][result] = 1 end # puts "table #{@table.inspect}" next_state(result) end
[ "def", "insert", "(", "result", ")", "tabindex", "=", "Marshal", ".", "dump", "(", "@state", ")", "if", "@table", "[", "tabindex", "]", ".", "has_key?", "(", "result", ")", "@table", "[", "tabindex", "]", "[", "result", "]", "+=", "1", "else", "@table", "[", "tabindex", "]", "[", "result", "]", "=", "1", "end", "next_state", "(", "result", ")", "end" ]
given the next token of input add it to the table
[ "given", "the", "next", "token", "of", "input", "add", "it", "to", "the", "table" ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/markov.rb#L16-L26
train
dennisreimann/masq
app/helpers/masq/personas_helper.rb
Masq.PersonasHelper.countries_for_select
def countries_for_select ::I18nData.countries.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
ruby
def countries_for_select ::I18nData.countries.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
[ "def", "countries_for_select", "::", "I18nData", ".", "countries", ".", "map", "{", "|", "pair", "|", "pair", ".", "reverse", "}", ".", "sort", "{", "|", "x", ",", "y", "|", "x", ".", "first", "<=>", "y", ".", "first", "}", "end" ]
get list of codes and names sorted by country name
[ "get", "list", "of", "codes", "and", "names", "sorted", "by", "country", "name" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/helpers/masq/personas_helper.rb#L6-L8
train
dennisreimann/masq
app/helpers/masq/personas_helper.rb
Masq.PersonasHelper.languages_for_select
def languages_for_select ::I18nData.languages.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
ruby
def languages_for_select ::I18nData.languages.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
[ "def", "languages_for_select", "::", "I18nData", ".", "languages", ".", "map", "{", "|", "pair", "|", "pair", ".", "reverse", "}", ".", "sort", "{", "|", "x", ",", "y", "|", "x", ".", "first", "<=>", "y", ".", "first", "}", "end" ]
get list of codes and names sorted by language name
[ "get", "list", "of", "codes", "and", "names", "sorted", "by", "language", "name" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/helpers/masq/personas_helper.rb#L11-L13
train
qoobaa/vcard
lib/vcard/vcard.rb
Vcard.Vcard.lines
def lines(name=nil) #:yield: Line # FIXME - this would be much easier if #lines was #each, and there was a # different #lines that returned an Enumerator that used #each unless block_given? map do |f| if( !name || f.name?(name) ) f2l(f) else nil end end.compact else each do |f| if( !name || f.name?(name) ) line = f2l(f) if line yield line end end end self end end
ruby
def lines(name=nil) #:yield: Line # FIXME - this would be much easier if #lines was #each, and there was a # different #lines that returned an Enumerator that used #each unless block_given? map do |f| if( !name || f.name?(name) ) f2l(f) else nil end end.compact else each do |f| if( !name || f.name?(name) ) line = f2l(f) if line yield line end end end self end end
[ "def", "lines", "(", "name", "=", "nil", ")", "unless", "block_given?", "map", "do", "|", "f", "|", "if", "(", "!", "name", "||", "f", ".", "name?", "(", "name", ")", ")", "f2l", "(", "f", ")", "else", "nil", "end", "end", ".", "compact", "else", "each", "do", "|", "f", "|", "if", "(", "!", "name", "||", "f", ".", "name?", "(", "name", ")", ")", "line", "=", "f2l", "(", "f", ")", "if", "line", "yield", "line", "end", "end", "end", "self", "end", "end" ]
With no block, returns an Array of Line. If +name+ is specified, the Array will only contain the +Line+s with that +name+. The Array may be empty. If a block is given, each Line will be yielded instead of being returned in an Array.
[ "With", "no", "block", "returns", "an", "Array", "of", "Line", ".", "If", "+", "name", "+", "is", "specified", "the", "Array", "will", "only", "contain", "the", "+", "Line", "+", "s", "with", "that", "+", "name", "+", ".", "The", "Array", "may", "be", "empty", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/vcard.rb#L578-L600
train
qoobaa/vcard
lib/vcard/vcard.rb
Vcard.Vcard.delete_if
def delete_if #:nodoc: :yield: line # Do in two steps to not mess up progress through the enumerator. rm = [] each do |f| line = f2l(f) if line && yield(line) rm << f # Hack - because we treat N and FN as one field if f.name? "N" rm << field("FN") end end end rm.each do |f| @fields.delete( f ) @cache.delete( f ) end end
ruby
def delete_if #:nodoc: :yield: line # Do in two steps to not mess up progress through the enumerator. rm = [] each do |f| line = f2l(f) if line && yield(line) rm << f # Hack - because we treat N and FN as one field if f.name? "N" rm << field("FN") end end end rm.each do |f| @fields.delete( f ) @cache.delete( f ) end end
[ "def", "delete_if", "rm", "=", "[", "]", "each", "do", "|", "f", "|", "line", "=", "f2l", "(", "f", ")", "if", "line", "&&", "yield", "(", "line", ")", "rm", "<<", "f", "if", "f", ".", "name?", "\"N\"", "rm", "<<", "field", "(", "\"FN\"", ")", "end", "end", "end", "rm", ".", "each", "do", "|", "f", "|", "@fields", ".", "delete", "(", "f", ")", "@cache", ".", "delete", "(", "f", ")", "end", "end" ]
Delete +line+ if block yields true.
[ "Delete", "+", "line", "+", "if", "block", "yields", "true", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/vcard.rb#L966-L987
train
ma2gedev/breadcrumble
lib/breadcrumble/action_controller.rb
Breadcrumble.ActionController.add_breadcrumb_to
def add_breadcrumb_to(name, url, trail_index) breadcrumb_trails @breadcrumb_trails[trail_index] ||= [] @breadcrumb_trails[trail_index] << { name: case name when Proc then name.call(self) else name end, url: case url when Proc then url.call(self) else url ? url_for(url) : nil end } end
ruby
def add_breadcrumb_to(name, url, trail_index) breadcrumb_trails @breadcrumb_trails[trail_index] ||= [] @breadcrumb_trails[trail_index] << { name: case name when Proc then name.call(self) else name end, url: case url when Proc then url.call(self) else url ? url_for(url) : nil end } end
[ "def", "add_breadcrumb_to", "(", "name", ",", "url", ",", "trail_index", ")", "breadcrumb_trails", "@breadcrumb_trails", "[", "trail_index", "]", "||=", "[", "]", "@breadcrumb_trails", "[", "trail_index", "]", "<<", "{", "name", ":", "case", "name", "when", "Proc", "then", "name", ".", "call", "(", "self", ")", "else", "name", "end", ",", "url", ":", "case", "url", "when", "Proc", "then", "url", ".", "call", "(", "self", ")", "else", "url", "?", "url_for", "(", "url", ")", ":", "nil", "end", "}", "end" ]
Add a breadcrumb to breadcrumb trail. @param trail_index index of breadcrumb trail @example add_breadcrumb_to("level 1", "level 1 url", 0)
[ "Add", "a", "breadcrumb", "to", "breadcrumb", "trail", "." ]
6a274b9b881d74aa69a8c3cf248fa73bacfd1d46
https://github.com/ma2gedev/breadcrumble/blob/6a274b9b881d74aa69a8c3cf248fa73bacfd1d46/lib/breadcrumble/action_controller.rb#L57-L70
train
dennisreimann/masq
lib/masq/authenticated_system.rb
Masq.AuthenticatedSystem.current_account=
def current_account=(new_account) if self.auth_type_used != :basic session[:account_id] = (new_account.nil? || new_account.is_a?(Symbol)) ? nil : new_account.id end @current_account = new_account || :false end
ruby
def current_account=(new_account) if self.auth_type_used != :basic session[:account_id] = (new_account.nil? || new_account.is_a?(Symbol)) ? nil : new_account.id end @current_account = new_account || :false end
[ "def", "current_account", "=", "(", "new_account", ")", "if", "self", ".", "auth_type_used", "!=", ":basic", "session", "[", ":account_id", "]", "=", "(", "new_account", ".", "nil?", "||", "new_account", ".", "is_a?", "(", "Symbol", ")", ")", "?", "nil", ":", "new_account", ".", "id", "end", "@current_account", "=", "new_account", "||", ":false", "end" ]
Store the given account id in the session.
[ "Store", "the", "given", "account", "id", "in", "the", "session", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/authenticated_system.rb#L17-L22
train
dennisreimann/masq
lib/masq/authenticated_system.rb
Masq.AuthenticatedSystem.access_denied
def access_denied respond_to do |format| format.html do store_location redirect_to login_path end format.any do request_http_basic_authentication 'Web Password' end end end
ruby
def access_denied respond_to do |format| format.html do store_location redirect_to login_path end format.any do request_http_basic_authentication 'Web Password' end end end
[ "def", "access_denied", "respond_to", "do", "|", "format", "|", "format", ".", "html", "do", "store_location", "redirect_to", "login_path", "end", "format", ".", "any", "do", "request_http_basic_authentication", "'Web Password'", "end", "end", "end" ]
Redirect as appropriate when an access request fails. The default action is to redirect to the login screen. Override this method in your controllers if you want to have special behavior in case the account is not authorized to access the requested action. For example, a popup window might simply close itself.
[ "Redirect", "as", "appropriate", "when", "an", "access", "request", "fails", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/authenticated_system.rb#L66-L76
train
jhass/open_graph_reader
lib/open_graph_reader/object.rb
OpenGraphReader.Object.[]=
def []= name, value if property?(name) public_send "#{name}=", value elsif OpenGraphReader.config.strict raise UndefinedPropertyError, "Undefined property #{name} on #{inspect}" end end
ruby
def []= name, value if property?(name) public_send "#{name}=", value elsif OpenGraphReader.config.strict raise UndefinedPropertyError, "Undefined property #{name} on #{inspect}" end end
[ "def", "[]=", "name", ",", "value", "if", "property?", "(", "name", ")", "public_send", "\"#{name}=\"", ",", "value", "elsif", "OpenGraphReader", ".", "config", ".", "strict", "raise", "UndefinedPropertyError", ",", "\"Undefined property #{name} on #{inspect}\"", "end", "end" ]
Set the property to the given value. @api private @param [#to_s] name @param [String, Object] value @raise [UndefinedPropertyError] If the requested property is undefined.
[ "Set", "the", "property", "to", "the", "given", "value", "." ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/object.rb#L81-L87
train
tomharris/random_data
lib/random_data/dates.rb
RandomData.Dates.date
def date(dayrange=10) if dayrange.is_a?(Range) offset = rand(dayrange.max-dayrange.min) + dayrange.min else offset = rand(dayrange*2) - dayrange end Date.today + offset end
ruby
def date(dayrange=10) if dayrange.is_a?(Range) offset = rand(dayrange.max-dayrange.min) + dayrange.min else offset = rand(dayrange*2) - dayrange end Date.today + offset end
[ "def", "date", "(", "dayrange", "=", "10", ")", "if", "dayrange", ".", "is_a?", "(", "Range", ")", "offset", "=", "rand", "(", "dayrange", ".", "max", "-", "dayrange", ".", "min", ")", "+", "dayrange", ".", "min", "else", "offset", "=", "rand", "(", "dayrange", "*", "2", ")", "-", "dayrange", "end", "Date", ".", "today", "+", "offset", "end" ]
Returns a date within a specified range of days. If dayrange is an Integer, then the date returned will be plus or minus half what you specify. The default is ten days, so by default you will get a date within plus or minus five days of today. If dayrange is a Range, then you will get a date the falls between that range Example: Random.date # => a Date +/- 5 days of today Random.date(20) # => a Date +/- 10 days of today Random.date(-60..-30) # => a Date between 60 days ago and 30 days ago
[ "Returns", "a", "date", "within", "a", "specified", "range", "of", "days", ".", "If", "dayrange", "is", "an", "Integer", "then", "the", "date", "returned", "will", "be", "plus", "or", "minus", "half", "what", "you", "specify", ".", "The", "default", "is", "ten", "days", "so", "by", "default", "you", "will", "get", "a", "date", "within", "plus", "or", "minus", "five", "days", "of", "today", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/dates.rb#L21-L28
train
tomharris/random_data
lib/random_data/dates.rb
RandomData.Dates.date_between
def date_between(range) min_date = range.min.is_a?(Date) ? range.min : Date.parse(range.min) max_date = range.max.is_a?(Date) ? range.max : Date.parse(range.max) diff = (max_date - min_date).to_i min_date + rand(diff) end
ruby
def date_between(range) min_date = range.min.is_a?(Date) ? range.min : Date.parse(range.min) max_date = range.max.is_a?(Date) ? range.max : Date.parse(range.max) diff = (max_date - min_date).to_i min_date + rand(diff) end
[ "def", "date_between", "(", "range", ")", "min_date", "=", "range", ".", "min", ".", "is_a?", "(", "Date", ")", "?", "range", ".", "min", ":", "Date", ".", "parse", "(", "range", ".", "min", ")", "max_date", "=", "range", ".", "max", ".", "is_a?", "(", "Date", ")", "?", "range", ".", "max", ":", "Date", ".", "parse", "(", "range", ".", "max", ")", "diff", "=", "(", "max_date", "-", "min_date", ")", ".", "to_i", "min_date", "+", "rand", "(", "diff", ")", "end" ]
Returns a date within the specified Range. The Range can be Date or String objects. Example: min = Date.parse('1966-11-15') max = Date.parse('1990-01-01') Random.date(min..max) # => a Date between 11/15/1996 and 1/1/1990 Random.date('1966-11-15'..'1990-01-01') # => a Date between 11/15/1996 and 1/1/1990
[ "Returns", "a", "date", "within", "the", "specified", "Range", ".", "The", "Range", "can", "be", "Date", "or", "String", "objects", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/dates.rb#L38-L44
train
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/path.rb
GoogleStaticMapsHelper.Path.url_params
def url_params # :nodoc: raise BuildDataMissing, "Need at least 2 points to create a path!" unless can_build? out = 'path=' path_params = OPTIONAL_OPTIONS.inject([]) do |path_params, attribute| value = send(attribute) path_params << "#{attribute}:#{URI.escape(value.to_s)}" unless value.nil? path_params end.join('|') out += "#{path_params}|" unless path_params.empty? out += encoded_url_points if encoding_points? out += unencoded_url_points unless encoding_points? out end
ruby
def url_params # :nodoc: raise BuildDataMissing, "Need at least 2 points to create a path!" unless can_build? out = 'path=' path_params = OPTIONAL_OPTIONS.inject([]) do |path_params, attribute| value = send(attribute) path_params << "#{attribute}:#{URI.escape(value.to_s)}" unless value.nil? path_params end.join('|') out += "#{path_params}|" unless path_params.empty? out += encoded_url_points if encoding_points? out += unencoded_url_points unless encoding_points? out end
[ "def", "url_params", "raise", "BuildDataMissing", ",", "\"Need at least 2 points to create a path!\"", "unless", "can_build?", "out", "=", "'path='", "path_params", "=", "OPTIONAL_OPTIONS", ".", "inject", "(", "[", "]", ")", "do", "|", "path_params", ",", "attribute", "|", "value", "=", "send", "(", "attribute", ")", "path_params", "<<", "\"#{attribute}:#{URI.escape(value.to_s)}\"", "unless", "value", ".", "nil?", "path_params", "end", ".", "join", "(", "'|'", ")", "out", "+=", "\"#{path_params}|\"", "unless", "path_params", ".", "empty?", "out", "+=", "encoded_url_points", "if", "encoding_points?", "out", "+=", "unencoded_url_points", "unless", "encoding_points?", "out", "end" ]
Creates a new Path which you can push points on to to make up lines or polygons The following options are available, for more information see the Google API documentation[http://code.google.com/apis/maps/documentation/staticmaps/#Paths]. <tt>:weight</tt>:: The weight is the thickness of the line, defaults to 5 <tt>:color</tt>:: The color of the border can either be a textual representation like red, green, blue, black etc or as a 24-bit (0xAABBCC) or 32-bit hex value (0xAABBCCDD). When 32-bit values are given the two last bits will represent the alpha transparency value. <tt>:fillcolor</tt>:: With the fill color set you'll get a polygon in the map. The color value can be the same as described in the <tt>:color</tt>. When used, the static map will automatically create a closed shape. <tt>:points</tt>:: An array of points. You can mix objects responding to lng and lat, and a Hash with lng and lat keys. <tt>:encode_points:: A flag which tells us if we should encode the points in this path or not. Defaults to <tt>true</tt> Returns a string representation of this Path Used by the Map when building the URL
[ "Creates", "a", "new", "Path", "which", "you", "can", "push", "points", "on", "to", "to", "make", "up", "lines", "or", "polygons" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/path.rb#L42-L57
train
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/path.rb
GoogleStaticMapsHelper.Path.points=
def points=(array) raise ArgumentError unless array.is_a? Array @points = [] array.each {|point| self << point} end
ruby
def points=(array) raise ArgumentError unless array.is_a? Array @points = [] array.each {|point| self << point} end
[ "def", "points", "=", "(", "array", ")", "raise", "ArgumentError", "unless", "array", ".", "is_a?", "Array", "@points", "=", "[", "]", "array", ".", "each", "{", "|", "point", "|", "self", "<<", "point", "}", "end" ]
Sets the points of this Path. *WARNING* Using this method will clear out any points which might be set.
[ "Sets", "the", "points", "of", "this", "Path", "." ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/path.rb#L65-L69
train
dennisreimann/masq
lib/masq/openid_server_system.rb
Masq.OpenidServerSystem.add_pape
def add_pape(resp, policies = [], nist_auth_level = 0, auth_time = nil) if papereq = OpenID::PAPE::Request.from_openid_request(openid_request) paperesp = OpenID::PAPE::Response.new policies.each { |p| paperesp.add_policy_uri(p) } paperesp.nist_auth_level = nist_auth_level paperesp.auth_time = auth_time.utc.iso8601 resp.add_extension(paperesp) end resp end
ruby
def add_pape(resp, policies = [], nist_auth_level = 0, auth_time = nil) if papereq = OpenID::PAPE::Request.from_openid_request(openid_request) paperesp = OpenID::PAPE::Response.new policies.each { |p| paperesp.add_policy_uri(p) } paperesp.nist_auth_level = nist_auth_level paperesp.auth_time = auth_time.utc.iso8601 resp.add_extension(paperesp) end resp end
[ "def", "add_pape", "(", "resp", ",", "policies", "=", "[", "]", ",", "nist_auth_level", "=", "0", ",", "auth_time", "=", "nil", ")", "if", "papereq", "=", "OpenID", "::", "PAPE", "::", "Request", ".", "from_openid_request", "(", "openid_request", ")", "paperesp", "=", "OpenID", "::", "PAPE", "::", "Response", ".", "new", "policies", ".", "each", "{", "|", "p", "|", "paperesp", ".", "add_policy_uri", "(", "p", ")", "}", "paperesp", ".", "nist_auth_level", "=", "nist_auth_level", "paperesp", ".", "auth_time", "=", "auth_time", ".", "utc", ".", "iso8601", "resp", ".", "add_extension", "(", "paperesp", ")", "end", "resp", "end" ]
Adds PAPE information for your server to an OpenID response.
[ "Adds", "PAPE", "information", "for", "your", "server", "to", "an", "OpenID", "response", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/openid_server_system.rb#L74-L83
train
dennisreimann/masq
lib/masq/openid_server_system.rb
Masq.OpenidServerSystem.render_openid_response
def render_openid_response(resp) signed_response = openid_server.signatory.sign(resp) if resp.needs_signing web_response = openid_server.encode_response(resp) case web_response.code when OpenID::Server::HTTP_OK then render(:text => web_response.body, :status => 200) when OpenID::Server::HTTP_REDIRECT then redirect_to(web_response.headers['location']) else render(:text => web_response.body, :status => 400) end end
ruby
def render_openid_response(resp) signed_response = openid_server.signatory.sign(resp) if resp.needs_signing web_response = openid_server.encode_response(resp) case web_response.code when OpenID::Server::HTTP_OK then render(:text => web_response.body, :status => 200) when OpenID::Server::HTTP_REDIRECT then redirect_to(web_response.headers['location']) else render(:text => web_response.body, :status => 400) end end
[ "def", "render_openid_response", "(", "resp", ")", "signed_response", "=", "openid_server", ".", "signatory", ".", "sign", "(", "resp", ")", "if", "resp", ".", "needs_signing", "web_response", "=", "openid_server", ".", "encode_response", "(", "resp", ")", "case", "web_response", ".", "code", "when", "OpenID", "::", "Server", "::", "HTTP_OK", "then", "render", "(", ":text", "=>", "web_response", ".", "body", ",", ":status", "=>", "200", ")", "when", "OpenID", "::", "Server", "::", "HTTP_REDIRECT", "then", "redirect_to", "(", "web_response", ".", "headers", "[", "'location'", "]", ")", "else", "render", "(", ":text", "=>", "web_response", ".", "body", ",", ":status", "=>", "400", ")", "end", "end" ]
Renders the final response output
[ "Renders", "the", "final", "response", "output" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/openid_server_system.rb#L92-L100
train
dennisreimann/masq
app/models/masq/persona.rb
Masq.Persona.property
def property(type) prop = Persona.mappings.detect { |i| i[1].include?(type) } prop ? self.send(prop[0]).to_s : nil end
ruby
def property(type) prop = Persona.mappings.detect { |i| i[1].include?(type) } prop ? self.send(prop[0]).to_s : nil end
[ "def", "property", "(", "type", ")", "prop", "=", "Persona", ".", "mappings", ".", "detect", "{", "|", "i", "|", "i", "[", "1", "]", ".", "include?", "(", "type", ")", "}", "prop", "?", "self", ".", "send", "(", "prop", "[", "0", "]", ")", ".", "to_s", ":", "nil", "end" ]
Returns the personas attribute for the given SReg name or AX Type URI
[ "Returns", "the", "personas", "attribute", "for", "the", "given", "SReg", "name", "or", "AX", "Type", "URI" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/persona.rb#L26-L29
train
ustasb/pandata
lib/pandata/cli.rb
Pandata.CLI.format_data
def format_data(data, json = false) if json JSON.generate(data) else data.map do |category, cat_data| # Capitalize each word in the category symbol. # e.g. :liked_tracks becomes 'Liked Tracks' title = category.to_s.split('_').map(&:capitalize).join(' ') output = if cat_data.empty? " ** No Data **\n" else case category when /liked_tracks/ formatter.tracks(cat_data) when /liked_artists|liked_stations/ formatter.sort_list(cat_data) when :liked_albums formatter.albums(cat_data) when /following|followers/ formatter.followx(cat_data) end end "#{title}:\n#{output}" end.join end end
ruby
def format_data(data, json = false) if json JSON.generate(data) else data.map do |category, cat_data| # Capitalize each word in the category symbol. # e.g. :liked_tracks becomes 'Liked Tracks' title = category.to_s.split('_').map(&:capitalize).join(' ') output = if cat_data.empty? " ** No Data **\n" else case category when /liked_tracks/ formatter.tracks(cat_data) when /liked_artists|liked_stations/ formatter.sort_list(cat_data) when :liked_albums formatter.albums(cat_data) when /following|followers/ formatter.followx(cat_data) end end "#{title}:\n#{output}" end.join end end
[ "def", "format_data", "(", "data", ",", "json", "=", "false", ")", "if", "json", "JSON", ".", "generate", "(", "data", ")", "else", "data", ".", "map", "do", "|", "category", ",", "cat_data", "|", "title", "=", "category", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "(", "&", ":capitalize", ")", ".", "join", "(", "' '", ")", "output", "=", "if", "cat_data", ".", "empty?", "\" ** No Data **\\n\"", "else", "case", "category", "when", "/", "/", "formatter", ".", "tracks", "(", "cat_data", ")", "when", "/", "/", "formatter", ".", "sort_list", "(", "cat_data", ")", "when", ":liked_albums", "formatter", ".", "albums", "(", "cat_data", ")", "when", "/", "/", "formatter", ".", "followx", "(", "cat_data", ")", "end", "end", "\"#{title}:\\n#{output}\"", "end", ".", "join", "end", "end" ]
Formats data as a string list or JSON. @param data [Hash] @param json [Boolean] @return [String]
[ "Formats", "data", "as", "a", "string", "list", "or", "JSON", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/cli.rb#L75-L102
train
ustasb/pandata
lib/pandata/cli.rb
Pandata.CLI.download_data
def download_data scraper_data = {} @data_to_get.each do |data_category| if /liked_(.*)/ =~ data_category argument = $1.to_sym # :tracks, :artists, :stations or :albums scraper_data[data_category] = @scraper.public_send(:likes, argument) else scraper_data[data_category] = @scraper.public_send(data_category) end end scraper_data end
ruby
def download_data scraper_data = {} @data_to_get.each do |data_category| if /liked_(.*)/ =~ data_category argument = $1.to_sym # :tracks, :artists, :stations or :albums scraper_data[data_category] = @scraper.public_send(:likes, argument) else scraper_data[data_category] = @scraper.public_send(data_category) end end scraper_data end
[ "def", "download_data", "scraper_data", "=", "{", "}", "@data_to_get", ".", "each", "do", "|", "data_category", "|", "if", "/", "/", "=~", "data_category", "argument", "=", "$1", ".", "to_sym", "scraper_data", "[", "data_category", "]", "=", "@scraper", ".", "public_send", "(", ":likes", ",", "argument", ")", "else", "scraper_data", "[", "data_category", "]", "=", "@scraper", ".", "public_send", "(", "data_category", ")", "end", "end", "scraper_data", "end" ]
Downloads the user's desired data. @return [Hash]
[ "Downloads", "the", "user", "s", "desired", "data", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/cli.rb#L106-L119
train
ustasb/pandata
lib/pandata/cli.rb
Pandata.CLI.scraper_for
def scraper_for(user_id) scraper = Pandata::Scraper.get(user_id) if scraper.kind_of?(Array) log "No exact match for '#{user_id}'." unless scraper.empty? log "\nWebname results for '#{user_id}':\n#{formatter.list(scraper)}" end raise PandataError, "Could not create a scraper for '#{user_id}'." end scraper end
ruby
def scraper_for(user_id) scraper = Pandata::Scraper.get(user_id) if scraper.kind_of?(Array) log "No exact match for '#{user_id}'." unless scraper.empty? log "\nWebname results for '#{user_id}':\n#{formatter.list(scraper)}" end raise PandataError, "Could not create a scraper for '#{user_id}'." end scraper end
[ "def", "scraper_for", "(", "user_id", ")", "scraper", "=", "Pandata", "::", "Scraper", ".", "get", "(", "user_id", ")", "if", "scraper", ".", "kind_of?", "(", "Array", ")", "log", "\"No exact match for '#{user_id}'.\"", "unless", "scraper", ".", "empty?", "log", "\"\\nWebname results for '#{user_id}':\\n#{formatter.list(scraper)}\"", "end", "raise", "PandataError", ",", "\"Could not create a scraper for '#{user_id}'.\"", "end", "scraper", "end" ]
Returns a scraper for the user's id. @param user_id [String] webname or email @return [Pandata::Scraper]
[ "Returns", "a", "scraper", "for", "the", "user", "s", "id", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/cli.rb#L124-L138
train
dennisreimann/masq
app/models/masq/site.rb
Masq.Site.ax_fetch=
def ax_fetch=(props) props.each_pair do |property, details| release_policies.build(:property => property, :type_identifier => details['type']) if details['value'] end end
ruby
def ax_fetch=(props) props.each_pair do |property, details| release_policies.build(:property => property, :type_identifier => details['type']) if details['value'] end end
[ "def", "ax_fetch", "=", "(", "props", ")", "props", ".", "each_pair", "do", "|", "property", ",", "details", "|", "release_policies", ".", "build", "(", ":property", "=>", "property", ",", ":type_identifier", "=>", "details", "[", "'type'", "]", ")", "if", "details", "[", "'value'", "]", "end", "end" ]
Generates a release policy for each property that has a value. This setter is used in the server controllers complete action to set the attributes recieved from the decision form.
[ "Generates", "a", "release", "policy", "for", "each", "property", "that", "has", "a", "value", ".", "This", "setter", "is", "used", "in", "the", "server", "controllers", "complete", "action", "to", "set", "the", "attributes", "recieved", "from", "the", "decision", "form", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/site.rb#L29-L33
train
dennisreimann/masq
app/models/masq/site.rb
Masq.Site.sreg_properties
def sreg_properties props = {} release_policies.each do |rp| is_sreg = (rp.property == rp.type_identifier) props[rp.property] = persona.property(rp.property) if is_sreg end props end
ruby
def sreg_properties props = {} release_policies.each do |rp| is_sreg = (rp.property == rp.type_identifier) props[rp.property] = persona.property(rp.property) if is_sreg end props end
[ "def", "sreg_properties", "props", "=", "{", "}", "release_policies", ".", "each", "do", "|", "rp", "|", "is_sreg", "=", "(", "rp", ".", "property", "==", "rp", ".", "type_identifier", ")", "props", "[", "rp", ".", "property", "]", "=", "persona", ".", "property", "(", "rp", ".", "property", ")", "if", "is_sreg", "end", "props", "end" ]
Returns a hash with all released SReg properties. SReg properties have a type_identifier matching their property name
[ "Returns", "a", "hash", "with", "all", "released", "SReg", "properties", ".", "SReg", "properties", "have", "a", "type_identifier", "matching", "their", "property", "name" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/site.rb#L46-L53
train
dennisreimann/masq
app/models/masq/site.rb
Masq.Site.ax_properties
def ax_properties props = {} release_policies.each do |rp| if rp.type_identifier.match("://") props["type.#{rp.property}"] = rp.type_identifier props["value.#{rp.property}"] = persona.property(rp.type_identifier ) end end props end
ruby
def ax_properties props = {} release_policies.each do |rp| if rp.type_identifier.match("://") props["type.#{rp.property}"] = rp.type_identifier props["value.#{rp.property}"] = persona.property(rp.type_identifier ) end end props end
[ "def", "ax_properties", "props", "=", "{", "}", "release_policies", ".", "each", "do", "|", "rp", "|", "if", "rp", ".", "type_identifier", ".", "match", "(", "\"://\"", ")", "props", "[", "\"type.#{rp.property}\"", "]", "=", "rp", ".", "type_identifier", "props", "[", "\"value.#{rp.property}\"", "]", "=", "persona", ".", "property", "(", "rp", ".", "type_identifier", ")", "end", "end", "props", "end" ]
Returns a hash with all released AX properties. AX properties have an URL as type_identifier.
[ "Returns", "a", "hash", "with", "all", "released", "AX", "properties", ".", "AX", "properties", "have", "an", "URL", "as", "type_identifier", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/site.rb#L57-L66
train
ustasb/pandata
lib/pandata/data_formatter.rb
Pandata.DataFormatter.custom_sort
def custom_sort(enumerable) sorted_array = enumerable.sort_by do |key, _| key.sub(/^the\s*/i, '').downcase end # sort_by() returns an array when called on hashes. if enumerable.kind_of?(Hash) # Rebuild the hash. sorted_hash = {} sorted_array.each { |item| sorted_hash[item[0]] = item[1] } sorted_hash else sorted_array end end
ruby
def custom_sort(enumerable) sorted_array = enumerable.sort_by do |key, _| key.sub(/^the\s*/i, '').downcase end # sort_by() returns an array when called on hashes. if enumerable.kind_of?(Hash) # Rebuild the hash. sorted_hash = {} sorted_array.each { |item| sorted_hash[item[0]] = item[1] } sorted_hash else sorted_array end end
[ "def", "custom_sort", "(", "enumerable", ")", "sorted_array", "=", "enumerable", ".", "sort_by", "do", "|", "key", ",", "_", "|", "key", ".", "sub", "(", "/", "\\s", "/i", ",", "''", ")", ".", "downcase", "end", "if", "enumerable", ".", "kind_of?", "(", "Hash", ")", "sorted_hash", "=", "{", "}", "sorted_array", ".", "each", "{", "|", "item", "|", "sorted_hash", "[", "item", "[", "0", "]", "]", "=", "item", "[", "1", "]", "}", "sorted_hash", "else", "sorted_array", "end", "end" ]
Sorts alphabetically ignoring the initial 'The' when sorting strings. Also case-insensitive to prevent lowercase names from being sorted last. @param enumerable [Array, Hash] @return [Array, Hash]
[ "Sorts", "alphabetically", "ignoring", "the", "initial", "The", "when", "sorting", "strings", ".", "Also", "case", "-", "insensitive", "to", "prevent", "lowercase", "names", "from", "being", "sorted", "last", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/data_formatter.rb#L53-L67
train
tomharris/random_data
lib/random_data/array_randomizer.rb
RandomData.ArrayRandomizer.roulette
def roulette(k=1) wheel = [] weight = 0 # Create the cumulative array. self.each do |x| raise "Illegal negative weight #{x}" if x < 0 wheel.push(weight += x) end # print "wheel is #{wheel.inspect}\n"; # print "weight is #{weight.inspect}\n"; raise "Array had all zero weights" if weight.zero? wheel.push(weight + 1) #Add extra element if block_given? k.times do r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| if wheel[i+1] > roll yield i break end # if end # upto end # if block_given? return nil else r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| return i if wheel[i+1] > roll end end end
ruby
def roulette(k=1) wheel = [] weight = 0 # Create the cumulative array. self.each do |x| raise "Illegal negative weight #{x}" if x < 0 wheel.push(weight += x) end # print "wheel is #{wheel.inspect}\n"; # print "weight is #{weight.inspect}\n"; raise "Array had all zero weights" if weight.zero? wheel.push(weight + 1) #Add extra element if block_given? k.times do r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| if wheel[i+1] > roll yield i break end # if end # upto end # if block_given? return nil else r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| return i if wheel[i+1] > roll end end end
[ "def", "roulette", "(", "k", "=", "1", ")", "wheel", "=", "[", "]", "weight", "=", "0", "self", ".", "each", "do", "|", "x", "|", "raise", "\"Illegal negative weight #{x}\"", "if", "x", "<", "0", "wheel", ".", "push", "(", "weight", "+=", "x", ")", "end", "raise", "\"Array had all zero weights\"", "if", "weight", ".", "zero?", "wheel", ".", "push", "(", "weight", "+", "1", ")", "if", "block_given?", "k", ".", "times", "do", "r", "=", "Kernel", ".", "rand", "(", ")", "roll", "=", "weight", ".", "to_f", "*", "r", "0", ".", "upto", "(", "self", ".", "size", "-", "1", ")", "do", "|", "i", "|", "if", "wheel", "[", "i", "+", "1", "]", ">", "roll", "yield", "i", "break", "end", "end", "end", "return", "nil", "else", "r", "=", "Kernel", ".", "rand", "(", ")", "roll", "=", "weight", ".", "to_f", "*", "r", "0", ".", "upto", "(", "self", ".", "size", "-", "1", ")", "do", "|", "i", "|", "return", "i", "if", "wheel", "[", "i", "+", "1", "]", ">", "roll", "end", "end", "end" ]
Takes an array of non-negative weights and returns the index selected by a roulette wheel weighted according to those weights. If a block is given then k is used to determine how many times the block is called. In this case nil is returned.
[ "Takes", "an", "array", "of", "non", "-", "negative", "weights", "and", "returns", "the", "index", "selected", "by", "a", "roulette", "wheel", "weighted", "according", "to", "those", "weights", ".", "If", "a", "block", "is", "given", "then", "k", "is", "used", "to", "determine", "how", "many", "times", "the", "block", "is", "called", ".", "In", "this", "case", "nil", "is", "returned", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/array_randomizer.rb#L22-L57
train
jhass/open_graph_reader
lib/open_graph_reader/fetcher.rb
OpenGraphReader.Fetcher.body
def body fetch_body unless fetched? raise NoOpenGraphDataError, "No response body received for #{@uri}" if fetch_failed? raise NoOpenGraphDataError, "Did not receive a HTML site at #{@uri}" unless html? @get_response.body end
ruby
def body fetch_body unless fetched? raise NoOpenGraphDataError, "No response body received for #{@uri}" if fetch_failed? raise NoOpenGraphDataError, "Did not receive a HTML site at #{@uri}" unless html? @get_response.body end
[ "def", "body", "fetch_body", "unless", "fetched?", "raise", "NoOpenGraphDataError", ",", "\"No response body received for #{@uri}\"", "if", "fetch_failed?", "raise", "NoOpenGraphDataError", ",", "\"Did not receive a HTML site at #{@uri}\"", "unless", "html?", "@get_response", ".", "body", "end" ]
Retrieve the body @todo Custom error class @raise [ArgumentError] The received content does not seems to be HTML. @return [String]
[ "Retrieve", "the", "body" ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/fetcher.rb#L70-L75
train
jhass/open_graph_reader
lib/open_graph_reader/fetcher.rb
OpenGraphReader.Fetcher.html?
def html? fetch_headers unless fetched_headers? response = @get_response || @head_response return false if fetch_failed? return false unless response return false unless response.success? return false unless response["content-type"] response["content-type"].include? "text/html" end
ruby
def html? fetch_headers unless fetched_headers? response = @get_response || @head_response return false if fetch_failed? return false unless response return false unless response.success? return false unless response["content-type"] response["content-type"].include? "text/html" end
[ "def", "html?", "fetch_headers", "unless", "fetched_headers?", "response", "=", "@get_response", "||", "@head_response", "return", "false", "if", "fetch_failed?", "return", "false", "unless", "response", "return", "false", "unless", "response", ".", "success?", "return", "false", "unless", "response", "[", "\"content-type\"", "]", "response", "[", "\"content-type\"", "]", ".", "include?", "\"text/html\"", "end" ]
Whether the target URI seems to return HTML @return [Bool]
[ "Whether", "the", "target", "URI", "seems", "to", "return", "HTML" ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/fetcher.rb#L80-L88
train